Rename constructors to __constructor
[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 __construct() {
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 if( isset( $_SERVER['REQUEST_URI'] ) ) {
318 $base = $_SERVER['REQUEST_URI'];
319 } elseif( isset( $_SERVER['SCRIPT_NAME'] ) ) {
320 // Probably IIS; doesn't set REQUEST_URI
321 $base = $_SERVER['SCRIPT_NAME'];
322 if( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
323 $base .= '?' . $_SERVER['QUERY_STRING'];
324 }
325 } else {
326 // This shouldn't happen!
327 throw new MWException( "Web server doesn't provide either " .
328 "REQUEST_URI or SCRIPT_NAME. Report details of your " .
329 "web server configuration to http://bugzilla.wikimedia.org/" );
330 }
331 if( $base{0} == '/' ) {
332 return $base;
333 } else {
334 // We may get paths with a host prepended; strip it.
335 return preg_replace( '!^[^:]+://[^/]+/!', '/', $base );
336 }
337 }
338
339 /**
340 * Return the request URI with the canonical service and hostname.
341 * @return string
342 */
343 function getFullRequestURL() {
344 global $wgServer;
345 return $wgServer . $this->getRequestURL();
346 }
347
348 /**
349 * Take an arbitrary query and rewrite the present URL to include it
350 * @param $query String: query string fragment; do not include initial '?'
351 * @return string
352 */
353 function appendQuery( $query ) {
354 global $wgTitle;
355 $basequery = '';
356 foreach( $_GET as $var => $val ) {
357 if ( $var == 'title' )
358 continue;
359 if ( is_array( $val ) )
360 /* This will happen given a request like
361 * http://en.wikipedia.org/w/index.php?title[]=Special:Userlogin&returnto[]=Main_Page
362 */
363 continue;
364 $basequery .= '&' . urlencode( $var ) . '=' . urlencode( $val );
365 }
366 $basequery .= '&' . $query;
367
368 # Trim the extra &
369 $basequery = substr( $basequery, 1 );
370 return $wgTitle->getLocalURL( $basequery );
371 }
372
373 /**
374 * HTML-safe version of appendQuery().
375 * @param $query String: query string fragment; do not include initial '?'
376 * @return string
377 */
378 function escapeAppendQuery( $query ) {
379 return htmlspecialchars( $this->appendQuery( $query ) );
380 }
381
382 /**
383 * Check for limit and offset parameters on the input, and return sensible
384 * defaults if not given. The limit must be positive and is capped at 5000.
385 * Offset must be positive but is not capped.
386 *
387 * @param $deflimit Integer: limit to use if no input and the user hasn't set the option.
388 * @param $optionname String: to specify an option other than rclimit to pull from.
389 * @return array first element is limit, second is offset
390 */
391 function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
392 global $wgUser;
393
394 $limit = $this->getInt( 'limit', 0 );
395 if( $limit < 0 ) $limit = 0;
396 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
397 $limit = (int)$wgUser->getOption( $optionname );
398 }
399 if( $limit <= 0 ) $limit = $deflimit;
400 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
401
402 $offset = $this->getInt( 'offset', 0 );
403 if( $offset < 0 ) $offset = 0;
404
405 return array( $limit, $offset );
406 }
407
408 /**
409 * Return the path to the temporary file where PHP has stored the upload.
410 * @param $key String:
411 * @return string or NULL if no such file.
412 */
413 function getFileTempname( $key ) {
414 if( !isset( $_FILES[$key] ) ) {
415 return NULL;
416 }
417 return $_FILES[$key]['tmp_name'];
418 }
419
420 /**
421 * Return the size of the upload, or 0.
422 * @param $key String:
423 * @return integer
424 */
425 function getFileSize( $key ) {
426 if( !isset( $_FILES[$key] ) ) {
427 return 0;
428 }
429 return $_FILES[$key]['size'];
430 }
431
432 /**
433 * Return the upload error or 0
434 * @param $key String:
435 * @return integer
436 */
437 function getUploadError( $key ) {
438 if( !isset( $_FILES[$key] ) || !isset( $_FILES[$key]['error'] ) ) {
439 return 0/*UPLOAD_ERR_OK*/;
440 }
441 return $_FILES[$key]['error'];
442 }
443
444 /**
445 * Return the original filename of the uploaded file, as reported by
446 * the submitting user agent. HTML-style character entities are
447 * interpreted and normalized to Unicode normalization form C, in part
448 * to deal with weird input from Safari with non-ASCII filenames.
449 *
450 * Other than this the name is not verified for being a safe filename.
451 *
452 * @param $key String:
453 * @return string or NULL if no such file.
454 */
455 function getFileName( $key ) {
456 if( !isset( $_FILES[$key] ) ) {
457 return NULL;
458 }
459 $name = $_FILES[$key]['name'];
460
461 # Safari sends filenames in HTML-encoded Unicode form D...
462 # Horrid and evil! Let's try to make some kind of sense of it.
463 $name = Sanitizer::decodeCharReferences( $name );
464 $name = UtfNormal::cleanUp( $name );
465 wfDebug( "WebRequest::getFileName() '" . $_FILES[$key]['name'] . "' normalized to '$name'\n" );
466 return $name;
467 }
468
469 /**
470 * Return a handle to WebResponse style object, for setting cookies,
471 * headers and other stuff, for Request being worked on.
472 */
473 function response() {
474 /* Lazy initialization of response object for this request */
475 if (!is_object($this->_response)) {
476 $this->_response = new WebResponse;
477 }
478 return $this->_response;
479 }
480
481 }
482
483 /**
484 * WebRequest clone which takes values from a provided array.
485 *
486 * @package MediaWiki
487 */
488 class FauxRequest extends WebRequest {
489 var $data = null;
490 var $wasPosted = false;
491
492 function FauxRequest( $data, $wasPosted = false ) {
493 if( is_array( $data ) ) {
494 $this->data = $data;
495 } else {
496 throw new MWException( "FauxRequest() got bogus data" );
497 }
498 $this->wasPosted = $wasPosted;
499 }
500
501 function getVal( $name, $default = NULL ) {
502 return $this->getGPCVal( $this->data, $name, $default );
503 }
504
505 function getText( $name, $default = '' ) {
506 # Override; don't recode since we're using internal data
507 return $this->getVal( $name, $default );
508 }
509
510 function getValues() {
511 return $this->data;
512 }
513
514 function wasPosted() {
515 return $this->wasPosted;
516 }
517
518 function checkSessionCookie() {
519 return false;
520 }
521
522 function getRequestURL() {
523 throw new MWException( 'FauxRequest::getRequestURL() not implemented' );
524 }
525
526 function appendQuery( $query ) {
527 throw new MWException( 'FauxRequest::appendQuery() not implemented' );
528 }
529
530 }
531
532 ?>