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
45 function __construct() {
46 $this->checkMagicQuotes();
47 global $wgUsePathInfo;
48 if ( $wgUsePathInfo ) {
49 // PATH_INFO is mangled due to http://bugs.php.net/bug.php?id=31892
50 // And also by Apache 2.x, double slashes are converted to single slashes.
51 // So we will use REQUEST_URI if possible.
53 if ( !empty( $_SERVER['REQUEST_URI'] ) ) {
54 global $wgArticlePath;
55 $url = $_SERVER['REQUEST_URI'];
56 if ( !preg_match( '!^https?://!', $url ) ) {
57 $url = 'http://unused' . $url;
59 $a = parse_url( $url );
60 // Find the part after $wgArticlePath
61 $base = str_replace( '$1', '', $wgArticlePath );
62 if ( $a && substr( $a['path'], 0, strlen( $base ) ) == $base ) {
63 $title = urldecode( substr( $a['path'], strlen( $base ) ) );
65 } elseif ( isset( $_SERVER['ORIG_PATH_INFO'] ) && $_SERVER['ORIG_PATH_INFO'] != '' ) {
67 # http://bugs.php.net/bug.php?id=31892
68 # Also reported when ini_get('cgi.fix_pathinfo')==false
69 $title = substr( $_SERVER['ORIG_PATH_INFO'], 1 );
70 } elseif ( isset( $_SERVER['PATH_INFO'] ) && ($_SERVER['PATH_INFO'] != '') && $wgUsePathInfo ) {
71 $title = substr( $_SERVER['PATH_INFO'], 1 );
73 if ( strval( $title ) != '' ) {
74 $_GET['title'] = $_REQUEST['title'] = $title;
82 * Recursively strips slashes from the given array;
83 * used for undoing the evil that is magic_quotes_gpc.
84 * @param array &$arr will be modified
85 * @return array the original array
88 function &fix_magic_quotes( &$arr ) {
89 foreach( $arr as $key => $val ) {
90 if( is_array( $val ) ) {
91 $this->fix_magic_quotes( $arr[$key] );
93 $arr[$key] = stripslashes( $val );
100 * If magic_quotes_gpc option is on, run the global arrays
101 * through fix_magic_quotes to strip out the stupid slashes.
102 * WARNING: This should only be done once! Running a second
103 * time could damage the values.
106 function checkMagicQuotes() {
107 if ( get_magic_quotes_gpc() ) {
108 $this->fix_magic_quotes( $_COOKIE );
109 $this->fix_magic_quotes( $_ENV );
110 $this->fix_magic_quotes( $_GET );
111 $this->fix_magic_quotes( $_POST );
112 $this->fix_magic_quotes( $_REQUEST );
113 $this->fix_magic_quotes( $_SERVER );
118 * Recursively normalizes UTF-8 strings in the given array.
119 * @param array $data string or array
120 * @return cleaned-up version of the given
123 function normalizeUnicode( $data ) {
124 if( is_array( $data ) ) {
125 foreach( $data as $key => $val ) {
126 $data[$key] = $this->normalizeUnicode( $val );
129 $data = UtfNormal
::cleanUp( $data );
135 * Fetch a value from the given array or return $default if it's not set.
138 * @param string $name
139 * @param mixed $default
143 function getGPCVal( $arr, $name, $default ) {
144 if( isset( $arr[$name] ) ) {
147 if( isset( $_GET[$name] ) && !is_array( $data ) ) {
148 # Check for alternate/legacy character encoding.
149 if( isset( $wgContLang ) ) {
150 $data = $wgContLang->checkTitleEncoding( $data );
153 $data = $this->normalizeUnicode( $data );
161 * Fetch a scalar from the input or return $default if it's not set.
162 * Returns a string. Arrays are discarded. Useful for
163 * non-freeform text inputs (e.g. predefined internal text keys
164 * selected by a drop-down menu). For freeform input, see getText().
166 * @param string $name
167 * @param string $default optional default (or NULL)
170 function getVal( $name, $default = NULL ) {
171 $val = $this->getGPCVal( $_REQUEST, $name, $default );
172 if( is_array( $val ) ) {
175 if( is_null( $val ) ) {
183 * Fetch an array from the input or return $default if it's not set.
184 * If source was scalar, will return an array with a single element.
185 * If no source and no default, returns NULL.
187 * @param string $name
188 * @param array $default optional default (or NULL)
191 function getArray( $name, $default = NULL ) {
192 $val = $this->getGPCVal( $_REQUEST, $name, $default );
193 if( is_null( $val ) ) {
201 * Fetch an array of integers, or return $default if it's not set.
202 * If source was scalar, will return an array with a single element.
203 * If no source and no default, returns NULL.
204 * If an array is returned, contents are guaranteed to be integers.
206 * @param string $name
207 * @param array $default option default (or NULL)
208 * @return array of ints
210 function getIntArray( $name, $default = NULL ) {
211 $val = $this->getArray( $name, $default );
212 if( is_array( $val ) ) {
213 $val = array_map( 'intval', $val );
219 * Fetch an integer value from the input or return $default if not set.
220 * Guaranteed to return an integer; non-numeric input will typically
222 * @param string $name
223 * @param int $default
226 function getInt( $name, $default = 0 ) {
227 return intval( $this->getVal( $name, $default ) );
231 * Fetch an integer value from the input or return null if empty.
232 * Guaranteed to return an integer or null; non-numeric input will
233 * typically return null.
234 * @param string $name
237 function getIntOrNull( $name ) {
238 $val = $this->getVal( $name );
239 return is_numeric( $val )
245 * Fetch a boolean value from the input or return $default if not set.
246 * Guaranteed to return true or false, with normal PHP semantics for
247 * boolean interpretation of strings.
248 * @param string $name
249 * @param bool $default
252 function getBool( $name, $default = false ) {
253 return $this->getVal( $name, $default ) ?
true : false;
257 * Return true if the named value is set in the input, whatever that
258 * value is (even "0"). Return false if the named value is not set.
259 * Example use is checking for the presence of check boxes in forms.
260 * @param string $name
263 function getCheck( $name ) {
264 # Checkboxes and buttons are only present when clicked
265 # Presence connotes truth, abscense false
266 $val = $this->getVal( $name, NULL );
267 return isset( $val );
271 * Fetch a text string from the given array or return $default if it's not
272 * set. \r is stripped from the text, and with some language modules there
273 * is an input transliteration applied. This should generally be used for
274 * form <textarea> and <input> fields. Used for user-supplied freeform text
275 * input (for which input transformations may be required - e.g. Esperanto
278 * @param string $name
279 * @param string $default optional
282 function getText( $name, $default = '' ) {
284 $val = $this->getVal( $name, $default );
285 return str_replace( "\r\n", "\n",
286 $wgContLang->recodeInput( $val ) );
290 * Extracts the given named values into an array.
291 * If no arguments are given, returns all input values.
292 * No transformation is performed on the values.
294 function getValues() {
295 $names = func_get_args();
296 if ( count( $names ) == 0 ) {
297 $names = array_keys( $_REQUEST );
301 foreach ( $names as $name ) {
302 $value = $this->getVal( $name );
303 if ( !is_null( $value ) ) {
304 $retVal[$name] = $value;
311 * Returns true if the present request was reached by a POST operation,
312 * false otherwise (GET, HEAD, or command-line).
314 * Note that values retrieved by the object may come from the
315 * GET URL etc even on a POST request.
319 function wasPosted() {
320 return $_SERVER['REQUEST_METHOD'] == 'POST';
324 * Returns true if there is a session cookie set.
325 * This does not necessarily mean that the user is logged in!
327 * If you want to check for an open session, use session_id()
328 * instead; that will also tell you if the session was opened
329 * during the current request (in which case the cookie will
330 * be sent back to the client at the end of the script run).
334 function checkSessionCookie() {
335 return isset( $_COOKIE[session_name()] );
339 * Return the path portion of the request URI.
342 function getRequestURL() {
343 if( isset( $_SERVER['REQUEST_URI'] ) ) {
344 $base = $_SERVER['REQUEST_URI'];
345 } elseif( isset( $_SERVER['SCRIPT_NAME'] ) ) {
346 // Probably IIS; doesn't set REQUEST_URI
347 $base = $_SERVER['SCRIPT_NAME'];
348 if( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
349 $base .= '?' . $_SERVER['QUERY_STRING'];
352 // This shouldn't happen!
353 throw new MWException( "Web server doesn't provide either " .
354 "REQUEST_URI or SCRIPT_NAME. Report details of your " .
355 "web server configuration to http://bugzilla.wikimedia.org/" );
357 // User-agents should not send a fragment with the URI, but
358 // if they do, and the web server passes it on to us, we
359 // need to strip it or we get false-positive redirect loops
360 // or weird output URLs
361 $hash = strpos( $base, '#' );
362 if( $hash !== false ) {
363 $base = substr( $base, 0, $hash );
365 if( $base{0} == '/' ) {
368 // We may get paths with a host prepended; strip it.
369 return preg_replace( '!^[^:]+://[^/]+/!', '/', $base );
374 * Return the request URI with the canonical service and hostname.
377 function getFullRequestURL() {
379 return $wgServer . $this->getRequestURL();
383 * Take an arbitrary query and rewrite the present URL to include it
384 * @param $query String: query string fragment; do not include initial '?'
387 function appendQuery( $query ) {
390 foreach( $_GET as $var => $val ) {
391 if ( $var == 'title' )
393 if ( is_array( $val ) )
394 /* This will happen given a request like
395 * http://en.wikipedia.org/w/index.php?title[]=Special:Userlogin&returnto[]=Main_Page
398 $basequery .= '&' . urlencode( $var ) . '=' . urlencode( $val );
400 $basequery .= '&' . $query;
403 $basequery = substr( $basequery, 1 );
404 return $wgTitle->getLocalURL( $basequery );
408 * HTML-safe version of appendQuery().
409 * @param $query String: query string fragment; do not include initial '?'
412 function escapeAppendQuery( $query ) {
413 return htmlspecialchars( $this->appendQuery( $query ) );
417 * Check for limit and offset parameters on the input, and return sensible
418 * defaults if not given. The limit must be positive and is capped at 5000.
419 * Offset must be positive but is not capped.
421 * @param $deflimit Integer: limit to use if no input and the user hasn't set the option.
422 * @param $optionname String: to specify an option other than rclimit to pull from.
423 * @return array first element is limit, second is offset
425 function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
428 $limit = $this->getInt( 'limit', 0 );
429 if( $limit < 0 ) $limit = 0;
430 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
431 $limit = (int)$wgUser->getOption( $optionname );
433 if( $limit <= 0 ) $limit = $deflimit;
434 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
436 $offset = $this->getInt( 'offset', 0 );
437 if( $offset < 0 ) $offset = 0;
439 return array( $limit, $offset );
443 * Return the path to the temporary file where PHP has stored the upload.
444 * @param $key String:
445 * @return string or NULL if no such file.
447 function getFileTempname( $key ) {
448 if( !isset( $_FILES[$key] ) ) {
451 return $_FILES[$key]['tmp_name'];
455 * Return the size of the upload, or 0.
456 * @param $key String:
459 function getFileSize( $key ) {
460 if( !isset( $_FILES[$key] ) ) {
463 return $_FILES[$key]['size'];
467 * Return the upload error or 0
468 * @param $key String:
471 function getUploadError( $key ) {
472 if( !isset( $_FILES[$key] ) ||
!isset( $_FILES[$key]['error'] ) ) {
473 return 0/*UPLOAD_ERR_OK*/;
475 return $_FILES[$key]['error'];
479 * Return the original filename of the uploaded file, as reported by
480 * the submitting user agent. HTML-style character entities are
481 * interpreted and normalized to Unicode normalization form C, in part
482 * to deal with weird input from Safari with non-ASCII filenames.
484 * Other than this the name is not verified for being a safe filename.
486 * @param $key String:
487 * @return string or NULL if no such file.
489 function getFileName( $key ) {
490 if( !isset( $_FILES[$key] ) ) {
493 $name = $_FILES[$key]['name'];
495 # Safari sends filenames in HTML-encoded Unicode form D...
496 # Horrid and evil! Let's try to make some kind of sense of it.
497 $name = Sanitizer
::decodeCharReferences( $name );
498 $name = UtfNormal
::cleanUp( $name );
499 wfDebug( "WebRequest::getFileName() '" . $_FILES[$key]['name'] . "' normalized to '$name'\n" );
504 * Return a handle to WebResponse style object, for setting cookies,
505 * headers and other stuff, for Request being worked on.
507 function response() {
508 /* Lazy initialization of response object for this request */
509 if (!is_object($this->_response
)) {
510 $this->_response
= new WebResponse
;
512 return $this->_response
;
518 * WebRequest clone which takes values from a provided array.
521 class FauxRequest
extends WebRequest
{
523 var $wasPosted = false;
525 function FauxRequest( $data, $wasPosted = false ) {
526 if( is_array( $data ) ) {
529 throw new MWException( "FauxRequest() got bogus data" );
531 $this->wasPosted
= $wasPosted;
534 function getVal( $name, $default = NULL ) {
535 return $this->getGPCVal( $this->data
, $name, $default );
538 function getText( $name, $default = '' ) {
539 # Override; don't recode since we're using internal data
540 return $this->getVal( $name, $default );
543 function getValues() {
547 function wasPosted() {
548 return $this->wasPosted
;
551 function checkSessionCookie() {
555 function getRequestURL() {
556 throw new MWException( 'FauxRequest::getRequestURL() not implemented' );
559 function appendQuery( $query ) {
560 throw new MWException( 'FauxRequest::appendQuery() not implemented' );