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