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