PHP is so nice to not touch our input data ever (magic_quotes anyone?), except someti...
[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 = $_POST + $_GET;
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 # PHP is so nice to not touch input data, except sometimes:
223 # http://us2.php.net/variables.external#language.variables.external.dot-in-names
224 # Work around PHP *feature* to avoid *bugs* elsewhere.
225 $name = strtr( $name, '.', '_' );
226 if( isset( $arr[$name] ) ) {
227 global $wgContLang;
228 $data = $arr[$name];
229 if( isset( $_GET[$name] ) && !is_array( $data ) ) {
230 # Check for alternate/legacy character encoding.
231 if( isset( $wgContLang ) ) {
232 $data = $wgContLang->checkTitleEncoding( $data );
233 }
234 }
235 $data = $this->normalizeUnicode( $data );
236 return $data;
237 } else {
238 taint( $default );
239 return $default;
240 }
241 }
242
243 /**
244 * Fetch a scalar from the input or return $default if it's not set.
245 * Returns a string. Arrays are discarded. Useful for
246 * non-freeform text inputs (e.g. predefined internal text keys
247 * selected by a drop-down menu). For freeform input, see getText().
248 *
249 * @param $name string
250 * @param $default string: optional default (or NULL)
251 * @return string
252 */
253 function getVal( $name, $default = NULL ) {
254 $val = $this->getGPCVal( $this->data, $name, $default );
255 if( is_array( $val ) ) {
256 $val = $default;
257 }
258 if( is_null( $val ) ) {
259 return $val;
260 } else {
261 return (string)$val;
262 }
263 }
264
265 /**
266 * Set an aribtrary value into our get/post data.
267 * @param $key string Key name to use
268 * @param $value mixed Value to set
269 * @return mixed old value if one was present, null otherwise
270 */
271 function setVal( $key, $value ) {
272 $ret = isset( $this->data[$key] ) ? $this->data[$key] : null;
273 $this->data[$key] = $value;
274 return $ret;
275 }
276
277 /**
278 * Fetch an array from the input or return $default if it's not set.
279 * If source was scalar, will return an array with a single element.
280 * If no source and no default, returns NULL.
281 *
282 * @param $name string
283 * @param $default array: optional default (or NULL)
284 * @return array
285 */
286 function getArray( $name, $default = NULL ) {
287 $val = $this->getGPCVal( $this->data, $name, $default );
288 if( is_null( $val ) ) {
289 return null;
290 } else {
291 return (array)$val;
292 }
293 }
294
295 /**
296 * Fetch an array of integers, or return $default if it's not set.
297 * If source was scalar, will return an array with a single element.
298 * If no source and no default, returns NULL.
299 * If an array is returned, contents are guaranteed to be integers.
300 *
301 * @param $name string
302 * @param $default array: option default (or NULL)
303 * @return array of ints
304 */
305 function getIntArray( $name, $default = NULL ) {
306 $val = $this->getArray( $name, $default );
307 if( is_array( $val ) ) {
308 $val = array_map( 'intval', $val );
309 }
310 return $val;
311 }
312
313 /**
314 * Fetch an integer value from the input or return $default if not set.
315 * Guaranteed to return an integer; non-numeric input will typically
316 * return 0.
317 * @param $name string
318 * @param $default int
319 * @return int
320 */
321 function getInt( $name, $default = 0 ) {
322 return intval( $this->getVal( $name, $default ) );
323 }
324
325 /**
326 * Fetch an integer value from the input or return null if empty.
327 * Guaranteed to return an integer or null; non-numeric input will
328 * typically return null.
329 * @param $name string
330 * @return int
331 */
332 function getIntOrNull( $name ) {
333 $val = $this->getVal( $name );
334 return is_numeric( $val )
335 ? intval( $val )
336 : null;
337 }
338
339 /**
340 * Fetch a boolean value from the input or return $default if not set.
341 * Guaranteed to return true or false, with normal PHP semantics for
342 * boolean interpretation of strings.
343 * @param $name string
344 * @param $default bool
345 * @return bool
346 */
347 function getBool( $name, $default = false ) {
348 return $this->getVal( $name, $default ) ? true : false;
349 }
350
351 /**
352 * Return true if the named value is set in the input, whatever that
353 * value is (even "0"). Return false if the named value is not set.
354 * Example use is checking for the presence of check boxes in forms.
355 * @param $name string
356 * @return bool
357 */
358 function getCheck( $name ) {
359 # Checkboxes and buttons are only present when clicked
360 # Presence connotes truth, abscense false
361 $val = $this->getVal( $name, NULL );
362 return isset( $val );
363 }
364
365 /**
366 * Fetch a text string from the given array or return $default if it's not
367 * set. \r is stripped from the text, and with some language modules there
368 * is an input transliteration applied. This should generally be used for
369 * form <textarea> and <input> fields. Used for user-supplied freeform text
370 * input (for which input transformations may be required - e.g. Esperanto
371 * x-coding).
372 *
373 * @param $name string
374 * @param $default string: optional
375 * @return string
376 */
377 function getText( $name, $default = '' ) {
378 global $wgContLang;
379 $val = $this->getVal( $name, $default );
380 return str_replace( "\r\n", "\n",
381 $wgContLang->recodeInput( $val ) );
382 }
383
384 /**
385 * Extracts the given named values into an array.
386 * If no arguments are given, returns all input values.
387 * No transformation is performed on the values.
388 */
389 function getValues() {
390 $names = func_get_args();
391 if ( count( $names ) == 0 ) {
392 $names = array_keys( $this->data );
393 }
394
395 $retVal = array();
396 foreach ( $names as $name ) {
397 $value = $this->getVal( $name );
398 if ( !is_null( $value ) ) {
399 $retVal[$name] = $value;
400 }
401 }
402 return $retVal;
403 }
404
405 /**
406 * Returns true if the present request was reached by a POST operation,
407 * false otherwise (GET, HEAD, or command-line).
408 *
409 * Note that values retrieved by the object may come from the
410 * GET URL etc even on a POST request.
411 *
412 * @return bool
413 */
414 function wasPosted() {
415 return $_SERVER['REQUEST_METHOD'] == 'POST';
416 }
417
418 /**
419 * Returns true if there is a session cookie set.
420 * This does not necessarily mean that the user is logged in!
421 *
422 * If you want to check for an open session, use session_id()
423 * instead; that will also tell you if the session was opened
424 * during the current request (in which case the cookie will
425 * be sent back to the client at the end of the script run).
426 *
427 * @return bool
428 */
429 function checkSessionCookie() {
430 return isset( $_COOKIE[session_name()] );
431 }
432
433 /**
434 * Return the path portion of the request URI.
435 * @return string
436 */
437 function getRequestURL() {
438 if( isset( $_SERVER['REQUEST_URI'] ) ) {
439 $base = $_SERVER['REQUEST_URI'];
440 } elseif( isset( $_SERVER['SCRIPT_NAME'] ) ) {
441 // Probably IIS; doesn't set REQUEST_URI
442 $base = $_SERVER['SCRIPT_NAME'];
443 if( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
444 $base .= '?' . $_SERVER['QUERY_STRING'];
445 }
446 } else {
447 // This shouldn't happen!
448 throw new MWException( "Web server doesn't provide either " .
449 "REQUEST_URI or SCRIPT_NAME. Report details of your " .
450 "web server configuration to http://bugzilla.wikimedia.org/" );
451 }
452 // User-agents should not send a fragment with the URI, but
453 // if they do, and the web server passes it on to us, we
454 // need to strip it or we get false-positive redirect loops
455 // or weird output URLs
456 $hash = strpos( $base, '#' );
457 if( $hash !== false ) {
458 $base = substr( $base, 0, $hash );
459 }
460 if( $base{0} == '/' ) {
461 return $base;
462 } else {
463 // We may get paths with a host prepended; strip it.
464 return preg_replace( '!^[^:]+://[^/]+/!', '/', $base );
465 }
466 }
467
468 /**
469 * Return the request URI with the canonical service and hostname.
470 * @return string
471 */
472 function getFullRequestURL() {
473 global $wgServer;
474 return $wgServer . $this->getRequestURL();
475 }
476
477 /**
478 * Take an arbitrary query and rewrite the present URL to include it
479 * @param $query String: query string fragment; do not include initial '?'
480 * @return string
481 */
482 function appendQuery( $query ) {
483 global $wgTitle;
484 $basequery = '';
485 foreach( $_GET as $var => $val ) {
486 if ( $var == 'title' )
487 continue;
488 if ( is_array( $val ) )
489 /* This will happen given a request like
490 * http://en.wikipedia.org/w/index.php?title[]=Special:Userlogin&returnto[]=Main_Page
491 */
492 continue;
493 $basequery .= '&' . urlencode( $var ) . '=' . urlencode( $val );
494 }
495 $basequery .= '&' . $query;
496
497 # Trim the extra &
498 $basequery = substr( $basequery, 1 );
499 return $wgTitle->getLocalURL( $basequery );
500 }
501
502 /**
503 * HTML-safe version of appendQuery().
504 * @param $query String: query string fragment; do not include initial '?'
505 * @return string
506 */
507 function escapeAppendQuery( $query ) {
508 return htmlspecialchars( $this->appendQuery( $query ) );
509 }
510
511 function appendQueryValue( $key, $value, $onlyquery = false ) {
512 return $this->appendQueryArray( array( $key => $value ), $onlyquery );
513 }
514
515 /**
516 * Appends or replaces value of query variables.
517 * @param $array Array of values to replace/add to query
518 * @param $onlyquery Bool: whether to only return the query string and not
519 * the complete URL
520 * @return string
521 */
522 function appendQueryArray( $array, $onlyquery = false ) {
523 global $wgTitle;
524 $newquery = $_GET;
525 unset( $newquery['title'] );
526 $newquery = array_merge( $newquery, $array );
527 $query = wfArrayToCGI( $newquery );
528 return $onlyquery ? $query : $wgTitle->getLocalURL( $query );
529 }
530
531 /**
532 * Check for limit and offset parameters on the input, and return sensible
533 * defaults if not given. The limit must be positive and is capped at 5000.
534 * Offset must be positive but is not capped.
535 *
536 * @param $deflimit Integer: limit to use if no input and the user hasn't set the option.
537 * @param $optionname String: to specify an option other than rclimit to pull from.
538 * @return array first element is limit, second is offset
539 */
540 function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
541 global $wgUser;
542
543 $limit = $this->getInt( 'limit', 0 );
544 if( $limit < 0 ) $limit = 0;
545 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
546 $limit = (int)$wgUser->getOption( $optionname );
547 }
548 if( $limit <= 0 ) $limit = $deflimit;
549 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
550
551 $offset = $this->getInt( 'offset', 0 );
552 if( $offset < 0 ) $offset = 0;
553
554 return array( $limit, $offset );
555 }
556
557 /**
558 * Return the path to the temporary file where PHP has stored the upload.
559 * @param $key String:
560 * @return string or NULL if no such file.
561 */
562 function getFileTempname( $key ) {
563 if( !isset( $_FILES[$key] ) ) {
564 return NULL;
565 }
566 return $_FILES[$key]['tmp_name'];
567 }
568
569 /**
570 * Return the size of the upload, or 0.
571 * @param $key String:
572 * @return integer
573 */
574 function getFileSize( $key ) {
575 if( !isset( $_FILES[$key] ) ) {
576 return 0;
577 }
578 return $_FILES[$key]['size'];
579 }
580
581 /**
582 * Return the upload error or 0
583 * @param $key String:
584 * @return integer
585 */
586 function getUploadError( $key ) {
587 if( !isset( $_FILES[$key] ) || !isset( $_FILES[$key]['error'] ) ) {
588 return 0/*UPLOAD_ERR_OK*/;
589 }
590 return $_FILES[$key]['error'];
591 }
592
593 /**
594 * Return the original filename of the uploaded file, as reported by
595 * the submitting user agent. HTML-style character entities are
596 * interpreted and normalized to Unicode normalization form C, in part
597 * to deal with weird input from Safari with non-ASCII filenames.
598 *
599 * Other than this the name is not verified for being a safe filename.
600 *
601 * @param $key String:
602 * @return string or NULL if no such file.
603 */
604 function getFileName( $key ) {
605 if( !isset( $_FILES[$key] ) ) {
606 return NULL;
607 }
608 $name = $_FILES[$key]['name'];
609
610 # Safari sends filenames in HTML-encoded Unicode form D...
611 # Horrid and evil! Let's try to make some kind of sense of it.
612 $name = Sanitizer::decodeCharReferences( $name );
613 $name = UtfNormal::cleanUp( $name );
614 wfDebug( "WebRequest::getFileName() '" . $_FILES[$key]['name'] . "' normalized to '$name'\n" );
615 return $name;
616 }
617
618 /**
619 * Return a handle to WebResponse style object, for setting cookies,
620 * headers and other stuff, for Request being worked on.
621 */
622 function response() {
623 /* Lazy initialization of response object for this request */
624 if (!is_object($this->_response)) {
625 $this->_response = new WebResponse;
626 }
627 return $this->_response;
628 }
629
630 /**
631 * Get a request header, or false if it isn't set
632 * @param $name String: case-insensitive header name
633 */
634 function getHeader( $name ) {
635 $name = strtoupper( $name );
636 if ( function_exists( 'apache_request_headers' ) ) {
637 if ( !isset( $this->headers ) ) {
638 $this->headers = array();
639 foreach ( apache_request_headers() as $tempName => $tempValue ) {
640 $this->headers[ strtoupper( $tempName ) ] = $tempValue;
641 }
642 }
643 if ( isset( $this->headers[$name] ) ) {
644 return $this->headers[$name];
645 } else {
646 return false;
647 }
648 } else {
649 $name = 'HTTP_' . str_replace( '-', '_', $name );
650 if ( isset( $_SERVER[$name] ) ) {
651 return $_SERVER[$name];
652 } else {
653 return false;
654 }
655 }
656 }
657
658 /*
659 * Get data from $_SESSION
660 */
661 function getSessionData( $key ) {
662 if( !isset( $_SESSION[$key] ) )
663 return null;
664 return $_SESSION[$key];
665 }
666 function setSessionData( $key, $data ) {
667 $_SESSION[$key] = $data;
668 }
669 }
670
671 /**
672 * WebRequest clone which takes values from a provided array.
673 *
674 * @ingroup HTTP
675 */
676 class FauxRequest extends WebRequest {
677 var $wasPosted = false;
678
679 /**
680 * @param $data Array of *non*-urlencoded key => value pairs, the
681 * fake GET/POST values
682 * @param $wasPosted Bool: whether to treat the data as POST
683 */
684 function FauxRequest( $data, $wasPosted = false, $session = null ) {
685 if( is_array( $data ) ) {
686 $this->data = $data;
687 } else {
688 throw new MWException( "FauxRequest() got bogus data" );
689 }
690 $this->wasPosted = $wasPosted;
691 $this->headers = array();
692 $this->session = $session ? $session : array();
693 }
694
695 function notImplemented( $method ) {
696 throw new MWException( "{$method}() not implemented" );
697 }
698
699 function getText( $name, $default = '' ) {
700 # Override; don't recode since we're using internal data
701 return (string)$this->getVal( $name, $default );
702 }
703
704 function getValues() {
705 return $this->data;
706 }
707
708 function wasPosted() {
709 return $this->wasPosted;
710 }
711
712 function checkSessionCookie() {
713 return false;
714 }
715
716 function getRequestURL() {
717 $this->notImplemented( __METHOD__ );
718 }
719
720 function appendQuery( $query ) {
721 $this->notImplemented( __METHOD__ );
722 }
723
724 function getHeader( $name ) {
725 return isset( $this->headers[$name] ) ? $this->headers[$name] : false;
726 }
727
728 function getSessionData( $key ) {
729 if( !isset( $this->session[$key] ) )
730 return null;
731 return $this->session[$key];
732 }
733 function setSessionData( $key, $data ) {
734 $this->notImplemented( __METHOD__ );
735 }
736
737 }