784dc0fab14f7f2c8387d86a1a88c12052cfc3d7
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();
47 private $_response, $mFixMagicQuotes;
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 $this->mFixMagicQuotes
= function_exists( 'get_magic_quotes_gpc' ) && get_magic_quotes_gpc();
183 if( $this->mFixMagicQuotes
) {
184 $this->fix_magic_quotes( $_COOKIE );
185 $this->fix_magic_quotes( $_ENV );
186 $this->fix_magic_quotes( $_GET );
187 $this->fix_magic_quotes( $_POST );
188 $this->fix_magic_quotes( $_REQUEST );
189 $this->fix_magic_quotes( $_SERVER );
194 * Recursively normalizes UTF-8 strings in the given array.
195 * @param $data string or array
196 * @return cleaned-up version of the given
199 function normalizeUnicode( $data ) {
200 if( is_array( $data ) ) {
201 foreach( $data as $key => $val ) {
202 $data[$key] = $this->normalizeUnicode( $val );
205 $data = UtfNormal
::cleanUp( $data );
211 * Fetch a value from the given array or return $default if it's not set.
214 * @param $name string
215 * @param $default mixed
218 private function getGPCVal( $arr, $name, $default ) {
219 # PHP is so nice to not touch input data, except sometimes:
220 # http://us2.php.net/variables.external#language.variables.external.dot-in-names
221 # Work around PHP *feature* to avoid *bugs* elsewhere.
222 $name = strtr( $name, '.', '_' );
223 if( isset( $arr[$name] ) ) {
226 if( isset( $_GET[$name] ) && !is_array( $data ) ) {
227 # Check for alternate/legacy character encoding.
228 if( isset( $wgContLang ) ) {
229 $data = $wgContLang->checkTitleEncoding( $data );
232 $data = $this->normalizeUnicode( $data );
241 * Fetch a scalar from the input or return $default if it's not set.
242 * Returns a string. Arrays are discarded. Useful for
243 * non-freeform text inputs (e.g. predefined internal text keys
244 * selected by a drop-down menu). For freeform input, see getText().
246 * @param $name string
247 * @param $default string: optional default (or NULL)
250 public function getVal( $name, $default = NULL ) {
251 $val = $this->getGPCVal( $this->data
, $name, $default );
252 if( is_array( $val ) ) {
255 if( is_null( $val ) ) {
263 * Set an aribtrary value into our get/post data.
264 * @param $key string Key name to use
265 * @param $value mixed Value to set
266 * @return mixed old value if one was present, null otherwise
268 public function setVal( $key, $value ) {
269 $ret = isset( $this->data
[$key] ) ?
$this->data
[$key] : null;
270 $this->data
[$key] = $value;
275 * Fetch an array from the input or return $default if it's not set.
276 * If source was scalar, will return an array with a single element.
277 * If no source and no default, returns NULL.
279 * @param $name string
280 * @param $default array: optional default (or NULL)
283 public function getArray( $name, $default = NULL ) {
284 $val = $this->getGPCVal( $this->data
, $name, $default );
285 if( is_null( $val ) ) {
293 * Fetch an array of integers, or return $default if it's not set.
294 * If source was scalar, will return an array with a single element.
295 * If no source and no default, returns NULL.
296 * If an array is returned, contents are guaranteed to be integers.
298 * @param $name string
299 * @param $default array: option default (or NULL)
300 * @return array of ints
302 public function getIntArray( $name, $default = NULL ) {
303 $val = $this->getArray( $name, $default );
304 if( is_array( $val ) ) {
305 $val = array_map( 'intval', $val );
311 * Fetch an integer value from the input or return $default if not set.
312 * Guaranteed to return an integer; non-numeric input will typically
314 * @param $name string
315 * @param $default int
318 public function getInt( $name, $default = 0 ) {
319 return intval( $this->getVal( $name, $default ) );
323 * Fetch an integer value from the input or return null if empty.
324 * Guaranteed to return an integer or null; non-numeric input will
325 * typically return null.
326 * @param $name string
329 public function getIntOrNull( $name ) {
330 $val = $this->getVal( $name );
331 return is_numeric( $val )
337 * Fetch a boolean value from the input or return $default if not set.
338 * Guaranteed to return true or false, with normal PHP semantics for
339 * boolean interpretation of strings.
340 * @param $name string
341 * @param $default bool
344 public function getBool( $name, $default = false ) {
345 return $this->getVal( $name, $default ) ?
true : false;
349 * Return true if the named value is set in the input, whatever that
350 * value is (even "0"). Return false if the named value is not set.
351 * Example use is checking for the presence of check boxes in forms.
352 * @param $name string
355 public function getCheck( $name ) {
356 # Checkboxes and buttons are only present when clicked
357 # Presence connotes truth, abscense false
358 $val = $this->getVal( $name, NULL );
359 return isset( $val );
363 * Fetch a text string from the given array or return $default if it's not
364 * set. \r is stripped from the text, and with some language modules there
365 * is an input transliteration applied. This should generally be used for
366 * form <textarea> and <input> fields. Used for user-supplied freeform text
367 * input (for which input transformations may be required - e.g. Esperanto
370 * @param $name string
371 * @param $default string: optional
374 public function getText( $name, $default = '' ) {
376 $val = $this->getVal( $name, $default );
377 return str_replace( "\r\n", "\n",
378 $wgContLang->recodeInput( $val ) );
382 * Extracts the given named values into an array.
383 * If no arguments are given, returns all input values.
384 * No transformation is performed on the values.
386 public function getValues() {
387 $names = func_get_args();
388 if ( count( $names ) == 0 ) {
389 $names = array_keys( $this->data
);
393 foreach ( $names as $name ) {
394 $value = $this->getVal( $name );
395 if ( !is_null( $value ) ) {
396 $retVal[$name] = $value;
403 * Returns true if the present request was reached by a POST operation,
404 * false otherwise (GET, HEAD, or command-line).
406 * Note that values retrieved by the object may come from the
407 * GET URL etc even on a POST request.
411 public function wasPosted() {
412 return $_SERVER['REQUEST_METHOD'] == 'POST';
416 * Returns true if there is a session cookie set.
417 * This does not necessarily mean that the user is logged in!
419 * If you want to check for an open session, use session_id()
420 * instead; that will also tell you if the session was opened
421 * during the current request (in which case the cookie will
422 * be sent back to the client at the end of the script run).
426 public function checkSessionCookie() {
427 return isset( $_COOKIE[session_name()] );
431 * Return the path portion of the request URI.
434 public function getRequestURL() {
435 if( isset( $_SERVER['REQUEST_URI'] ) ) {
436 $base = $_SERVER['REQUEST_URI'];
437 } elseif( isset( $_SERVER['SCRIPT_NAME'] ) ) {
438 // Probably IIS; doesn't set REQUEST_URI
439 $base = $_SERVER['SCRIPT_NAME'];
440 if( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
441 $base .= '?' . $_SERVER['QUERY_STRING'];
444 // This shouldn't happen!
445 throw new MWException( "Web server doesn't provide either " .
446 "REQUEST_URI or SCRIPT_NAME. Report details of your " .
447 "web server configuration to http://bugzilla.wikimedia.org/" );
449 // User-agents should not send a fragment with the URI, but
450 // if they do, and the web server passes it on to us, we
451 // need to strip it or we get false-positive redirect loops
452 // or weird output URLs
453 $hash = strpos( $base, '#' );
454 if( $hash !== false ) {
455 $base = substr( $base, 0, $hash );
457 if( $base{0} == '/' ) {
460 // We may get paths with a host prepended; strip it.
461 return preg_replace( '!^[^:]+://[^/]+/!', '/', $base );
466 * Return the request URI with the canonical service and hostname.
469 public function getFullRequestURL() {
471 return $wgServer . $this->getRequestURL();
475 * Take an arbitrary query and rewrite the present URL to include it
476 * @param $query String: query string fragment; do not include initial '?'
479 public function appendQuery( $query ) {
482 foreach( $_GET as $var => $val ) {
483 if ( $var == 'title' )
485 if ( is_array( $val ) )
486 /* This will happen given a request like
487 * http://en.wikipedia.org/w/index.php?title[]=Special:Userlogin&returnto[]=Main_Page
490 $basequery .= '&' . urlencode( $var ) . '=' . urlencode( $val );
492 $basequery .= '&' . $query;
495 $basequery = substr( $basequery, 1 );
496 return $wgTitle->getLocalURL( $basequery );
500 * HTML-safe version of appendQuery().
501 * @param $query String: query string fragment; do not include initial '?'
504 public function escapeAppendQuery( $query ) {
505 return htmlspecialchars( $this->appendQuery( $query ) );
508 public function appendQueryValue( $key, $value, $onlyquery = false ) {
509 return $this->appendQueryArray( array( $key => $value ), $onlyquery );
513 * Appends or replaces value of query variables.
514 * @param $array Array of values to replace/add to query
515 * @param $onlyquery Bool: whether to only return the query string and not
519 public function appendQueryArray( $array, $onlyquery = false ) {
522 unset( $newquery['title'] );
523 $newquery = array_merge( $newquery, $array );
524 $query = wfArrayToCGI( $newquery );
525 return $onlyquery ?
$query : $wgTitle->getLocalURL( $query );
529 * Check for limit and offset parameters on the input, and return sensible
530 * defaults if not given. The limit must be positive and is capped at 5000.
531 * Offset must be positive but is not capped.
533 * @param $deflimit Integer: limit to use if no input and the user hasn't set the option.
534 * @param $optionname String: to specify an option other than rclimit to pull from.
535 * @return array first element is limit, second is offset
537 public function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
540 $limit = $this->getInt( 'limit', 0 );
541 if( $limit < 0 ) $limit = 0;
542 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
543 $limit = (int)$wgUser->getOption( $optionname );
545 if( $limit <= 0 ) $limit = $deflimit;
546 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
548 $offset = $this->getInt( 'offset', 0 );
549 if( $offset < 0 ) $offset = 0;
551 return array( $limit, $offset );
555 * Return the path to the temporary file where PHP has stored the upload.
556 * @param $key String:
557 * @return string or NULL if no such file.
559 public function getFileTempname( $key ) {
560 if( !isset( $_FILES[$key] ) ) {
563 return $_FILES[$key]['tmp_name'];
567 * Return the size of the upload, or 0.
568 * @param $key String:
571 public function getFileSize( $key ) {
572 if( !isset( $_FILES[$key] ) ) {
575 return $_FILES[$key]['size'];
579 * Return the upload error or 0
580 * @param $key String:
583 public function getUploadError( $key ) {
584 if( !isset( $_FILES[$key] ) ||
!isset( $_FILES[$key]['error'] ) ) {
585 return 0/*UPLOAD_ERR_OK*/;
587 return $_FILES[$key]['error'];
591 * Return the original filename of the uploaded file, as reported by
592 * the submitting user agent. HTML-style character entities are
593 * interpreted and normalized to Unicode normalization form C, in part
594 * to deal with weird input from Safari with non-ASCII filenames.
596 * Other than this the name is not verified for being a safe filename.
598 * @param $key String:
599 * @return string or NULL if no such file.
601 public function getFileName( $key ) {
602 if( !isset( $_FILES[$key] ) ) {
605 $name = $_FILES[$key]['name'];
607 # Safari sends filenames in HTML-encoded Unicode form D...
608 # Horrid and evil! Let's try to make some kind of sense of it.
609 $name = Sanitizer
::decodeCharReferences( $name );
610 $name = UtfNormal
::cleanUp( $name );
611 wfDebug( "WebRequest::getFileName() '" . $_FILES[$key]['name'] . "' normalized to '$name'\n" );
616 * Return a handle to WebResponse style object, for setting cookies,
617 * headers and other stuff, for Request being worked on.
619 public function response() {
620 /* Lazy initialization of response object for this request */
621 if ( !is_object( $this->_response
) ) {
622 $this->_response
= new WebResponse
;
624 return $this->_response
;
628 * Get a request header, or false if it isn't set
629 * @param $name String: case-insensitive header name
631 public function getHeader( $name ) {
632 $name = strtoupper( $name );
633 if ( function_exists( 'apache_request_headers' ) ) {
634 if ( !$this->headers
) {
635 foreach ( apache_request_headers() as $tempName => $tempValue ) {
636 $this->headers
[ strtoupper( $tempName ) ] = $tempValue;
639 if ( isset( $this->headers
[$name] ) ) {
640 return $this->headers
[$name];
645 $name = 'HTTP_' . str_replace( '-', '_', $name );
646 if ( isset( $_SERVER[$name] ) ) {
647 return $_SERVER[$name];
655 * Get data from $_SESSION
656 * @param $key String Name of key in $_SESSION
659 public function getSessionData( $key ) {
660 if( !isset( $_SESSION[$key] ) )
662 return $_SESSION[$key];
667 * @param $key String Name of key in $_SESSION
670 public function setSessionData( $key, $data ) {
671 $_SESSION[$key] = $data;
676 * WebRequest clone which takes values from a provided array.
680 class FauxRequest
extends WebRequest
{
681 private $wasPosted = false;
682 private $session = array();
685 * @param $data Array of *non*-urlencoded key => value pairs, the
686 * fake GET/POST values
687 * @param $wasPosted Bool: whether to treat the data as POST
689 public function __construct( $data, $wasPosted = false, $session = null ) {
690 if( is_array( $data ) ) {
693 throw new MWException( "FauxRequest() got bogus data" );
695 $this->wasPosted
= $wasPosted;
697 $this->session
= $session;
700 private function notImplemented( $method ) {
701 throw new MWException( "{$method}() not implemented" );
704 public function getText( $name, $default = '' ) {
705 # Override; don't recode since we're using internal data
706 return (string)$this->getVal( $name, $default );
709 public function getValues() {
713 public function wasPosted() {
714 return $this->wasPosted
;
717 public function checkSessionCookie() {
721 public function getRequestURL() {
722 $this->notImplemented( __METHOD__
);
725 public function appendQuery( $query ) {
726 $this->notImplemented( __METHOD__
);
729 public function getHeader( $name ) {
730 return isset( $this->headers
[$name] ) ?
$this->headers
[$name] : false;
733 public function getSessionData( $key ) {
734 if( !isset( $this->session
[$key] ) )
736 return $this->session
[$key];
739 public function setSessionData( $key, $data ) {
740 $this->notImplemented( __METHOD__
);