Fix for redirect.php
[lhc/web/wiklou.git] / includes / WebRequest.php
1 <?php
2 /**
3 * Deal with importing all those nasssty globals and things
4 * @package MediaWiki
5 */
6
7 # Copyright (C) 2003 Brion Vibber <brion@pobox.com>
8 # http://www.mediawiki.org/
9 #
10 # This program is free software; you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 2 of the License, or
13 # (at your option) any later version.
14 #
15 # This program is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
19 #
20 # You should have received a copy of the GNU General Public License along
21 # with this program; if not, write to the Free Software Foundation, Inc.,
22 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
23 # http://www.gnu.org/copyleft/gpl.html
24
25 /**
26 * The WebRequest class encapsulates getting at data passed in the
27 * URL or via a POSTed form, handling remove of "magic quotes" slashes,
28 * stripping illegal input characters and normalizing Unicode sequences.
29 *
30 * Usually this is used via a global singleton, $wgRequest. You should
31 * not create a second WebRequest object; make a FauxRequest object if
32 * you want to pass arbitrary data to some function in place of the web
33 * input.
34 *
35 * @package MediaWiki
36 */
37
38 /**
39 * Some entry points may use this file without first enabling the
40 * autoloader.
41 */
42 if ( !function_exists( '__autoload' ) ) {
43 require_once( dirname(__FILE__) . '/normal/UtfNormal.php' );
44 }
45
46 class WebRequest {
47 function WebRequest() {
48 $this->checkMagicQuotes();
49 global $wgUsePathInfo;
50 if( isset( $_SERVER['PATH_INFO'] ) && ($_SERVER['PATH_INFO'] != '') && $wgUsePathInfo ) {
51 # Stuff it!
52 $_GET['title'] = $_REQUEST['title'] =
53 substr( $_SERVER['PATH_INFO'], 1 );
54 }
55 }
56
57 private $_response;
58
59 /**
60 * Recursively strips slashes from the given array;
61 * used for undoing the evil that is magic_quotes_gpc.
62 * @param array &$arr will be modified
63 * @return array the original array
64 * @private
65 */
66 function &fix_magic_quotes( &$arr ) {
67 foreach( $arr as $key => $val ) {
68 if( is_array( $val ) ) {
69 $this->fix_magic_quotes( $arr[$key] );
70 } else {
71 $arr[$key] = stripslashes( $val );
72 }
73 }
74 return $arr;
75 }
76
77 /**
78 * If magic_quotes_gpc option is on, run the global arrays
79 * through fix_magic_quotes to strip out the stupid slashes.
80 * WARNING: This should only be done once! Running a second
81 * time could damage the values.
82 * @private
83 */
84 function checkMagicQuotes() {
85 if ( get_magic_quotes_gpc() ) {
86 $this->fix_magic_quotes( $_COOKIE );
87 $this->fix_magic_quotes( $_ENV );
88 $this->fix_magic_quotes( $_GET );
89 $this->fix_magic_quotes( $_POST );
90 $this->fix_magic_quotes( $_REQUEST );
91 $this->fix_magic_quotes( $_SERVER );
92 }
93 }
94
95 /**
96 * Recursively normalizes UTF-8 strings in the given array.
97 * @param array $data string or array
98 * @return cleaned-up version of the given
99 * @private
100 */
101 function normalizeUnicode( $data ) {
102 if( is_array( $data ) ) {
103 foreach( $data as $key => $val ) {
104 $data[$key] = $this->normalizeUnicode( $val );
105 }
106 } else {
107 $data = UtfNormal::cleanUp( $data );
108 }
109 return $data;
110 }
111
112 /**
113 * Fetch a value from the given array or return $default if it's not set.
114 *
115 * @param array $arr
116 * @param string $name
117 * @param mixed $default
118 * @return mixed
119 * @private
120 */
121 function getGPCVal( $arr, $name, $default ) {
122 if( isset( $arr[$name] ) ) {
123 global $wgContLang;
124 $data = $arr[$name];
125 if( isset( $_GET[$name] ) && !is_array( $data ) ) {
126 # Check for alternate/legacy character encoding.
127 if( isset( $wgContLang ) ) {
128 $data = $wgContLang->checkTitleEncoding( $data );
129 }
130 }
131 $data = $this->normalizeUnicode( $data );
132 return $data;
133 } else {
134 return $default;
135 }
136 }
137
138 /**
139 * Fetch a scalar from the input or return $default if it's not set.
140 * Returns a string. Arrays are discarded.
141 *
142 * @param string $name
143 * @param string $default optional default (or NULL)
144 * @return string
145 */
146 function getVal( $name, $default = NULL ) {
147 $val = $this->getGPCVal( $_REQUEST, $name, $default );
148 if( is_array( $val ) ) {
149 $val = $default;
150 }
151 if( is_null( $val ) ) {
152 return null;
153 } else {
154 return (string)$val;
155 }
156 }
157
158 /**
159 * Fetch an array from the input or return $default if it's not set.
160 * If source was scalar, will return an array with a single element.
161 * If no source and no default, returns NULL.
162 *
163 * @param string $name
164 * @param array $default optional default (or NULL)
165 * @return array
166 */
167 function getArray( $name, $default = NULL ) {
168 $val = $this->getGPCVal( $_REQUEST, $name, $default );
169 if( is_null( $val ) ) {
170 return null;
171 } else {
172 return (array)$val;
173 }
174 }
175
176 /**
177 * Fetch an array of integers, or return $default if it's not set.
178 * If source was scalar, will return an array with a single element.
179 * If no source and no default, returns NULL.
180 * If an array is returned, contents are guaranteed to be integers.
181 *
182 * @param string $name
183 * @param array $default option default (or NULL)
184 * @return array of ints
185 */
186 function getIntArray( $name, $default = NULL ) {
187 $val = $this->getArray( $name, $default );
188 if( is_array( $val ) ) {
189 $val = array_map( 'intval', $val );
190 }
191 return $val;
192 }
193
194 /**
195 * Fetch an integer value from the input or return $default if not set.
196 * Guaranteed to return an integer; non-numeric input will typically
197 * return 0.
198 * @param string $name
199 * @param int $default
200 * @return int
201 */
202 function getInt( $name, $default = 0 ) {
203 return intval( $this->getVal( $name, $default ) );
204 }
205
206 /**
207 * Fetch an integer value from the input or return null if empty.
208 * Guaranteed to return an integer or null; non-numeric input will
209 * typically return null.
210 * @param string $name
211 * @return int
212 */
213 function getIntOrNull( $name ) {
214 $val = $this->getVal( $name );
215 return is_numeric( $val )
216 ? intval( $val )
217 : null;
218 }
219
220 /**
221 * Fetch a boolean value from the input or return $default if not set.
222 * Guaranteed to return true or false, with normal PHP semantics for
223 * boolean interpretation of strings.
224 * @param string $name
225 * @param bool $default
226 * @return bool
227 */
228 function getBool( $name, $default = false ) {
229 return $this->getVal( $name, $default ) ? true : false;
230 }
231
232 /**
233 * Return true if the named value is set in the input, whatever that
234 * value is (even "0"). Return false if the named value is not set.
235 * Example use is checking for the presence of check boxes in forms.
236 * @param string $name
237 * @return bool
238 */
239 function getCheck( $name ) {
240 # Checkboxes and buttons are only present when clicked
241 # Presence connotes truth, abscense false
242 $val = $this->getVal( $name, NULL );
243 return isset( $val );
244 }
245
246 /**
247 * Fetch a text string from the given array or return $default if it's not
248 * set. \r is stripped from the text, and with some language modules there
249 * is an input transliteration applied. This should generally be used for
250 * form <textarea> and <input> fields.
251 *
252 * @param string $name
253 * @param string $default optional
254 * @return string
255 */
256 function getText( $name, $default = '' ) {
257 global $wgContLang;
258 $val = $this->getVal( $name, $default );
259 return str_replace( "\r\n", "\n",
260 $wgContLang->recodeInput( $val ) );
261 }
262
263 /**
264 * Extracts the given named values into an array.
265 * If no arguments are given, returns all input values.
266 * No transformation is performed on the values.
267 */
268 function getValues() {
269 $names = func_get_args();
270 if ( count( $names ) == 0 ) {
271 $names = array_keys( $_REQUEST );
272 }
273
274 $retVal = array();
275 foreach ( $names as $name ) {
276 $value = $this->getVal( $name );
277 if ( !is_null( $value ) ) {
278 $retVal[$name] = $value;
279 }
280 }
281 return $retVal;
282 }
283
284 /**
285 * Returns true if the present request was reached by a POST operation,
286 * false otherwise (GET, HEAD, or command-line).
287 *
288 * Note that values retrieved by the object may come from the
289 * GET URL etc even on a POST request.
290 *
291 * @return bool
292 */
293 function wasPosted() {
294 return $_SERVER['REQUEST_METHOD'] == 'POST';
295 }
296
297 /**
298 * Returns true if there is a session cookie set.
299 * This does not necessarily mean that the user is logged in!
300 *
301 * @return bool
302 */
303 function checkSessionCookie() {
304 return isset( $_COOKIE[ini_get('session.name')] );
305 }
306
307 /**
308 * Return the path portion of the request URI.
309 * @return string
310 */
311 function getRequestURL() {
312 $base = $_SERVER['REQUEST_URI'];
313 if( $base{0} == '/' ) {
314 return $base;
315 } else {
316 // We may get paths with a host prepended; strip it.
317 return preg_replace( '!^[^:]+://[^/]+/!', '/', $base );
318 }
319 }
320
321 /**
322 * Return the request URI with the canonical service and hostname.
323 * @return string
324 */
325 function getFullRequestURL() {
326 global $wgServer;
327 return $wgServer . $this->getRequestURL();
328 }
329
330 /**
331 * Take an arbitrary query and rewrite the present URL to include it
332 * @param $query String: query string fragment; do not include initial '?'
333 * @return string
334 */
335 function appendQuery( $query ) {
336 global $wgTitle;
337 $basequery = '';
338 foreach( $_GET as $var => $val ) {
339 if ( $var == 'title' )
340 continue;
341 if ( is_array( $val ) )
342 /* This will happen given a request like
343 * http://en.wikipedia.org/w/index.php?title[]=Special:Userlogin&returnto[]=Main_Page
344 */
345 continue;
346 $basequery .= '&' . urlencode( $var ) . '=' . urlencode( $val );
347 }
348 $basequery .= '&' . $query;
349
350 # Trim the extra &
351 $basequery = substr( $basequery, 1 );
352 return $wgTitle->getLocalURL( $basequery );
353 }
354
355 /**
356 * HTML-safe version of appendQuery().
357 * @param $query String: query string fragment; do not include initial '?'
358 * @return string
359 */
360 function escapeAppendQuery( $query ) {
361 return htmlspecialchars( $this->appendQuery( $query ) );
362 }
363
364 /**
365 * Check for limit and offset parameters on the input, and return sensible
366 * defaults if not given. The limit must be positive and is capped at 5000.
367 * Offset must be positive but is not capped.
368 *
369 * @param $deflimit Integer: limit to use if no input and the user hasn't set the option.
370 * @param $optionname String: to specify an option other than rclimit to pull from.
371 * @return array first element is limit, second is offset
372 */
373 function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
374 global $wgUser;
375
376 $limit = $this->getInt( 'limit', 0 );
377 if( $limit < 0 ) $limit = 0;
378 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
379 $limit = (int)$wgUser->getOption( $optionname );
380 }
381 if( $limit <= 0 ) $limit = $deflimit;
382 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
383
384 $offset = $this->getInt( 'offset', 0 );
385 if( $offset < 0 ) $offset = 0;
386
387 return array( $limit, $offset );
388 }
389
390 /**
391 * Return the path to the temporary file where PHP has stored the upload.
392 * @param $key String:
393 * @return string or NULL if no such file.
394 */
395 function getFileTempname( $key ) {
396 if( !isset( $_FILES[$key] ) ) {
397 return NULL;
398 }
399 return $_FILES[$key]['tmp_name'];
400 }
401
402 /**
403 * Return the size of the upload, or 0.
404 * @param $key String:
405 * @return integer
406 */
407 function getFileSize( $key ) {
408 if( !isset( $_FILES[$key] ) ) {
409 return 0;
410 }
411 return $_FILES[$key]['size'];
412 }
413
414 /**
415 * Return the upload error or 0
416 * @param $key String:
417 * @return integer
418 */
419 function getUploadError( $key ) {
420 if( !isset( $_FILES[$key] ) || !isset( $_FILES[$key]['error'] ) ) {
421 return 0/*UPLOAD_ERR_OK*/;
422 }
423 return $_FILES[$key]['error'];
424 }
425
426 /**
427 * Return the original filename of the uploaded file, as reported by
428 * the submitting user agent. HTML-style character entities are
429 * interpreted and normalized to Unicode normalization form C, in part
430 * to deal with weird input from Safari with non-ASCII filenames.
431 *
432 * Other than this the name is not verified for being a safe filename.
433 *
434 * @param $key String:
435 * @return string or NULL if no such file.
436 */
437 function getFileName( $key ) {
438 if( !isset( $_FILES[$key] ) ) {
439 return NULL;
440 }
441 $name = $_FILES[$key]['name'];
442
443 # Safari sends filenames in HTML-encoded Unicode form D...
444 # Horrid and evil! Let's try to make some kind of sense of it.
445 $name = Sanitizer::decodeCharReferences( $name );
446 $name = UtfNormal::cleanUp( $name );
447 wfDebug( "WebRequest::getFileName() '" . $_FILES[$key]['name'] . "' normalized to '$name'\n" );
448 return $name;
449 }
450
451 /**
452 * Return a handle to WebResponse style object, for setting cookies,
453 * headers and other stuff, for Request being worked on.
454 */
455 function response() {
456 /* Lazy initialization of response object for this request */
457 if (!is_object($this->_response)) {
458 $this->_response = new WebResponse;
459 }
460 return $this->_response;
461 }
462
463 }
464
465 /**
466 * WebRequest clone which takes values from a provided array.
467 *
468 * @package MediaWiki
469 */
470 class FauxRequest extends WebRequest {
471 var $data = null;
472 var $wasPosted = false;
473
474 function FauxRequest( $data, $wasPosted = false ) {
475 if( is_array( $data ) ) {
476 $this->data = $data;
477 } else {
478 throw new MWException( "FauxRequest() got bogus data" );
479 }
480 $this->wasPosted = $wasPosted;
481 }
482
483 function getVal( $name, $default = NULL ) {
484 return $this->getGPCVal( $this->data, $name, $default );
485 }
486
487 function getText( $name, $default = '' ) {
488 # Override; don't recode since we're using internal data
489 return $this->getVal( $name, $default );
490 }
491
492 function getValues() {
493 return $this->data;
494 }
495
496 function wasPosted() {
497 return $this->wasPosted;
498 }
499
500 function checkSessionCookie() {
501 return false;
502 }
503
504 function getRequestURL() {
505 throw new MWException( 'FauxRequest::getRequestURL() not implemented' );
506 }
507
508 function appendQuery( $query ) {
509 throw new MWException( 'FauxRequest::appendQuery() not implemented' );
510 }
511
512 }
513
514 ?>