debugging
[lhc/web/wiklou.git] / includes / WebRequest.php
1 <?php
2 /**
3 * Deal with importing all those nasssty globals and things
4 */
5
6 # Copyright (C) 2003 Brion Vibber <brion@pobox.com>
7 # http://www.mediawiki.org/
8 #
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.
13 #
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.
18 #
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
23
24
25 /**
26 * Some entry points may use this file without first enabling the
27 * autoloader.
28 */
29 if ( !function_exists( '__autoload' ) ) {
30 require_once( dirname(__FILE__) . '/normal/UtfNormal.php' );
31 }
32
33 /**
34 * The WebRequest class encapsulates getting at data passed in the
35 * URL or via a POSTed form, handling remove of "magic quotes" slashes,
36 * stripping illegal input characters and normalizing Unicode sequences.
37 *
38 * Usually this is used via a global singleton, $wgRequest. You should
39 * not create a second WebRequest object; make a FauxRequest object if
40 * you want to pass arbitrary data to some function in place of the web
41 * input.
42 *
43 */
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 );
56 }
57 }
58 }
59
60 private $_response;
61
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
68 */
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 );
75 }
76 }
77 return $arr;
78 }
79
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
86 */
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 );
95 }
96 }
97
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
103 */
104 function normalizeUnicode( $data ) {
105 if( is_array( $data ) ) {
106 foreach( $data as $key => $val ) {
107 $data[$key] = $this->normalizeUnicode( $val );
108 }
109 } else {
110 $data = UtfNormal::cleanUp( $data );
111 }
112 return $data;
113 }
114
115 /**
116 * Fetch a value from the given array or return $default if it's not set.
117 *
118 * @param array $arr
119 * @param string $name
120 * @param mixed $default
121 * @return mixed
122 * @private
123 */
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 );
132 }
133 }
134 $data = $this->normalizeUnicode( $data );
135 return $data;
136 } else {
137 return $default;
138 }
139 }
140
141 /**
142 * Fetch a scalar from the input or return $default if it's not set.
143 * Returns a string. Arrays are discarded. Useful for
144 * non-freeform text inputs (e.g. predefined internal text keys
145 * selected by a drop-down menu). For freeform input, see getText().
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. Used for user-supplied freeform text
256 * input (for which input transformations may be required - e.g. Esperanto
257 * x-coding).
258 *
259 * @param string $name
260 * @param string $default optional
261 * @return string
262 */
263 function getText( $name, $default = '' ) {
264 global $wgContLang;
265 $val = $this->getVal( $name, $default );
266 return str_replace( "\r\n", "\n",
267 $wgContLang->recodeInput( $val ) );
268 }
269
270 /**
271 * Extracts the given named values into an array.
272 * If no arguments are given, returns all input values.
273 * No transformation is performed on the values.
274 */
275 function getValues() {
276 $names = func_get_args();
277 if ( count( $names ) == 0 ) {
278 $names = array_keys( $_REQUEST );
279 }
280
281 $retVal = array();
282 foreach ( $names as $name ) {
283 $value = $this->getVal( $name );
284 if ( !is_null( $value ) ) {
285 $retVal[$name] = $value;
286 }
287 }
288 return $retVal;
289 }
290
291 /**
292 * Returns true if the present request was reached by a POST operation,
293 * false otherwise (GET, HEAD, or command-line).
294 *
295 * Note that values retrieved by the object may come from the
296 * GET URL etc even on a POST request.
297 *
298 * @return bool
299 */
300 function wasPosted() {
301 return $_SERVER['REQUEST_METHOD'] == 'POST';
302 }
303
304 /**
305 * Returns true if there is a session cookie set.
306 * This does not necessarily mean that the user is logged in!
307 *
308 * If you want to check for an open session, use session_id()
309 * instead; that will also tell you if the session was opened
310 * during the current request (in which case the cookie will
311 * be sent back to the client at the end of the script run).
312 *
313 * @return bool
314 */
315 function checkSessionCookie() {
316 return isset( $_COOKIE[session_name()] );
317 }
318
319 /**
320 * Return the path portion of the request URI.
321 * @return string
322 */
323 function getRequestURL() {
324 if( isset( $_SERVER['REQUEST_URI'] ) ) {
325 $base = $_SERVER['REQUEST_URI'];
326 } elseif( isset( $_SERVER['SCRIPT_NAME'] ) ) {
327 // Probably IIS; doesn't set REQUEST_URI
328 $base = $_SERVER['SCRIPT_NAME'];
329 if( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
330 $base .= '?' . $_SERVER['QUERY_STRING'];
331 }
332 } else {
333 // This shouldn't happen!
334 throw new MWException( "Web server doesn't provide either " .
335 "REQUEST_URI or SCRIPT_NAME. Report details of your " .
336 "web server configuration to http://bugzilla.wikimedia.org/" );
337 }
338 // User-agents should not send a fragment with the URI, but
339 // if they do, and the web server passes it on to us, we
340 // need to strip it or we get false-positive redirect loops
341 // or weird output URLs
342 $hash = strpos( $base, '#' );
343 if( $hash !== false ) {
344 $base = substr( $base, 0, $hash );
345 }
346 if( $base{0} == '/' ) {
347 return $base;
348 } else {
349 // We may get paths with a host prepended; strip it.
350 return preg_replace( '!^[^:]+://[^/]+/!', '/', $base );
351 }
352 }
353
354 /**
355 * Return the request URI with the canonical service and hostname.
356 * @return string
357 */
358 function getFullRequestURL() {
359 global $wgServer;
360 return $wgServer . $this->getRequestURL();
361 }
362
363 /**
364 * Take an arbitrary query and rewrite the present URL to include it
365 * @param $query String: query string fragment; do not include initial '?'
366 * @return string
367 */
368 function appendQuery( $query ) {
369 global $wgTitle;
370 $basequery = '';
371 foreach( $_GET as $var => $val ) {
372 if ( $var == 'title' )
373 continue;
374 if ( is_array( $val ) )
375 /* This will happen given a request like
376 * http://en.wikipedia.org/w/index.php?title[]=Special:Userlogin&returnto[]=Main_Page
377 */
378 continue;
379 $basequery .= '&' . urlencode( $var ) . '=' . urlencode( $val );
380 }
381 $basequery .= '&' . $query;
382
383 # Trim the extra &
384 $basequery = substr( $basequery, 1 );
385 return $wgTitle->getLocalURL( $basequery );
386 }
387
388 /**
389 * HTML-safe version of appendQuery().
390 * @param $query String: query string fragment; do not include initial '?'
391 * @return string
392 */
393 function escapeAppendQuery( $query ) {
394 return htmlspecialchars( $this->appendQuery( $query ) );
395 }
396
397 /**
398 * Check for limit and offset parameters on the input, and return sensible
399 * defaults if not given. The limit must be positive and is capped at 5000.
400 * Offset must be positive but is not capped.
401 *
402 * @param $deflimit Integer: limit to use if no input and the user hasn't set the option.
403 * @param $optionname String: to specify an option other than rclimit to pull from.
404 * @return array first element is limit, second is offset
405 */
406 function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
407 global $wgUser;
408
409 $limit = $this->getInt( 'limit', 0 );
410 if( $limit < 0 ) $limit = 0;
411 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
412 $limit = (int)$wgUser->getOption( $optionname );
413 }
414 if( $limit <= 0 ) $limit = $deflimit;
415 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
416
417 $offset = $this->getInt( 'offset', 0 );
418 if( $offset < 0 ) $offset = 0;
419
420 return array( $limit, $offset );
421 }
422
423 /**
424 * Return the path to the temporary file where PHP has stored the upload.
425 * @param $key String:
426 * @return string or NULL if no such file.
427 */
428 function getFileTempname( $key ) {
429 if( !isset( $_FILES[$key] ) ) {
430 return NULL;
431 }
432 return $_FILES[$key]['tmp_name'];
433 }
434
435 /**
436 * Return the size of the upload, or 0.
437 * @param $key String:
438 * @return integer
439 */
440 function getFileSize( $key ) {
441 if( !isset( $_FILES[$key] ) ) {
442 return 0;
443 }
444 return $_FILES[$key]['size'];
445 }
446
447 /**
448 * Return the upload error or 0
449 * @param $key String:
450 * @return integer
451 */
452 function getUploadError( $key ) {
453 if( !isset( $_FILES[$key] ) || !isset( $_FILES[$key]['error'] ) ) {
454 return 0/*UPLOAD_ERR_OK*/;
455 }
456 return $_FILES[$key]['error'];
457 }
458
459 /**
460 * Return the original filename of the uploaded file, as reported by
461 * the submitting user agent. HTML-style character entities are
462 * interpreted and normalized to Unicode normalization form C, in part
463 * to deal with weird input from Safari with non-ASCII filenames.
464 *
465 * Other than this the name is not verified for being a safe filename.
466 *
467 * @param $key String:
468 * @return string or NULL if no such file.
469 */
470 function getFileName( $key ) {
471 if( !isset( $_FILES[$key] ) ) {
472 return NULL;
473 }
474 $name = $_FILES[$key]['name'];
475
476 # Safari sends filenames in HTML-encoded Unicode form D...
477 # Horrid and evil! Let's try to make some kind of sense of it.
478 $name = Sanitizer::decodeCharReferences( $name );
479 $name = UtfNormal::cleanUp( $name );
480 wfDebug( "WebRequest::getFileName() '" . $_FILES[$key]['name'] . "' normalized to '$name'\n" );
481 return $name;
482 }
483
484 /**
485 * Return a handle to WebResponse style object, for setting cookies,
486 * headers and other stuff, for Request being worked on.
487 */
488 function response() {
489 /* Lazy initialization of response object for this request */
490 if (!is_object($this->_response)) {
491 $this->_response = new WebResponse;
492 }
493 return $this->_response;
494 }
495
496 }
497
498 /**
499 * WebRequest clone which takes values from a provided array.
500 *
501 */
502 class FauxRequest extends WebRequest {
503 var $data = null;
504 var $wasPosted = false;
505
506 function FauxRequest( $data, $wasPosted = false ) {
507 if( is_array( $data ) ) {
508 $this->data = $data;
509 } else {
510 throw new MWException( "FauxRequest() got bogus data" );
511 }
512 $this->wasPosted = $wasPosted;
513 }
514
515 function getVal( $name, $default = NULL ) {
516 return $this->getGPCVal( $this->data, $name, $default );
517 }
518
519 function getText( $name, $default = '' ) {
520 # Override; don't recode since we're using internal data
521 return $this->getVal( $name, $default );
522 }
523
524 function getValues() {
525 return $this->data;
526 }
527
528 function wasPosted() {
529 return $this->wasPosted;
530 }
531
532 function checkSessionCookie() {
533 return false;
534 }
535
536 function getRequestURL() {
537 throw new MWException( 'FauxRequest::getRequestURL() not implemented' );
538 }
539
540 function appendQuery( $query ) {
541 throw new MWException( 'FauxRequest::appendQuery() not implemented' );
542 }
543
544 }
545
546 ?>