Self-revert 40530, 40531. Too many things still depend on $_GET and $_POST. Needs...
[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 * @ingroup HTTP
44 */
45 class WebRequest {
46 var $data = array();
47 var $headers;
48 private $_response;
49
50 function __construct() {
51 /// @fixme This preemptive de-quoting can interfere with other web libraries
52 /// and increases our memory footprint. It would be cleaner to do on
53 /// demand; but currently we have no wrapper for $_SERVER etc.
54 $this->checkMagicQuotes();
55
56 // POST overrides GET data
57 // We don't use $_REQUEST here to avoid interference from cookies...
58 $this->data = wfArrayMerge( $_GET, $_POST );
59 }
60
61 /**
62 * Check for title, action, and/or variant data in the URL
63 * and interpolate it into the GET variables.
64 * This should only be run after $wgContLang is available,
65 * as we may need the list of language variants to determine
66 * available variant URLs.
67 */
68 function interpolateTitle() {
69 global $wgUsePathInfo;
70 if ( $wgUsePathInfo ) {
71 // PATH_INFO is mangled due to http://bugs.php.net/bug.php?id=31892
72 // And also by Apache 2.x, double slashes are converted to single slashes.
73 // So we will use REQUEST_URI if possible.
74 $matches = array();
75 if ( !empty( $_SERVER['REQUEST_URI'] ) ) {
76 // Slurp out the path portion to examine...
77 $url = $_SERVER['REQUEST_URI'];
78 if ( !preg_match( '!^https?://!', $url ) ) {
79 $url = 'http://unused' . $url;
80 }
81 $a = parse_url( $url );
82 if( $a ) {
83 $path = isset( $a['path'] ) ? $a['path'] : '';
84
85 global $wgScript;
86 if( $path == $wgScript ) {
87 // Script inside a rewrite path?
88 // Abort to keep from breaking...
89 return;
90 }
91 // Raw PATH_INFO style
92 $matches = $this->extractTitle( $path, "$wgScript/$1" );
93
94 global $wgArticlePath;
95 if( !$matches && $wgArticlePath ) {
96 $matches = $this->extractTitle( $path, $wgArticlePath );
97 }
98
99 global $wgActionPaths;
100 if( !$matches && $wgActionPaths ) {
101 $matches = $this->extractTitle( $path, $wgActionPaths, 'action' );
102 }
103
104 global $wgVariantArticlePath, $wgContLang;
105 if( !$matches && $wgVariantArticlePath ) {
106 $variantPaths = array();
107 foreach( $wgContLang->getVariants() as $variant ) {
108 $variantPaths[$variant] =
109 str_replace( '$2', $variant, $wgVariantArticlePath );
110 }
111 $matches = $this->extractTitle( $path, $variantPaths, 'variant' );
112 }
113 }
114 } elseif ( isset( $_SERVER['ORIG_PATH_INFO'] ) && $_SERVER['ORIG_PATH_INFO'] != '' ) {
115 // Mangled PATH_INFO
116 // http://bugs.php.net/bug.php?id=31892
117 // Also reported when ini_get('cgi.fix_pathinfo')==false
118 $matches['title'] = substr( $_SERVER['ORIG_PATH_INFO'], 1 );
119
120 } elseif ( isset( $_SERVER['PATH_INFO'] ) && ($_SERVER['PATH_INFO'] != '') ) {
121 // Regular old PATH_INFO yay
122 $matches['title'] = substr( $_SERVER['PATH_INFO'], 1 );
123 }
124 foreach( $matches as $key => $val) {
125 $this->data[$key] = $_GET[$key] = $_REQUEST[$key] = $val;
126 }
127 }
128 }
129
130 /**
131 * Internal URL rewriting function; tries to extract page title and,
132 * optionally, one other fixed parameter value from a URL path.
133 *
134 * @param $path string: the URL path given from the client
135 * @param $bases array: one or more URLs, optionally with $1 at the end
136 * @param $key string: if provided, the matching key in $bases will be
137 * passed on as the value of this URL parameter
138 * @return array of URL variables to interpolate; empty if no match
139 */
140 private function extractTitle( $path, $bases, $key=false ) {
141 foreach( (array)$bases as $keyValue => $base ) {
142 // Find the part after $wgArticlePath
143 $base = str_replace( '$1', '', $base );
144 $baseLen = strlen( $base );
145 if( substr( $path, 0, $baseLen ) == $base ) {
146 $raw = substr( $path, $baseLen );
147 if( $raw !== '' ) {
148 $matches = array( 'title' => rawurldecode( $raw ) );
149 if( $key ) {
150 $matches[$key] = $keyValue;
151 }
152 return $matches;
153 }
154 }
155 }
156 return array();
157 }
158
159 /**
160 * Recursively strips slashes from the given array;
161 * used for undoing the evil that is magic_quotes_gpc.
162 * @param $arr array: will be modified
163 * @return array the original array
164 * @private
165 */
166 function &fix_magic_quotes( &$arr ) {
167 foreach( $arr as $key => $val ) {
168 if( is_array( $val ) ) {
169 $this->fix_magic_quotes( $arr[$key] );
170 } else {
171 $arr[$key] = stripslashes( $val );
172 }
173 }
174 return $arr;
175 }
176
177 /**
178 * If magic_quotes_gpc option is on, run the global arrays
179 * through fix_magic_quotes to strip out the stupid slashes.
180 * WARNING: This should only be done once! Running a second
181 * time could damage the values.
182 * @private
183 */
184 function checkMagicQuotes() {
185 if ( function_exists( 'get_magic_quotes_gpc' ) && get_magic_quotes_gpc() ) {
186 $this->fix_magic_quotes( $_COOKIE );
187 $this->fix_magic_quotes( $_ENV );
188 $this->fix_magic_quotes( $_GET );
189 $this->fix_magic_quotes( $_POST );
190 $this->fix_magic_quotes( $_REQUEST );
191 $this->fix_magic_quotes( $_SERVER );
192 }
193 }
194
195 /**
196 * Recursively normalizes UTF-8 strings in the given array.
197 * @param $data string or array
198 * @return cleaned-up version of the given
199 * @private
200 */
201 function normalizeUnicode( $data ) {
202 if( is_array( $data ) ) {
203 foreach( $data as $key => $val ) {
204 $data[$key] = $this->normalizeUnicode( $val );
205 }
206 } else {
207 $data = UtfNormal::cleanUp( $data );
208 }
209 return $data;
210 }
211
212 /**
213 * Fetch a value from the given array or return $default if it's not set.
214 *
215 * @param $arr array
216 * @param $name string
217 * @param $default mixed
218 * @return mixed
219 * @private
220 */
221 function getGPCVal( $arr, $name, $default ) {
222 if( isset( $arr[$name] ) ) {
223 global $wgContLang;
224 $data = $arr[$name];
225 if( isset( $_GET[$name] ) && !is_array( $data ) ) {
226 # Check for alternate/legacy character encoding.
227 if( isset( $wgContLang ) ) {
228 $data = $wgContLang->checkTitleEncoding( $data );
229 }
230 }
231 $data = $this->normalizeUnicode( $data );
232 return $data;
233 } else {
234 return $default;
235 }
236 }
237
238 /**
239 * Fetch a scalar from the input or return $default if it's not set.
240 * Returns a string. Arrays are discarded. Useful for
241 * non-freeform text inputs (e.g. predefined internal text keys
242 * selected by a drop-down menu). For freeform input, see getText().
243 *
244 * @param $name string
245 * @param $default string: optional default (or NULL)
246 * @return string
247 */
248 function getVal( $name, $default = NULL ) {
249 $val = $this->getGPCVal( $this->data, $name, $default );
250 if( is_array( $val ) ) {
251 $val = $default;
252 }
253 if( is_null( $val ) ) {
254 return null;
255 } else {
256 return (string)$val;
257 }
258 }
259
260 /**
261 * Fetch an array from the input or return $default if it's not set.
262 * If source was scalar, will return an array with a single element.
263 * If no source and no default, returns NULL.
264 *
265 * @param $name string
266 * @param $default array: optional default (or NULL)
267 * @return array
268 */
269 function getArray( $name, $default = NULL ) {
270 $val = $this->getGPCVal( $this->data, $name, $default );
271 if( is_null( $val ) ) {
272 return null;
273 } else {
274 return (array)$val;
275 }
276 }
277
278 /**
279 * Fetch an array of integers, or return $default if it's not set.
280 * If source was scalar, will return an array with a single element.
281 * If no source and no default, returns NULL.
282 * If an array is returned, contents are guaranteed to be integers.
283 *
284 * @param $name string
285 * @param $default array: option default (or NULL)
286 * @return array of ints
287 */
288 function getIntArray( $name, $default = NULL ) {
289 $val = $this->getArray( $name, $default );
290 if( is_array( $val ) ) {
291 $val = array_map( 'intval', $val );
292 }
293 return $val;
294 }
295
296 /**
297 * Fetch an integer value from the input or return $default if not set.
298 * Guaranteed to return an integer; non-numeric input will typically
299 * return 0.
300 * @param $name string
301 * @param $default int
302 * @return int
303 */
304 function getInt( $name, $default = 0 ) {
305 return intval( $this->getVal( $name, $default ) );
306 }
307
308 /**
309 * Fetch an integer value from the input or return null if empty.
310 * Guaranteed to return an integer or null; non-numeric input will
311 * typically return null.
312 * @param $name string
313 * @return int
314 */
315 function getIntOrNull( $name ) {
316 $val = $this->getVal( $name );
317 return is_numeric( $val )
318 ? intval( $val )
319 : null;
320 }
321
322 /**
323 * Fetch a boolean value from the input or return $default if not set.
324 * Guaranteed to return true or false, with normal PHP semantics for
325 * boolean interpretation of strings.
326 * @param $name string
327 * @param $default bool
328 * @return bool
329 */
330 function getBool( $name, $default = false ) {
331 return $this->getVal( $name, $default ) ? true : false;
332 }
333
334 /**
335 * Return true if the named value is set in the input, whatever that
336 * value is (even "0"). Return false if the named value is not set.
337 * Example use is checking for the presence of check boxes in forms.
338 * @param $name string
339 * @return bool
340 */
341 function getCheck( $name ) {
342 # Checkboxes and buttons are only present when clicked
343 # Presence connotes truth, abscense false
344 $val = $this->getVal( $name, NULL );
345 return isset( $val );
346 }
347
348 /**
349 * Fetch a text string from the given array or return $default if it's not
350 * set. \r is stripped from the text, and with some language modules there
351 * is an input transliteration applied. This should generally be used for
352 * form <textarea> and <input> fields. Used for user-supplied freeform text
353 * input (for which input transformations may be required - e.g. Esperanto
354 * x-coding).
355 *
356 * @param $name string
357 * @param $default string: optional
358 * @return string
359 */
360 function getText( $name, $default = '' ) {
361 global $wgContLang;
362 $val = $this->getVal( $name, $default );
363 return str_replace( "\r\n", "\n",
364 $wgContLang->recodeInput( $val ) );
365 }
366
367 /**
368 * Extracts the given named values into an array.
369 * If no arguments are given, returns all input values.
370 * No transformation is performed on the values.
371 */
372 function getValues() {
373 $names = func_get_args();
374 if ( count( $names ) == 0 ) {
375 $names = array_keys( $this->data );
376 }
377
378 $retVal = array();
379 foreach ( $names as $name ) {
380 $value = $this->getVal( $name );
381 if ( !is_null( $value ) ) {
382 $retVal[$name] = $value;
383 }
384 }
385 return $retVal;
386 }
387
388 /**
389 * Returns true if the present request was reached by a POST operation,
390 * false otherwise (GET, HEAD, or command-line).
391 *
392 * Note that values retrieved by the object may come from the
393 * GET URL etc even on a POST request.
394 *
395 * @return bool
396 */
397 function wasPosted() {
398 return $_SERVER['REQUEST_METHOD'] == 'POST';
399 }
400
401 /**
402 * Returns true if there is a session cookie set.
403 * This does not necessarily mean that the user is logged in!
404 *
405 * If you want to check for an open session, use session_id()
406 * instead; that will also tell you if the session was opened
407 * during the current request (in which case the cookie will
408 * be sent back to the client at the end of the script run).
409 *
410 * @return bool
411 */
412 function checkSessionCookie() {
413 return isset( $_COOKIE[session_name()] );
414 }
415
416 /**
417 * Return the path portion of the request URI.
418 * @return string
419 */
420 function getRequestURL() {
421 if( isset( $_SERVER['REQUEST_URI'] ) ) {
422 $base = $_SERVER['REQUEST_URI'];
423 } elseif( isset( $_SERVER['SCRIPT_NAME'] ) ) {
424 // Probably IIS; doesn't set REQUEST_URI
425 $base = $_SERVER['SCRIPT_NAME'];
426 if( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
427 $base .= '?' . $_SERVER['QUERY_STRING'];
428 }
429 } else {
430 // This shouldn't happen!
431 throw new MWException( "Web server doesn't provide either " .
432 "REQUEST_URI or SCRIPT_NAME. Report details of your " .
433 "web server configuration to http://bugzilla.wikimedia.org/" );
434 }
435 // User-agents should not send a fragment with the URI, but
436 // if they do, and the web server passes it on to us, we
437 // need to strip it or we get false-positive redirect loops
438 // or weird output URLs
439 $hash = strpos( $base, '#' );
440 if( $hash !== false ) {
441 $base = substr( $base, 0, $hash );
442 }
443 if( $base{0} == '/' ) {
444 return $base;
445 } else {
446 // We may get paths with a host prepended; strip it.
447 return preg_replace( '!^[^:]+://[^/]+/!', '/', $base );
448 }
449 }
450
451 /**
452 * Return the request URI with the canonical service and hostname.
453 * @return string
454 */
455 function getFullRequestURL() {
456 global $wgServer;
457 return $wgServer . $this->getRequestURL();
458 }
459
460 /**
461 * Take an arbitrary query and rewrite the present URL to include it
462 * @param $query String: query string fragment; do not include initial '?'
463 * @return string
464 */
465 function appendQuery( $query ) {
466 global $wgTitle;
467 $basequery = '';
468 foreach( $_GET as $var => $val ) {
469 if ( $var == 'title' )
470 continue;
471 if ( is_array( $val ) )
472 /* This will happen given a request like
473 * http://en.wikipedia.org/w/index.php?title[]=Special:Userlogin&returnto[]=Main_Page
474 */
475 continue;
476 $basequery .= '&' . urlencode( $var ) . '=' . urlencode( $val );
477 }
478 $basequery .= '&' . $query;
479
480 # Trim the extra &
481 $basequery = substr( $basequery, 1 );
482 return $wgTitle->getLocalURL( $basequery );
483 }
484
485 /**
486 * HTML-safe version of appendQuery().
487 * @param $query String: query string fragment; do not include initial '?'
488 * @return string
489 */
490 function escapeAppendQuery( $query ) {
491 return htmlspecialchars( $this->appendQuery( $query ) );
492 }
493
494 function appendQueryValue( $key, $value, $onlyquery = false ) {
495 return $this->appendQueryArray( array( $key => $value ), $onlyquery );
496 }
497
498 /**
499 * Appends or replaces value of query variables.
500 * @param $array Array of values to replace/add to query
501 * @param $onlyquery Bool: whether to only return the query string and not
502 * the complete URL
503 * @return string
504 */
505 function appendQueryArray( $array, $onlyquery = false ) {
506 global $wgTitle;
507 $newquery = $_GET;
508 unset( $newquery['title'] );
509 $newquery = array_merge( $newquery, $array );
510 $query = wfArrayToCGI( $newquery );
511 return $onlyquery ? $query : $wgTitle->getLocalURL( $query );
512 }
513
514 /**
515 * Check for limit and offset parameters on the input, and return sensible
516 * defaults if not given. The limit must be positive and is capped at 5000.
517 * Offset must be positive but is not capped.
518 *
519 * @param $deflimit Integer: limit to use if no input and the user hasn't set the option.
520 * @param $optionname String: to specify an option other than rclimit to pull from.
521 * @return array first element is limit, second is offset
522 */
523 function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
524 global $wgUser;
525
526 $limit = $this->getInt( 'limit', 0 );
527 if( $limit < 0 ) $limit = 0;
528 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
529 $limit = (int)$wgUser->getOption( $optionname );
530 }
531 if( $limit <= 0 ) $limit = $deflimit;
532 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
533
534 $offset = $this->getInt( 'offset', 0 );
535 if( $offset < 0 ) $offset = 0;
536
537 return array( $limit, $offset );
538 }
539
540 /**
541 * Return the path to the temporary file where PHP has stored the upload.
542 * @param $key String:
543 * @return string or NULL if no such file.
544 */
545 function getFileTempname( $key ) {
546 if( !isset( $_FILES[$key] ) ) {
547 return NULL;
548 }
549 return $_FILES[$key]['tmp_name'];
550 }
551
552 /**
553 * Return the size of the upload, or 0.
554 * @param $key String:
555 * @return integer
556 */
557 function getFileSize( $key ) {
558 if( !isset( $_FILES[$key] ) ) {
559 return 0;
560 }
561 return $_FILES[$key]['size'];
562 }
563
564 /**
565 * Return the upload error or 0
566 * @param $key String:
567 * @return integer
568 */
569 function getUploadError( $key ) {
570 if( !isset( $_FILES[$key] ) || !isset( $_FILES[$key]['error'] ) ) {
571 return 0/*UPLOAD_ERR_OK*/;
572 }
573 return $_FILES[$key]['error'];
574 }
575
576 /**
577 * Return the original filename of the uploaded file, as reported by
578 * the submitting user agent. HTML-style character entities are
579 * interpreted and normalized to Unicode normalization form C, in part
580 * to deal with weird input from Safari with non-ASCII filenames.
581 *
582 * Other than this the name is not verified for being a safe filename.
583 *
584 * @param $key String:
585 * @return string or NULL if no such file.
586 */
587 function getFileName( $key ) {
588 if( !isset( $_FILES[$key] ) ) {
589 return NULL;
590 }
591 $name = $_FILES[$key]['name'];
592
593 # Safari sends filenames in HTML-encoded Unicode form D...
594 # Horrid and evil! Let's try to make some kind of sense of it.
595 $name = Sanitizer::decodeCharReferences( $name );
596 $name = UtfNormal::cleanUp( $name );
597 wfDebug( "WebRequest::getFileName() '" . $_FILES[$key]['name'] . "' normalized to '$name'\n" );
598 return $name;
599 }
600
601 /**
602 * Return a handle to WebResponse style object, for setting cookies,
603 * headers and other stuff, for Request being worked on.
604 */
605 function response() {
606 /* Lazy initialization of response object for this request */
607 if (!is_object($this->_response)) {
608 $this->_response = new WebResponse;
609 }
610 return $this->_response;
611 }
612
613 /**
614 * Get a request header, or false if it isn't set
615 * @param $name String: case-insensitive header name
616 */
617 function getHeader( $name ) {
618 $name = strtoupper( $name );
619 if ( function_exists( 'apache_request_headers' ) ) {
620 if ( !isset( $this->headers ) ) {
621 $this->headers = array();
622 foreach ( apache_request_headers() as $tempName => $tempValue ) {
623 $this->headers[ strtoupper( $tempName ) ] = $tempValue;
624 }
625 }
626 if ( isset( $this->headers[$name] ) ) {
627 return $this->headers[$name];
628 } else {
629 return false;
630 }
631 } else {
632 $name = 'HTTP_' . str_replace( '-', '_', $name );
633 if ( isset( $_SERVER[$name] ) ) {
634 return $_SERVER[$name];
635 } else {
636 return false;
637 }
638 }
639 }
640
641 /*
642 * Get data from $_SESSION
643 */
644 function getSessionData( $key ) {
645 if( !isset( $_SESSION[$key] ) )
646 return null;
647 return $_SESSION[$key];
648 }
649 function setSessionData( $key, $data ) {
650 $_SESSION[$key] = $data;
651 }
652 }
653
654 /**
655 * WebRequest clone which takes values from a provided array.
656 *
657 * @ingroup HTTP
658 */
659 class FauxRequest extends WebRequest {
660 var $wasPosted = false;
661
662 /**
663 * @param $data Array of *non*-urlencoded key => value pairs, the
664 * fake GET/POST values
665 * @param $wasPosted Bool: whether to treat the data as POST
666 */
667 function FauxRequest( $data, $wasPosted = false, $session = null ) {
668 if( is_array( $data ) ) {
669 $this->data = $data;
670 } else {
671 throw new MWException( "FauxRequest() got bogus data" );
672 }
673 $this->wasPosted = $wasPosted;
674 $this->headers = array();
675 $this->session = $session ? $session : array();
676 }
677
678 function notImplemented( $method ) {
679 throw new MWException( "{$method}() not implemented" );
680 }
681
682 function getText( $name, $default = '' ) {
683 # Override; don't recode since we're using internal data
684 return (string)$this->getVal( $name, $default );
685 }
686
687 function getValues() {
688 return $this->data;
689 }
690
691 function wasPosted() {
692 return $this->wasPosted;
693 }
694
695 function checkSessionCookie() {
696 return false;
697 }
698
699 function getRequestURL() {
700 $this->notImplemented( __METHOD__ );
701 }
702
703 function appendQuery( $query ) {
704 $this->notImplemented( __METHOD__ );
705 }
706
707 function getHeader( $name ) {
708 return isset( $this->headers[$name] ) ? $this->headers[$name] : false;
709 }
710
711 function getSessionData( $key ) {
712 if( !isset( $this->session[$key] ) )
713 return null;
714 return $this->session[$key];
715 }
716 function setSessionData( $key, $data ) {
717 $this->notImplemented( __METHOD__ );
718 }
719
720 }