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