hook point for injecting fields into edit form
[mediawiki.git] / includes / WebRequest.php
blob6c058af0c9f686f0a4d7e7a770a92e6cdc16ed67
1 <?php
2 /**
3 * Deal with importing all those nasssty globals and things
4 */
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
24 /**
25 * The WebRequest class encapsulates getting at data passed in the
26 * URL or via a POSTed form, handling remove of "magic quotes" slashes,
27 * stripping illegal input characters and normalizing Unicode sequences.
29 * Usually this is used via a global singleton, $wgRequest. You should
30 * not create a second WebRequest object; make a FauxRequest object if
31 * you want to pass arbitrary data to some function in place of the web
32 * input.
36 /**
37 * Some entry points may use this file without first enabling the
38 * autoloader.
40 if ( !function_exists( '__autoload' ) ) {
41 require_once( dirname(__FILE__) . '/normal/UtfNormal.php' );
44 class WebRequest {
45 function __construct() {
46 $this->checkMagicQuotes();
47 global $wgUsePathInfo;
48 if ( $wgUsePathInfo ) {
49 if ( isset( $_SERVER['ORIG_PATH_INFO'] ) && $_SERVER['ORIG_PATH_INFO'] != '' ) {
50 # Mangled PATH_INFO
51 # http://bugs.php.net/bug.php?id=31892
52 # Also reported when ini_get('cgi.fix_pathinfo')==false
53 $_GET['title'] = $_REQUEST['title'] = substr( $_SERVER['ORIG_PATH_INFO'], 1 );
54 } elseif ( isset( $_SERVER['PATH_INFO'] ) && ($_SERVER['PATH_INFO'] != '') && $wgUsePathInfo ) {
55 $_GET['title'] = $_REQUEST['title'] = substr( $_SERVER['PATH_INFO'], 1 );
60 private $_response;
62 /**
63 * Recursively strips slashes from the given array;
64 * used for undoing the evil that is magic_quotes_gpc.
65 * @param array &$arr will be modified
66 * @return array the original array
67 * @private
69 function &fix_magic_quotes( &$arr ) {
70 foreach( $arr as $key => $val ) {
71 if( is_array( $val ) ) {
72 $this->fix_magic_quotes( $arr[$key] );
73 } else {
74 $arr[$key] = stripslashes( $val );
77 return $arr;
80 /**
81 * If magic_quotes_gpc option is on, run the global arrays
82 * through fix_magic_quotes to strip out the stupid slashes.
83 * WARNING: This should only be done once! Running a second
84 * time could damage the values.
85 * @private
87 function checkMagicQuotes() {
88 if ( get_magic_quotes_gpc() ) {
89 $this->fix_magic_quotes( $_COOKIE );
90 $this->fix_magic_quotes( $_ENV );
91 $this->fix_magic_quotes( $_GET );
92 $this->fix_magic_quotes( $_POST );
93 $this->fix_magic_quotes( $_REQUEST );
94 $this->fix_magic_quotes( $_SERVER );
98 /**
99 * Recursively normalizes UTF-8 strings in the given array.
100 * @param array $data string or array
101 * @return cleaned-up version of the given
102 * @private
104 function normalizeUnicode( $data ) {
105 if( is_array( $data ) ) {
106 foreach( $data as $key => $val ) {
107 $data[$key] = $this->normalizeUnicode( $val );
109 } else {
110 $data = UtfNormal::cleanUp( $data );
112 return $data;
116 * Fetch a value from the given array or return $default if it's not set.
118 * @param array $arr
119 * @param string $name
120 * @param mixed $default
121 * @return mixed
122 * @private
124 function getGPCVal( $arr, $name, $default ) {
125 if( isset( $arr[$name] ) ) {
126 global $wgContLang;
127 $data = $arr[$name];
128 if( isset( $_GET[$name] ) && !is_array( $data ) ) {
129 # Check for alternate/legacy character encoding.
130 if( isset( $wgContLang ) ) {
131 $data = $wgContLang->checkTitleEncoding( $data );
134 $data = $this->normalizeUnicode( $data );
135 return $data;
136 } else {
137 return $default;
142 * Fetch a scalar from the input or return $default if it's not set.
143 * Returns a string. Arrays are discarded.
145 * @param string $name
146 * @param string $default optional default (or NULL)
147 * @return string
149 function getVal( $name, $default = NULL ) {
150 $val = $this->getGPCVal( $_REQUEST, $name, $default );
151 if( is_array( $val ) ) {
152 $val = $default;
154 if( is_null( $val ) ) {
155 return null;
156 } else {
157 return (string)$val;
162 * Fetch an array from the input or return $default if it's not set.
163 * If source was scalar, will return an array with a single element.
164 * If no source and no default, returns NULL.
166 * @param string $name
167 * @param array $default optional default (or NULL)
168 * @return array
170 function getArray( $name, $default = NULL ) {
171 $val = $this->getGPCVal( $_REQUEST, $name, $default );
172 if( is_null( $val ) ) {
173 return null;
174 } else {
175 return (array)$val;
180 * Fetch an array of integers, or return $default if it's not set.
181 * If source was scalar, will return an array with a single element.
182 * If no source and no default, returns NULL.
183 * If an array is returned, contents are guaranteed to be integers.
185 * @param string $name
186 * @param array $default option default (or NULL)
187 * @return array of ints
189 function getIntArray( $name, $default = NULL ) {
190 $val = $this->getArray( $name, $default );
191 if( is_array( $val ) ) {
192 $val = array_map( 'intval', $val );
194 return $val;
198 * Fetch an integer value from the input or return $default if not set.
199 * Guaranteed to return an integer; non-numeric input will typically
200 * return 0.
201 * @param string $name
202 * @param int $default
203 * @return int
205 function getInt( $name, $default = 0 ) {
206 return intval( $this->getVal( $name, $default ) );
210 * Fetch an integer value from the input or return null if empty.
211 * Guaranteed to return an integer or null; non-numeric input will
212 * typically return null.
213 * @param string $name
214 * @return int
216 function getIntOrNull( $name ) {
217 $val = $this->getVal( $name );
218 return is_numeric( $val )
219 ? intval( $val )
220 : null;
224 * Fetch a boolean value from the input or return $default if not set.
225 * Guaranteed to return true or false, with normal PHP semantics for
226 * boolean interpretation of strings.
227 * @param string $name
228 * @param bool $default
229 * @return bool
231 function getBool( $name, $default = false ) {
232 return $this->getVal( $name, $default ) ? true : false;
236 * Return true if the named value is set in the input, whatever that
237 * value is (even "0"). Return false if the named value is not set.
238 * Example use is checking for the presence of check boxes in forms.
239 * @param string $name
240 * @return bool
242 function getCheck( $name ) {
243 # Checkboxes and buttons are only present when clicked
244 # Presence connotes truth, abscense false
245 $val = $this->getVal( $name, NULL );
246 return isset( $val );
250 * Fetch a text string from the given array or return $default if it's not
251 * set. \r is stripped from the text, and with some language modules there
252 * is an input transliteration applied. This should generally be used for
253 * form <textarea> and <input> fields.
255 * @param string $name
256 * @param string $default optional
257 * @return string
259 function getText( $name, $default = '' ) {
260 global $wgContLang;
261 $val = $this->getVal( $name, $default );
262 return str_replace( "\r\n", "\n",
263 $wgContLang->recodeInput( $val ) );
267 * Extracts the given named values into an array.
268 * If no arguments are given, returns all input values.
269 * No transformation is performed on the values.
271 function getValues() {
272 $names = func_get_args();
273 if ( count( $names ) == 0 ) {
274 $names = array_keys( $_REQUEST );
277 $retVal = array();
278 foreach ( $names as $name ) {
279 $value = $this->getVal( $name );
280 if ( !is_null( $value ) ) {
281 $retVal[$name] = $value;
284 return $retVal;
288 * Returns true if the present request was reached by a POST operation,
289 * false otherwise (GET, HEAD, or command-line).
291 * Note that values retrieved by the object may come from the
292 * GET URL etc even on a POST request.
294 * @return bool
296 function wasPosted() {
297 return $_SERVER['REQUEST_METHOD'] == 'POST';
301 * Returns true if there is a session cookie set.
302 * This does not necessarily mean that the user is logged in!
304 * If you want to check for an open session, use session_id()
305 * instead; that will also tell you if the session was opened
306 * during the current request (in which case the cookie will
307 * be sent back to the client at the end of the script run).
309 * @return bool
311 function checkSessionCookie() {
312 return isset( $_COOKIE[session_name()] );
316 * Return the path portion of the request URI.
317 * @return string
319 function getRequestURL() {
320 if( isset( $_SERVER['REQUEST_URI'] ) ) {
321 $base = $_SERVER['REQUEST_URI'];
322 } elseif( isset( $_SERVER['SCRIPT_NAME'] ) ) {
323 // Probably IIS; doesn't set REQUEST_URI
324 $base = $_SERVER['SCRIPT_NAME'];
325 if( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
326 $base .= '?' . $_SERVER['QUERY_STRING'];
328 } else {
329 // This shouldn't happen!
330 throw new MWException( "Web server doesn't provide either " .
331 "REQUEST_URI or SCRIPT_NAME. Report details of your " .
332 "web server configuration to http://bugzilla.wikimedia.org/" );
334 // User-agents should not send a fragment with the URI, but
335 // if they do, and the web server passes it on to us, we
336 // need to strip it or we get false-positive redirect loops
337 // or weird output URLs
338 $hash = strpos( $base, '#' );
339 if( $hash !== false ) {
340 $base = substr( $base, 0, $hash );
342 if( $base{0} == '/' ) {
343 return $base;
344 } else {
345 // We may get paths with a host prepended; strip it.
346 return preg_replace( '!^[^:]+://[^/]+/!', '/', $base );
351 * Return the request URI with the canonical service and hostname.
352 * @return string
354 function getFullRequestURL() {
355 global $wgServer;
356 return $wgServer . $this->getRequestURL();
360 * Take an arbitrary query and rewrite the present URL to include it
361 * @param $query String: query string fragment; do not include initial '?'
362 * @return string
364 function appendQuery( $query ) {
365 global $wgTitle;
366 $basequery = '';
367 foreach( $_GET as $var => $val ) {
368 if ( $var == 'title' )
369 continue;
370 if ( is_array( $val ) )
371 /* This will happen given a request like
372 * http://en.wikipedia.org/w/index.php?title[]=Special:Userlogin&returnto[]=Main_Page
374 continue;
375 $basequery .= '&' . urlencode( $var ) . '=' . urlencode( $val );
377 $basequery .= '&' . $query;
379 # Trim the extra &
380 $basequery = substr( $basequery, 1 );
381 return $wgTitle->getLocalURL( $basequery );
385 * HTML-safe version of appendQuery().
386 * @param $query String: query string fragment; do not include initial '?'
387 * @return string
389 function escapeAppendQuery( $query ) {
390 return htmlspecialchars( $this->appendQuery( $query ) );
394 * Check for limit and offset parameters on the input, and return sensible
395 * defaults if not given. The limit must be positive and is capped at 5000.
396 * Offset must be positive but is not capped.
398 * @param $deflimit Integer: limit to use if no input and the user hasn't set the option.
399 * @param $optionname String: to specify an option other than rclimit to pull from.
400 * @return array first element is limit, second is offset
402 function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
403 global $wgUser;
405 $limit = $this->getInt( 'limit', 0 );
406 if( $limit < 0 ) $limit = 0;
407 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
408 $limit = (int)$wgUser->getOption( $optionname );
410 if( $limit <= 0 ) $limit = $deflimit;
411 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
413 $offset = $this->getInt( 'offset', 0 );
414 if( $offset < 0 ) $offset = 0;
416 return array( $limit, $offset );
420 * Return the path to the temporary file where PHP has stored the upload.
421 * @param $key String:
422 * @return string or NULL if no such file.
424 function getFileTempname( $key ) {
425 if( !isset( $_FILES[$key] ) ) {
426 return NULL;
428 return $_FILES[$key]['tmp_name'];
432 * Return the size of the upload, or 0.
433 * @param $key String:
434 * @return integer
436 function getFileSize( $key ) {
437 if( !isset( $_FILES[$key] ) ) {
438 return 0;
440 return $_FILES[$key]['size'];
444 * Return the upload error or 0
445 * @param $key String:
446 * @return integer
448 function getUploadError( $key ) {
449 if( !isset( $_FILES[$key] ) || !isset( $_FILES[$key]['error'] ) ) {
450 return 0/*UPLOAD_ERR_OK*/;
452 return $_FILES[$key]['error'];
456 * Return the original filename of the uploaded file, as reported by
457 * the submitting user agent. HTML-style character entities are
458 * interpreted and normalized to Unicode normalization form C, in part
459 * to deal with weird input from Safari with non-ASCII filenames.
461 * Other than this the name is not verified for being a safe filename.
463 * @param $key String:
464 * @return string or NULL if no such file.
466 function getFileName( $key ) {
467 if( !isset( $_FILES[$key] ) ) {
468 return NULL;
470 $name = $_FILES[$key]['name'];
472 # Safari sends filenames in HTML-encoded Unicode form D...
473 # Horrid and evil! Let's try to make some kind of sense of it.
474 $name = Sanitizer::decodeCharReferences( $name );
475 $name = UtfNormal::cleanUp( $name );
476 wfDebug( "WebRequest::getFileName() '" . $_FILES[$key]['name'] . "' normalized to '$name'\n" );
477 return $name;
481 * Return a handle to WebResponse style object, for setting cookies,
482 * headers and other stuff, for Request being worked on.
484 function response() {
485 /* Lazy initialization of response object for this request */
486 if (!is_object($this->_response)) {
487 $this->_response = new WebResponse;
489 return $this->_response;
495 * WebRequest clone which takes values from a provided array.
498 class FauxRequest extends WebRequest {
499 var $data = null;
500 var $wasPosted = false;
502 function FauxRequest( $data, $wasPosted = false ) {
503 if( is_array( $data ) ) {
504 $this->data = $data;
505 } else {
506 throw new MWException( "FauxRequest() got bogus data" );
508 $this->wasPosted = $wasPosted;
511 function getVal( $name, $default = NULL ) {
512 return $this->getGPCVal( $this->data, $name, $default );
515 function getText( $name, $default = '' ) {
516 # Override; don't recode since we're using internal data
517 return $this->getVal( $name, $default );
520 function getValues() {
521 return $this->data;
524 function wasPosted() {
525 return $this->wasPosted;
528 function checkSessionCookie() {
529 return false;
532 function getRequestURL() {
533 throw new MWException( 'FauxRequest::getRequestURL() not implemented' );
536 function appendQuery( $query ) {
537 throw new MWException( 'FauxRequest::appendQuery() not implemented' );