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 = array();
50 public function __construct() {
51 /// @fixme This preemptive de-quoting can interfere with other web libraries
52 /// and increases our memory footprint. It would be cleaner to do on
53 /// demand; but currently we have no wrapper for $_SERVER etc.
54 $this->checkMagicQuotes();
56 // POST overrides GET data
57 // We don't use $_REQUEST here to avoid interference from cookies...
58 $this->data
= $_POST +
$_GET;
62 * Check for title, action, and/or variant data in the URL
63 * and interpolate it into the GET variables.
64 * This should only be run after $wgContLang is available,
65 * as we may need the list of language variants to determine
66 * available variant URLs.
68 public function interpolateTitle() {
69 global $wgUsePathInfo;
70 if ( $wgUsePathInfo ) {
71 // PATH_INFO is mangled due to http://bugs.php.net/bug.php?id=31892
72 // And also by Apache 2.x, double slashes are converted to single slashes.
73 // So we will use REQUEST_URI if possible.
75 if ( !empty( $_SERVER['REQUEST_URI'] ) ) {
76 // Slurp out the path portion to examine...
77 $url = $_SERVER['REQUEST_URI'];
78 if ( !preg_match( '!^https?://!', $url ) ) {
79 $url = 'http://unused' . $url;
81 $a = parse_url( $url );
83 $path = isset( $a['path'] ) ?
$a['path'] : '';
86 if( $path == $wgScript ) {
87 // Script inside a rewrite path?
88 // Abort to keep from breaking...
91 // Raw PATH_INFO style
92 $matches = $this->extractTitle( $path, "$wgScript/$1" );
94 global $wgArticlePath;
95 if( !$matches && $wgArticlePath ) {
96 $matches = $this->extractTitle( $path, $wgArticlePath );
99 global $wgActionPaths;
100 if( !$matches && $wgActionPaths ) {
101 $matches = $this->extractTitle( $path, $wgActionPaths, 'action' );
104 global $wgVariantArticlePath, $wgContLang;
105 if( !$matches && $wgVariantArticlePath ) {
106 $variantPaths = array();
107 foreach( $wgContLang->getVariants() as $variant ) {
108 $variantPaths[$variant] =
109 str_replace( '$2', $variant, $wgVariantArticlePath );
111 $matches = $this->extractTitle( $path, $variantPaths, 'variant' );
114 } elseif ( isset( $_SERVER['ORIG_PATH_INFO'] ) && $_SERVER['ORIG_PATH_INFO'] != '' ) {
116 // http://bugs.php.net/bug.php?id=31892
117 // Also reported when ini_get('cgi.fix_pathinfo')==false
118 $matches['title'] = substr( $_SERVER['ORIG_PATH_INFO'], 1 );
120 } elseif ( isset( $_SERVER['PATH_INFO'] ) && ($_SERVER['PATH_INFO'] != '') ) {
121 // Regular old PATH_INFO yay
122 $matches['title'] = substr( $_SERVER['PATH_INFO'], 1 );
124 foreach( $matches as $key => $val) {
125 $this->data
[$key] = $_GET[$key] = $_REQUEST[$key] = $val;
131 * Internal URL rewriting function; tries to extract page title and,
132 * optionally, one other fixed parameter value from a URL path.
134 * @param $path string: the URL path given from the client
135 * @param $bases array: one or more URLs, optionally with $1 at the end
136 * @param $key string: if provided, the matching key in $bases will be
137 * passed on as the value of this URL parameter
138 * @return array of URL variables to interpolate; empty if no match
140 private function extractTitle( $path, $bases, $key=false ) {
141 foreach( (array)$bases as $keyValue => $base ) {
142 // Find the part after $wgArticlePath
143 $base = str_replace( '$1', '', $base );
144 $baseLen = strlen( $base );
145 if( substr( $path, 0, $baseLen ) == $base ) {
146 $raw = substr( $path, $baseLen );
148 $matches = array( 'title' => rawurldecode( $raw ) );
150 $matches[$key] = $keyValue;
160 * Recursively strips slashes from the given array;
161 * used for undoing the evil that is magic_quotes_gpc.
162 * @param $arr array: will be modified
163 * @return array the original array
165 private function &fix_magic_quotes( &$arr ) {
166 foreach( $arr as $key => $val ) {
167 if( is_array( $val ) ) {
168 $this->fix_magic_quotes( $arr[$key] );
170 $arr[$key] = stripslashes( $val );
177 * If magic_quotes_gpc option is on, run the global arrays
178 * through fix_magic_quotes to strip out the stupid slashes.
179 * WARNING: This should only be done once! Running a second
180 * time could damage the values.
182 private function checkMagicQuotes() {
183 $this->mFixMagicQuotes
= function_exists( 'get_magic_quotes_gpc' ) && get_magic_quotes_gpc()
184 if( $this->mFixMagicQuotes
) {
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 ( !isset( $this->headers
) ) {
636 $this->headers
= array();
637 foreach ( apache_request_headers() as $tempName => $tempValue ) {
638 $this->headers
[ strtoupper( $tempName ) ] = $tempValue;
641 if ( isset( $this->headers
[$name] ) ) {
642 return $this->headers
[$name];
647 $name = 'HTTP_' . str_replace( '-', '_', $name );
648 if ( isset( $_SERVER[$name] ) ) {
649 return $_SERVER[$name];
657 * Get data from $_SESSION
658 * @param $key String Name of key in $_SESSION
661 public function getSessionData( $key ) {
662 if( !isset( $_SESSION[$key] ) )
664 return $_SESSION[$key];
669 * @param $key String Name of key in $_SESSION
672 public function setSessionData( $key, $data ) {
673 $_SESSION[$key] = $data;
678 * WebRequest clone which takes values from a provided array.
682 class FauxRequest
extends WebRequest
{
683 private $wasPosted = false;
684 private $session, $headers = array();
687 * @param $data Array of *non*-urlencoded key => value pairs, the
688 * fake GET/POST values
689 * @param $wasPosted Bool: whether to treat the data as POST
691 public function __construct( $data, $wasPosted = false, $session = null ) {
692 if( is_array( $data ) ) {
695 throw new MWException( "FauxRequest() got bogus data" );
697 $this->wasPosted
= $wasPosted;
699 $this->session
= $session;
702 private function notImplemented( $method ) {
703 throw new MWException( "{$method}() not implemented" );
706 public function getText( $name, $default = '' ) {
707 # Override; don't recode since we're using internal data
708 return (string)$this->getVal( $name, $default );
711 public function getValues() {
715 public function wasPosted() {
716 return $this->wasPosted
;
719 public function checkSessionCookie() {
723 public function getRequestURL() {
724 $this->notImplemented( __METHOD__
);
727 public function appendQuery( $query ) {
728 $this->notImplemented( __METHOD__
);
731 public function getHeader( $name ) {
732 return isset( $this->headers
[$name] ) ?
$this->headers
[$name] : false;
735 public function getSessionData( $key ) {
736 if( !isset( $this->session
[$key] ) )
738 return $this->session
[$key];
741 public function setSessionData( $key, $data ) {
742 $this->notImplemented( __METHOD__
);