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