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