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 /// @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 );
206 $data = UtfNormal
::cleanUp( $data );
212 * Fetch a value from the given array or return $default if it's not set.
215 * @param $name string
216 * @param $default mixed
219 private function getGPCVal( $arr, $name, $default ) {
220 # PHP is so nice to not touch input data, except sometimes:
221 # http://us2.php.net/variables.external#language.variables.external.dot-in-names
222 # Work around PHP *feature* to avoid *bugs* elsewhere.
223 $name = strtr( $name, '.', '_' );
224 if( isset( $arr[$name] ) ) {
227 if( isset( $_GET[$name] ) && !is_array( $data ) ) {
228 # Check for alternate/legacy character encoding.
229 if( isset( $wgContLang ) ) {
230 $data = $wgContLang->checkTitleEncoding( $data );
233 $data = $this->normalizeUnicode( $data );
242 * Fetch a scalar from the input or return $default if it's not set.
243 * Returns a string. Arrays are discarded. Useful for
244 * non-freeform text inputs (e.g. predefined internal text keys
245 * selected by a drop-down menu). For freeform input, see getText().
247 * @param $name string
248 * @param $default string: optional default (or NULL)
251 public function getVal( $name, $default = NULL ) {
252 $val = $this->getGPCVal( $this->data
, $name, $default );
253 if( is_array( $val ) ) {
256 if( is_null( $val ) ) {
264 * Set an aribtrary value into our get/post data.
265 * @param $key string Key name to use
266 * @param $value mixed Value to set
267 * @return mixed old value if one was present, null otherwise
269 public function setVal( $key, $value ) {
270 $ret = isset( $this->data
[$key] ) ?
$this->data
[$key] : null;
271 $this->data
[$key] = $value;
276 * Fetch an array from the input or return $default if it's not set.
277 * If source was scalar, will return an array with a single element.
278 * If no source and no default, returns NULL.
280 * @param $name string
281 * @param $default array: optional default (or NULL)
284 public function getArray( $name, $default = NULL ) {
285 $val = $this->getGPCVal( $this->data
, $name, $default );
286 if( is_null( $val ) ) {
294 * Fetch an array of integers, or return $default if it's not set.
295 * If source was scalar, will return an array with a single element.
296 * If no source and no default, returns NULL.
297 * If an array is returned, contents are guaranteed to be integers.
299 * @param $name string
300 * @param $default array: option default (or NULL)
301 * @return array of ints
303 public function getIntArray( $name, $default = NULL ) {
304 $val = $this->getArray( $name, $default );
305 if( is_array( $val ) ) {
306 $val = array_map( 'intval', $val );
312 * Fetch an integer value from the input or return $default if not set.
313 * Guaranteed to return an integer; non-numeric input will typically
315 * @param $name string
316 * @param $default int
319 public function getInt( $name, $default = 0 ) {
320 return intval( $this->getVal( $name, $default ) );
324 * Fetch an integer value from the input or return null if empty.
325 * Guaranteed to return an integer or null; non-numeric input will
326 * typically return null.
327 * @param $name string
330 public function getIntOrNull( $name ) {
331 $val = $this->getVal( $name );
332 return is_numeric( $val )
338 * Fetch a boolean value from the input or return $default if not set.
339 * Guaranteed to return true or false, with normal PHP semantics for
340 * boolean interpretation of strings.
341 * @param $name string
342 * @param $default bool
345 public function getBool( $name, $default = false ) {
346 return $this->getVal( $name, $default ) ?
true : false;
350 * Return true if the named value is set in the input, whatever that
351 * value is (even "0"). Return false if the named value is not set.
352 * Example use is checking for the presence of check boxes in forms.
353 * @param $name string
356 public function getCheck( $name ) {
357 # Checkboxes and buttons are only present when clicked
358 # Presence connotes truth, abscense false
359 $val = $this->getVal( $name, NULL );
360 return isset( $val );
364 * Fetch a text string from the given array or return $default if it's not
365 * set. \r is stripped from the text, and with some language modules there
366 * is an input transliteration applied. This should generally be used for
367 * form <textarea> and <input> fields. Used for user-supplied freeform text
368 * input (for which input transformations may be required - e.g. Esperanto
371 * @param $name string
372 * @param $default string: optional
375 public function getText( $name, $default = '' ) {
377 $val = $this->getVal( $name, $default );
378 return str_replace( "\r\n", "\n",
379 $wgContLang->recodeInput( $val ) );
383 * Extracts the given named values into an array.
384 * If no arguments are given, returns all input values.
385 * No transformation is performed on the values.
387 public function getValues() {
388 $names = func_get_args();
389 if ( count( $names ) == 0 ) {
390 $names = array_keys( $this->data
);
394 foreach ( $names as $name ) {
395 $value = $this->getVal( $name );
396 if ( !is_null( $value ) ) {
397 $retVal[$name] = $value;
404 * Returns true if the present request was reached by a POST operation,
405 * false otherwise (GET, HEAD, or command-line).
407 * Note that values retrieved by the object may come from the
408 * GET URL etc even on a POST request.
412 public function wasPosted() {
413 return $_SERVER['REQUEST_METHOD'] == 'POST';
417 * Returns true if there is a session cookie set.
418 * This does not necessarily mean that the user is logged in!
420 * If you want to check for an open session, use session_id()
421 * instead; that will also tell you if the session was opened
422 * during the current request (in which case the cookie will
423 * be sent back to the client at the end of the script run).
427 public function checkSessionCookie() {
428 return isset( $_COOKIE[session_name()] );
432 * Return the path portion of the request URI.
435 public function getRequestURL() {
436 if( isset( $_SERVER['REQUEST_URI'] ) ) {
437 $base = $_SERVER['REQUEST_URI'];
438 } elseif( isset( $_SERVER['SCRIPT_NAME'] ) ) {
439 // Probably IIS; doesn't set REQUEST_URI
440 $base = $_SERVER['SCRIPT_NAME'];
441 if( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
442 $base .= '?' . $_SERVER['QUERY_STRING'];
445 // This shouldn't happen!
446 throw new MWException( "Web server doesn't provide either " .
447 "REQUEST_URI or SCRIPT_NAME. Report details of your " .
448 "web server configuration to http://bugzilla.wikimedia.org/" );
450 // User-agents should not send a fragment with the URI, but
451 // if they do, and the web server passes it on to us, we
452 // need to strip it or we get false-positive redirect loops
453 // or weird output URLs
454 $hash = strpos( $base, '#' );
455 if( $hash !== false ) {
456 $base = substr( $base, 0, $hash );
458 if( $base{0} == '/' ) {
461 // We may get paths with a host prepended; strip it.
462 return preg_replace( '!^[^:]+://[^/]+/!', '/', $base );
467 * Return the request URI with the canonical service and hostname.
470 public function getFullRequestURL() {
472 return $wgServer . $this->getRequestURL();
476 * Take an arbitrary query and rewrite the present URL to include it
477 * @param $query String: query string fragment; do not include initial '?'
480 public function appendQuery( $query ) {
483 foreach( $_GET as $var => $val ) {
484 if ( $var == 'title' )
486 if ( is_array( $val ) )
487 /* This will happen given a request like
488 * http://en.wikipedia.org/w/index.php?title[]=Special:Userlogin&returnto[]=Main_Page
491 $basequery .= '&' . urlencode( $var ) . '=' . urlencode( $val );
493 $basequery .= '&' . $query;
496 $basequery = substr( $basequery, 1 );
497 return $wgTitle->getLocalURL( $basequery );
501 * HTML-safe version of appendQuery().
502 * @param $query String: query string fragment; do not include initial '?'
505 public function escapeAppendQuery( $query ) {
506 return htmlspecialchars( $this->appendQuery( $query ) );
509 public function appendQueryValue( $key, $value, $onlyquery = false ) {
510 return $this->appendQueryArray( array( $key => $value ), $onlyquery );
514 * Appends or replaces value of query variables.
515 * @param $array Array of values to replace/add to query
516 * @param $onlyquery Bool: whether to only return the query string and not
520 public function appendQueryArray( $array, $onlyquery = false ) {
523 unset( $newquery['title'] );
524 $newquery = array_merge( $newquery, $array );
525 $query = wfArrayToCGI( $newquery );
526 return $onlyquery ?
$query : $wgTitle->getLocalURL( $query );
530 * Check for limit and offset parameters on the input, and return sensible
531 * defaults if not given. The limit must be positive and is capped at 5000.
532 * Offset must be positive but is not capped.
534 * @param $deflimit Integer: limit to use if no input and the user hasn't set the option.
535 * @param $optionname String: to specify an option other than rclimit to pull from.
536 * @return array first element is limit, second is offset
538 public function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
541 $limit = $this->getInt( 'limit', 0 );
542 if( $limit < 0 ) $limit = 0;
543 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
544 $limit = (int)$wgUser->getOption( $optionname );
546 if( $limit <= 0 ) $limit = $deflimit;
547 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
549 $offset = $this->getInt( 'offset', 0 );
550 if( $offset < 0 ) $offset = 0;
552 return array( $limit, $offset );
556 * Return the path to the temporary file where PHP has stored the upload.
557 * @param $key String:
558 * @return string or NULL if no such file.
560 public function getFileTempname( $key ) {
561 if( !isset( $_FILES[$key] ) ) {
564 return $_FILES[$key]['tmp_name'];
568 * Return the size of the upload, or 0.
569 * @param $key String:
572 public function getFileSize( $key ) {
573 if( !isset( $_FILES[$key] ) ) {
576 return $_FILES[$key]['size'];
580 * Return the upload error or 0
581 * @param $key String:
584 public function getUploadError( $key ) {
585 if( !isset( $_FILES[$key] ) ||
!isset( $_FILES[$key]['error'] ) ) {
586 return 0/*UPLOAD_ERR_OK*/;
588 return $_FILES[$key]['error'];
592 * Return the original filename of the uploaded file, as reported by
593 * the submitting user agent. HTML-style character entities are
594 * interpreted and normalized to Unicode normalization form C, in part
595 * to deal with weird input from Safari with non-ASCII filenames.
597 * Other than this the name is not verified for being a safe filename.
599 * @param $key String:
600 * @return string or NULL if no such file.
602 public function getFileName( $key ) {
603 if( !isset( $_FILES[$key] ) ) {
606 $name = $_FILES[$key]['name'];
608 # Safari sends filenames in HTML-encoded Unicode form D...
609 # Horrid and evil! Let's try to make some kind of sense of it.
610 $name = Sanitizer
::decodeCharReferences( $name );
611 $name = UtfNormal
::cleanUp( $name );
612 wfDebug( "WebRequest::getFileName() '" . $_FILES[$key]['name'] . "' normalized to '$name'\n" );
617 * Return a handle to WebResponse style object, for setting cookies,
618 * headers and other stuff, for Request being worked on.
620 public function response() {
621 /* Lazy initialization of response object for this request */
622 if ( !is_object( $this->_response
) ) {
623 $this->_response
= new WebResponse
;
625 return $this->_response
;
629 * Get a request header, or false if it isn't set
630 * @param $name String: case-insensitive header name
632 public function getHeader( $name ) {
633 $name = strtoupper( $name );
634 if ( function_exists( 'apache_request_headers' ) ) {
635 if ( !$this->headers
) {
636 foreach ( apache_request_headers() as $tempName => $tempValue ) {
637 $this->headers
[ strtoupper( $tempName ) ] = $tempValue;
640 if ( isset( $this->headers
[$name] ) ) {
641 return $this->headers
[$name];
646 $name = 'HTTP_' . str_replace( '-', '_', $name );
647 if ( isset( $_SERVER[$name] ) ) {
648 return $_SERVER[$name];
656 * Get data from $_SESSION
657 * @param $key String Name of key in $_SESSION
660 public function getSessionData( $key ) {
661 if( !isset( $_SESSION[$key] ) )
663 return $_SESSION[$key];
668 * @param $key String Name of key in $_SESSION
671 public function setSessionData( $key, $data ) {
672 $_SESSION[$key] = $data;
676 * Returns true if the PATH_INFO ends with an extension other than a script
677 * extension. This could confuse IE for scripts that send arbitrary data which
678 * is not HTML but may be detected as such.
680 * Various past attempts to use the URL to make this check have generally
681 * run up against the fact that CGI does not provide a standard method to
682 * determine the URL. PATH_INFO may be mangled (e.g. if cgi.fix_pathinfo=0),
683 * but only by prefixing it with the script name and maybe some other stuff,
684 * the extension is not mangled. So this should be a reasonably portable
685 * way to perform this security check.
687 public function isPathInfoBad() {
688 global $wgScriptExtension;
690 if ( !isset( $_SERVER['PATH_INFO'] ) ) {
693 $pi = $_SERVER['PATH_INFO'];
694 $dotPos = strrpos( $pi, '.' );
695 if ( $dotPos === false ) {
698 $ext = substr( $pi, $dotPos );
699 return !in_array( $ext, array( $wgScriptExtension, '.php', '.php5' ) );
704 * WebRequest clone which takes values from a provided array.
708 class FauxRequest
extends WebRequest
{
709 private $wasPosted = false;
710 private $session = array();
713 * @param $data Array of *non*-urlencoded key => value pairs, the
714 * fake GET/POST values
715 * @param $wasPosted Bool: whether to treat the data as POST
717 public function __construct( $data, $wasPosted = false, $session = null ) {
718 if( is_array( $data ) ) {
721 throw new MWException( "FauxRequest() got bogus data" );
723 $this->wasPosted
= $wasPosted;
725 $this->session
= $session;
728 private function notImplemented( $method ) {
729 throw new MWException( "{$method}() not implemented" );
732 public function getText( $name, $default = '' ) {
733 # Override; don't recode since we're using internal data
734 return (string)$this->getVal( $name, $default );
737 public function getValues() {
741 public function wasPosted() {
742 return $this->wasPosted
;
745 public function checkSessionCookie() {
749 public function getRequestURL() {
750 $this->notImplemented( __METHOD__
);
753 public function appendQuery( $query ) {
754 $this->notImplemented( __METHOD__
);
757 public function getHeader( $name ) {
758 return isset( $this->headers
[$name] ) ?
$this->headers
[$name] : false;
761 public function getSessionData( $key ) {
762 if( !isset( $this->session
[$key] ) )
764 return $this->session
[$key];
767 public function setSessionData( $key, $data ) {
768 $this->notImplemented( __METHOD__
);
771 public function isPathInfoBad() {