Moved wfGetIP() to WebRequest::getIP():
[lhc/web/wiklou.git] / includes / WebRequest.php
1 <?php
2 /**
3 * Deal with importing all those nasssty globals and things
4 *
5 * Copyright © 2003 Brion Vibber <brion@pobox.com>
6 * http://www.mediawiki.org/
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
22 *
23 * @file
24 */
25
26 /**
27 * The WebRequest class encapsulates getting at data passed in the
28 * URL or via a POSTed form, handling remove of "magic quotes" slashes,
29 * stripping illegal input characters and normalizing Unicode sequences.
30 *
31 * Usually this is used via a global singleton, $wgRequest. You should
32 * not create a second WebRequest object; make a FauxRequest object if
33 * you want to pass arbitrary data to some function in place of the web
34 * input.
35 *
36 * @ingroup HTTP
37 */
38 class WebRequest {
39 protected $data, $headers = array();
40
41 /**
42 * Lazy-init response object
43 * @var WebResponse
44 */
45 private $response;
46
47 /**
48 * Cached client IP address
49 * @var String
50 */
51 private $ip;
52
53 public function __construct() {
54 /// @todo FIXME: This preemptive de-quoting can interfere with other web libraries
55 /// and increases our memory footprint. It would be cleaner to do on
56 /// demand; but currently we have no wrapper for $_SERVER etc.
57 $this->checkMagicQuotes();
58
59 // POST overrides GET data
60 // We don't use $_REQUEST here to avoid interference from cookies...
61 $this->data = $_POST + $_GET;
62 }
63
64 /**
65 * Extract the PATH_INFO variable even when it isn't a reasonable
66 * value. On some large webhosts, PATH_INFO includes the script
67 * path as well as everything after it.
68 *
69 * @param $want string: If this is not 'all', then the function
70 * will return an empty array if it determines that the URL is
71 * inside a rewrite path.
72 *
73 * @return Array: 'title' key is the title of the article.
74 */
75 static public function getPathInfo( $want = 'all' ) {
76 // PATH_INFO is mangled due to http://bugs.php.net/bug.php?id=31892
77 // And also by Apache 2.x, double slashes are converted to single slashes.
78 // So we will use REQUEST_URI if possible.
79 $matches = array();
80 if ( !empty( $_SERVER['REQUEST_URI'] ) ) {
81 // Slurp out the path portion to examine...
82 $url = $_SERVER['REQUEST_URI'];
83 if ( !preg_match( '!^https?://!', $url ) ) {
84 $url = 'http://unused' . $url;
85 }
86 $a = parse_url( $url );
87 if( $a ) {
88 $path = isset( $a['path'] ) ? $a['path'] : '';
89
90 global $wgScript;
91 if( $path == $wgScript && $want !== 'all' ) {
92 // Script inside a rewrite path?
93 // Abort to keep from breaking...
94 return $matches;
95 }
96 // Raw PATH_INFO style
97 $matches = self::extractTitle( $path, "$wgScript/$1" );
98
99 global $wgArticlePath;
100 if( !$matches && $wgArticlePath ) {
101 $matches = self::extractTitle( $path, $wgArticlePath );
102 }
103
104 global $wgActionPaths;
105 if( !$matches && $wgActionPaths ) {
106 $matches = self::extractTitle( $path, $wgActionPaths, 'action' );
107 }
108
109 global $wgVariantArticlePath, $wgContLang;
110 if( !$matches && $wgVariantArticlePath ) {
111 $variantPaths = array();
112 foreach( $wgContLang->getVariants() as $variant ) {
113 $variantPaths[$variant] =
114 str_replace( '$2', $variant, $wgVariantArticlePath );
115 }
116 $matches = self::extractTitle( $path, $variantPaths, 'variant' );
117 }
118
119 wfRunHooks( 'WebRequestGetPathInfoRequestURI', array( $path, &$matches ) );
120 }
121 } elseif ( isset( $_SERVER['ORIG_PATH_INFO'] ) && $_SERVER['ORIG_PATH_INFO'] != '' ) {
122 // Mangled PATH_INFO
123 // http://bugs.php.net/bug.php?id=31892
124 // Also reported when ini_get('cgi.fix_pathinfo')==false
125 $matches['title'] = substr( $_SERVER['ORIG_PATH_INFO'], 1 );
126
127 } elseif ( isset( $_SERVER['PATH_INFO'] ) && ($_SERVER['PATH_INFO'] != '') ) {
128 // Regular old PATH_INFO yay
129 $matches['title'] = substr( $_SERVER['PATH_INFO'], 1 );
130 }
131
132 return $matches;
133 }
134
135 /**
136 * Work out an appropriate URL prefix containing scheme and host, based on
137 * information detected from $_SERVER
138 *
139 * @return string
140 */
141 public static function detectServer() {
142 list( $proto, $stdPort ) = self::detectProtocolAndStdPort();
143
144 $varNames = array( 'HTTP_HOST', 'SERVER_NAME', 'HOSTNAME', 'SERVER_ADDR' );
145 $host = 'localhost';
146 $port = $stdPort;
147 foreach ( $varNames as $varName ) {
148 if ( !isset( $_SERVER[$varName] ) ) {
149 continue;
150 }
151 $parts = IP::splitHostAndPort( $_SERVER[$varName] );
152 if ( !$parts ) {
153 // Invalid, do not use
154 continue;
155 }
156 $host = $parts[0];
157 if ( $parts[1] === false ) {
158 if ( isset( $_SERVER['SERVER_PORT'] ) ) {
159 $port = $_SERVER['SERVER_PORT'];
160 } // else leave it as $stdPort
161 } else {
162 $port = $parts[1];
163 }
164 break;
165 }
166
167 return $proto . '://' . IP::combineHostAndPort( $host, $port, $stdPort );
168 }
169
170 public static function detectProtocolAndStdPort() {
171 return ( isset( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] == 'on' ) ? array( 'https', 443 ) : array( 'http', 80 );
172 }
173
174 public static function detectProtocol() {
175 list( $proto, $stdPort ) = self::detectProtocolAndStdPort();
176 return $proto;
177 }
178
179 /**
180 * Check for title, action, and/or variant data in the URL
181 * and interpolate it into the GET variables.
182 * This should only be run after $wgContLang is available,
183 * as we may need the list of language variants to determine
184 * available variant URLs.
185 */
186 public function interpolateTitle() {
187 global $wgUsePathInfo;
188
189 // bug 16019: title interpolation on API queries is useless and sometimes harmful
190 if ( defined( 'MW_API' ) ) {
191 return;
192 }
193
194 if ( $wgUsePathInfo ) {
195 $matches = self::getPathInfo( 'title' );
196 foreach( $matches as $key => $val) {
197 $this->data[$key] = $_GET[$key] = $_REQUEST[$key] = $val;
198 }
199 }
200 }
201
202 /**
203 * URL rewriting function; tries to extract page title and,
204 * optionally, one other fixed parameter value from a URL path.
205 *
206 * @param $path string: the URL path given from the client
207 * @param $bases array: one or more URLs, optionally with $1 at the end
208 * @param $key string: if provided, the matching key in $bases will be
209 * passed on as the value of this URL parameter
210 * @return array of URL variables to interpolate; empty if no match
211 */
212 static function extractTitle( $path, $bases, $key = false ) {
213 foreach( (array)$bases as $keyValue => $base ) {
214 // Find the part after $wgArticlePath
215 $base = str_replace( '$1', '', $base );
216 $baseLen = strlen( $base );
217 if( substr( $path, 0, $baseLen ) == $base ) {
218 $raw = substr( $path, $baseLen );
219 if( $raw !== '' ) {
220 $matches = array( 'title' => rawurldecode( $raw ) );
221 if( $key ) {
222 $matches[$key] = $keyValue;
223 }
224 return $matches;
225 }
226 }
227 }
228 return array();
229 }
230
231 /**
232 * Recursively strips slashes from the given array;
233 * used for undoing the evil that is magic_quotes_gpc.
234 *
235 * @param $arr array: will be modified
236 * @return array the original array
237 */
238 private function &fix_magic_quotes( &$arr ) {
239 foreach( $arr as $key => $val ) {
240 if( is_array( $val ) ) {
241 $this->fix_magic_quotes( $arr[$key] );
242 } else {
243 $arr[$key] = stripslashes( $val );
244 }
245 }
246 return $arr;
247 }
248
249 /**
250 * If magic_quotes_gpc option is on, run the global arrays
251 * through fix_magic_quotes to strip out the stupid slashes.
252 * WARNING: This should only be done once! Running a second
253 * time could damage the values.
254 */
255 private function checkMagicQuotes() {
256 $mustFixQuotes = function_exists( 'get_magic_quotes_gpc' )
257 && get_magic_quotes_gpc();
258 if( $mustFixQuotes ) {
259 $this->fix_magic_quotes( $_COOKIE );
260 $this->fix_magic_quotes( $_ENV );
261 $this->fix_magic_quotes( $_GET );
262 $this->fix_magic_quotes( $_POST );
263 $this->fix_magic_quotes( $_REQUEST );
264 $this->fix_magic_quotes( $_SERVER );
265 }
266 }
267
268 /**
269 * Recursively normalizes UTF-8 strings in the given array.
270 *
271 * @param $data string or array
272 * @return cleaned-up version of the given
273 * @private
274 */
275 function normalizeUnicode( $data ) {
276 if( is_array( $data ) ) {
277 foreach( $data as $key => $val ) {
278 $data[$key] = $this->normalizeUnicode( $val );
279 }
280 } else {
281 global $wgContLang;
282 $data = isset( $wgContLang ) ? $wgContLang->normalize( $data ) : UtfNormal::cleanUp( $data );
283 }
284 return $data;
285 }
286
287 /**
288 * Fetch a value from the given array or return $default if it's not set.
289 *
290 * @param $arr Array
291 * @param $name String
292 * @param $default Mixed
293 * @return mixed
294 */
295 private function getGPCVal( $arr, $name, $default ) {
296 # PHP is so nice to not touch input data, except sometimes:
297 # http://us2.php.net/variables.external#language.variables.external.dot-in-names
298 # Work around PHP *feature* to avoid *bugs* elsewhere.
299 $name = strtr( $name, '.', '_' );
300 if( isset( $arr[$name] ) ) {
301 global $wgContLang;
302 $data = $arr[$name];
303 if( isset( $_GET[$name] ) && !is_array( $data ) ) {
304 # Check for alternate/legacy character encoding.
305 if( isset( $wgContLang ) ) {
306 $data = $wgContLang->checkTitleEncoding( $data );
307 }
308 }
309 $data = $this->normalizeUnicode( $data );
310 return $data;
311 } else {
312 taint( $default );
313 return $default;
314 }
315 }
316
317 /**
318 * Fetch a scalar from the input or return $default if it's not set.
319 * Returns a string. Arrays are discarded. Useful for
320 * non-freeform text inputs (e.g. predefined internal text keys
321 * selected by a drop-down menu). For freeform input, see getText().
322 *
323 * @param $name String
324 * @param $default String: optional default (or NULL)
325 * @return String
326 */
327 public function getVal( $name, $default = null ) {
328 $val = $this->getGPCVal( $this->data, $name, $default );
329 if( is_array( $val ) ) {
330 $val = $default;
331 }
332 if( is_null( $val ) ) {
333 return $val;
334 } else {
335 return (string)$val;
336 }
337 }
338
339 /**
340 * Set an arbitrary value into our get/post data.
341 *
342 * @param $key String: key name to use
343 * @param $value Mixed: value to set
344 * @return Mixed: old value if one was present, null otherwise
345 */
346 public function setVal( $key, $value ) {
347 $ret = isset( $this->data[$key] ) ? $this->data[$key] : null;
348 $this->data[$key] = $value;
349 return $ret;
350 }
351
352 /**
353 * Fetch an array from the input or return $default if it's not set.
354 * If source was scalar, will return an array with a single element.
355 * If no source and no default, returns NULL.
356 *
357 * @param $name String
358 * @param $default Array: optional default (or NULL)
359 * @return Array
360 */
361 public function getArray( $name, $default = null ) {
362 $val = $this->getGPCVal( $this->data, $name, $default );
363 if( is_null( $val ) ) {
364 return null;
365 } else {
366 return (array)$val;
367 }
368 }
369
370 /**
371 * Fetch an array of integers, or return $default if it's not set.
372 * If source was scalar, will return an array with a single element.
373 * If no source and no default, returns NULL.
374 * If an array is returned, contents are guaranteed to be integers.
375 *
376 * @param $name String
377 * @param $default Array: option default (or NULL)
378 * @return Array of ints
379 */
380 public function getIntArray( $name, $default = null ) {
381 $val = $this->getArray( $name, $default );
382 if( is_array( $val ) ) {
383 $val = array_map( 'intval', $val );
384 }
385 return $val;
386 }
387
388 /**
389 * Fetch an integer value from the input or return $default if not set.
390 * Guaranteed to return an integer; non-numeric input will typically
391 * return 0.
392 *
393 * @param $name String
394 * @param $default Integer
395 * @return Integer
396 */
397 public function getInt( $name, $default = 0 ) {
398 return intval( $this->getVal( $name, $default ) );
399 }
400
401 /**
402 * Fetch an integer value from the input or return null if empty.
403 * Guaranteed to return an integer or null; non-numeric input will
404 * typically return null.
405 *
406 * @param $name String
407 * @return Integer
408 */
409 public function getIntOrNull( $name ) {
410 $val = $this->getVal( $name );
411 return is_numeric( $val )
412 ? intval( $val )
413 : null;
414 }
415
416 /**
417 * Fetch a boolean value from the input or return $default if not set.
418 * Guaranteed to return true or false, with normal PHP semantics for
419 * boolean interpretation of strings.
420 *
421 * @param $name String
422 * @param $default Boolean
423 * @return Boolean
424 */
425 public function getBool( $name, $default = false ) {
426 return (bool)$this->getVal( $name, $default );
427 }
428
429 /**
430 * Fetch a boolean value from the input or return $default if not set.
431 * Unlike getBool, the string "false" will result in boolean false, which is
432 * useful when interpreting information sent from JavaScript.
433 *
434 * @param $name String
435 * @param $default Boolean
436 * @return Boolean
437 */
438 public function getFuzzyBool( $name, $default = false ) {
439 return $this->getBool( $name, $default ) && strcasecmp( $this->getVal( $name ), 'false' ) !== 0;
440 }
441
442 /**
443 * Return true if the named value is set in the input, whatever that
444 * value is (even "0"). Return false if the named value is not set.
445 * Example use is checking for the presence of check boxes in forms.
446 *
447 * @param $name String
448 * @return Boolean
449 */
450 public function getCheck( $name ) {
451 # Checkboxes and buttons are only present when clicked
452 # Presence connotes truth, abscense false
453 $val = $this->getVal( $name, null );
454 return isset( $val );
455 }
456
457 /**
458 * Fetch a text string from the given array or return $default if it's not
459 * set. Carriage returns are stripped from the text, and with some language
460 * modules there is an input transliteration applied. This should generally
461 * be used for form <textarea> and <input> fields. Used for user-supplied
462 * freeform text input (for which input transformations may be required - e.g.
463 * Esperanto x-coding).
464 *
465 * @param $name String
466 * @param $default String: optional
467 * @return String
468 */
469 public function getText( $name, $default = '' ) {
470 global $wgContLang;
471 $val = $this->getVal( $name, $default );
472 return str_replace( "\r\n", "\n",
473 $wgContLang->recodeInput( $val ) );
474 }
475
476 /**
477 * Extracts the given named values into an array.
478 * If no arguments are given, returns all input values.
479 * No transformation is performed on the values.
480 *
481 * @return array
482 */
483 public function getValues() {
484 $names = func_get_args();
485 if ( count( $names ) == 0 ) {
486 $names = array_keys( $this->data );
487 }
488
489 $retVal = array();
490 foreach ( $names as $name ) {
491 $value = $this->getVal( $name );
492 if ( !is_null( $value ) ) {
493 $retVal[$name] = $value;
494 }
495 }
496 return $retVal;
497 }
498
499 /**
500 * Returns the names of all input values excluding those in $exclude.
501 *
502 * @param $exclude Array
503 * @return array
504 */
505 public function getValueNames( $exclude = array() ) {
506 return array_diff( array_keys( $this->getValues() ), $exclude );
507 }
508
509 /**
510 * Get the values passed in the query string.
511 * No transformation is performed on the values.
512 *
513 * @return Array
514 */
515 public function getQueryValues() {
516 return $_GET;
517 }
518
519 /**
520 * Returns true if the present request was reached by a POST operation,
521 * false otherwise (GET, HEAD, or command-line).
522 *
523 * Note that values retrieved by the object may come from the
524 * GET URL etc even on a POST request.
525 *
526 * @return Boolean
527 */
528 public function wasPosted() {
529 return isset( $_SERVER['REQUEST_METHOD'] ) && $_SERVER['REQUEST_METHOD'] == 'POST';
530 }
531
532 /**
533 * Returns true if there is a session cookie set.
534 * This does not necessarily mean that the user is logged in!
535 *
536 * If you want to check for an open session, use session_id()
537 * instead; that will also tell you if the session was opened
538 * during the current request (in which case the cookie will
539 * be sent back to the client at the end of the script run).
540 *
541 * @return Boolean
542 */
543 public function checkSessionCookie() {
544 return isset( $_COOKIE[ session_name() ] );
545 }
546
547 /**
548 * Get a cookie from the $_COOKIE jar
549 *
550 * @param $key String: the name of the cookie
551 * @param $prefix String: a prefix to use for the cookie name, if not $wgCookiePrefix
552 * @param $default Mixed: what to return if the value isn't found
553 * @return Mixed: cookie value or $default if the cookie not set
554 */
555 public function getCookie( $key, $prefix = null, $default = null ) {
556 if( $prefix === null ) {
557 global $wgCookiePrefix;
558 $prefix = $wgCookiePrefix;
559 }
560 return $this->getGPCVal( $_COOKIE, $prefix . $key , $default );
561 }
562
563 /**
564 * Return the path and query string portion of the request URI.
565 * This will be suitable for use as a relative link in HTML output.
566 *
567 * @return String
568 */
569 public function getRequestURL() {
570 if( isset( $_SERVER['REQUEST_URI'] ) && strlen( $_SERVER['REQUEST_URI'] ) ) {
571 $base = $_SERVER['REQUEST_URI'];
572 } elseif ( isset( $_SERVER['HTTP_X_ORIGINAL_URL'] ) && strlen( $_SERVER['HTTP_X_ORIGINAL_URL'] ) ) {
573 // Probably IIS; doesn't set REQUEST_URI
574 $base = $_SERVER['HTTP_X_ORIGINAL_URL'];
575 } elseif( isset( $_SERVER['SCRIPT_NAME'] ) ) {
576 $base = $_SERVER['SCRIPT_NAME'];
577 if( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
578 $base .= '?' . $_SERVER['QUERY_STRING'];
579 }
580 } else {
581 // This shouldn't happen!
582 throw new MWException( "Web server doesn't provide either " .
583 "REQUEST_URI, HTTP_X_ORIGINAL_URL or SCRIPT_NAME. Report details " .
584 "of your web server configuration to http://bugzilla.wikimedia.org/" );
585 }
586 // User-agents should not send a fragment with the URI, but
587 // if they do, and the web server passes it on to us, we
588 // need to strip it or we get false-positive redirect loops
589 // or weird output URLs
590 $hash = strpos( $base, '#' );
591 if( $hash !== false ) {
592 $base = substr( $base, 0, $hash );
593 }
594 if( $base[0] == '/' ) {
595 return $base;
596 } else {
597 // We may get paths with a host prepended; strip it.
598 return preg_replace( '!^[^:]+://[^/]+/!', '/', $base );
599 }
600 }
601
602 /**
603 * Return the request URI with the canonical service and hostname, path,
604 * and query string. This will be suitable for use as an absolute link
605 * in HTML or other output.
606 *
607 * NOTE: This will output a protocol-relative URL if $wgServer is protocol-relative
608 *
609 * @return String
610 */
611 public function getFullRequestURL() {
612 global $wgServer;
613 return $wgServer . $this->getRequestURL();
614 }
615
616 /**
617 * Take an arbitrary query and rewrite the present URL to include it
618 * @param $query String: query string fragment; do not include initial '?'
619 *
620 * @return String
621 */
622 public function appendQuery( $query ) {
623 return $this->appendQueryArray( wfCgiToArray( $query ) );
624 }
625
626 /**
627 * HTML-safe version of appendQuery().
628 *
629 * @param $query String: query string fragment; do not include initial '?'
630 * @return String
631 */
632 public function escapeAppendQuery( $query ) {
633 return htmlspecialchars( $this->appendQuery( $query ) );
634 }
635
636 /**
637 * @param $key
638 * @param $value
639 * @param $onlyquery bool
640 * @return String
641 */
642 public function appendQueryValue( $key, $value, $onlyquery = false ) {
643 return $this->appendQueryArray( array( $key => $value ), $onlyquery );
644 }
645
646 /**
647 * Appends or replaces value of query variables.
648 *
649 * @param $array Array of values to replace/add to query
650 * @param $onlyquery Bool: whether to only return the query string and not
651 * the complete URL
652 * @return String
653 */
654 public function appendQueryArray( $array, $onlyquery = false ) {
655 global $wgTitle;
656 $newquery = $this->getQueryValues();
657 unset( $newquery['title'] );
658 $newquery = array_merge( $newquery, $array );
659 $query = wfArrayToCGI( $newquery );
660 return $onlyquery ? $query : $wgTitle->getLocalURL( $query );
661 }
662
663 /**
664 * Check for limit and offset parameters on the input, and return sensible
665 * defaults if not given. The limit must be positive and is capped at 5000.
666 * Offset must be positive but is not capped.
667 *
668 * @param $deflimit Integer: limit to use if no input and the user hasn't set the option.
669 * @param $optionname String: to specify an option other than rclimit to pull from.
670 * @return array first element is limit, second is offset
671 */
672 public function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
673 global $wgUser;
674
675 $limit = $this->getInt( 'limit', 0 );
676 if( $limit < 0 ) {
677 $limit = 0;
678 }
679 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
680 $limit = (int)$wgUser->getOption( $optionname );
681 }
682 if( $limit <= 0 ) {
683 $limit = $deflimit;
684 }
685 if( $limit > 5000 ) {
686 $limit = 5000; # We have *some* limits...
687 }
688
689 $offset = $this->getInt( 'offset', 0 );
690 if( $offset < 0 ) {
691 $offset = 0;
692 }
693
694 return array( $limit, $offset );
695 }
696
697 /**
698 * Return the path to the temporary file where PHP has stored the upload.
699 *
700 * @param $key String:
701 * @return string or NULL if no such file.
702 */
703 public function getFileTempname( $key ) {
704 $file = new WebRequestUpload( $this, $key );
705 return $file->getTempName();
706 }
707
708 /**
709 * Return the size of the upload, or 0.
710 *
711 * @deprecated since 1.17
712 * @param $key String:
713 * @return integer
714 */
715 public function getFileSize( $key ) {
716 $file = new WebRequestUpload( $this, $key );
717 return $file->getSize();
718 }
719
720 /**
721 * Return the upload error or 0
722 *
723 * @param $key String:
724 * @return integer
725 */
726 public function getUploadError( $key ) {
727 $file = new WebRequestUpload( $this, $key );
728 return $file->getError();
729 }
730
731 /**
732 * Return the original filename of the uploaded file, as reported by
733 * the submitting user agent. HTML-style character entities are
734 * interpreted and normalized to Unicode normalization form C, in part
735 * to deal with weird input from Safari with non-ASCII filenames.
736 *
737 * Other than this the name is not verified for being a safe filename.
738 *
739 * @param $key String:
740 * @return string or NULL if no such file.
741 */
742 public function getFileName( $key ) {
743 $file = new WebRequestUpload( $this, $key );
744 return $file->getName();
745 }
746
747 /**
748 * Return a WebRequestUpload object corresponding to the key
749 *
750 * @param $key string
751 * @return WebRequestUpload
752 */
753 public function getUpload( $key ) {
754 return new WebRequestUpload( $this, $key );
755 }
756
757 /**
758 * Return a handle to WebResponse style object, for setting cookies,
759 * headers and other stuff, for Request being worked on.
760 *
761 * @return WebResponse
762 */
763 public function response() {
764 /* Lazy initialization of response object for this request */
765 if ( !is_object( $this->response ) ) {
766 $class = ( $this instanceof FauxRequest ) ? 'FauxResponse' : 'WebResponse';
767 $this->response = new $class();
768 }
769 return $this->response;
770 }
771
772 /**
773 * Initialise the header list
774 */
775 private function initHeaders() {
776 if ( count( $this->headers ) ) {
777 return;
778 }
779
780 if ( function_exists( 'apache_request_headers' ) ) {
781 foreach ( apache_request_headers() as $tempName => $tempValue ) {
782 $this->headers[ strtoupper( $tempName ) ] = $tempValue;
783 }
784 } else {
785 foreach ( $_SERVER as $name => $value ) {
786 if ( substr( $name, 0, 5 ) === 'HTTP_' ) {
787 $name = str_replace( '_', '-', substr( $name, 5 ) );
788 $this->headers[$name] = $value;
789 } elseif ( $name === 'CONTENT_LENGTH' ) {
790 $this->headers['CONTENT-LENGTH'] = $value;
791 }
792 }
793 }
794 }
795
796 /**
797 * Get an array containing all request headers
798 *
799 * @return Array mapping header name to its value
800 */
801 public function getAllHeaders() {
802 $this->initHeaders();
803 return $this->headers;
804 }
805
806 /**
807 * Get a request header, or false if it isn't set
808 * @param $name String: case-insensitive header name
809 *
810 * @return string|false
811 */
812 public function getHeader( $name ) {
813 $this->initHeaders();
814 $name = strtoupper( $name );
815 if ( isset( $this->headers[$name] ) ) {
816 return $this->headers[$name];
817 } else {
818 return false;
819 }
820 }
821
822 /**
823 * Get data from $_SESSION
824 *
825 * @param $key String: name of key in $_SESSION
826 * @return Mixed
827 */
828 public function getSessionData( $key ) {
829 if( !isset( $_SESSION[$key] ) ) {
830 return null;
831 }
832 return $_SESSION[$key];
833 }
834
835 /**
836 * Set session data
837 *
838 * @param $key String: name of key in $_SESSION
839 * @param $data Mixed
840 */
841 public function setSessionData( $key, $data ) {
842 $_SESSION[$key] = $data;
843 }
844
845 /**
846 * Check if Internet Explorer will detect an incorrect cache extension in
847 * PATH_INFO or QUERY_STRING. If the request can't be allowed, show an error
848 * message or redirect to a safer URL. Returns true if the URL is OK, and
849 * false if an error message has been shown and the request should be aborted.
850 *
851 * @param $extWhitelist array
852 * @return bool
853 */
854 public function checkUrlExtension( $extWhitelist = array() ) {
855 global $wgScriptExtension;
856 $extWhitelist[] = ltrim( $wgScriptExtension, '.' );
857 if ( IEUrlExtension::areServerVarsBad( $_SERVER, $extWhitelist ) ) {
858 if ( !$this->wasPosted() ) {
859 $newUrl = IEUrlExtension::fixUrlForIE6(
860 $this->getFullRequestURL(), $extWhitelist );
861 if ( $newUrl !== false ) {
862 $this->doSecurityRedirect( $newUrl );
863 return false;
864 }
865 }
866 wfHttpError( 403, 'Forbidden',
867 'Invalid file extension found in the path info or query string.' );
868
869 return false;
870 }
871 return true;
872 }
873
874 /**
875 * Attempt to redirect to a URL with a QUERY_STRING that's not dangerous in
876 * IE 6. Returns true if it was successful, false otherwise.
877 *
878 * @param $url string
879 * @return bool
880 */
881 protected function doSecurityRedirect( $url ) {
882 header( 'Location: ' . $url );
883 header( 'Content-Type: text/html' );
884 $encUrl = htmlspecialchars( $url );
885 echo <<<HTML
886 <html>
887 <head>
888 <title>Security redirect</title>
889 </head>
890 <body>
891 <h1>Security redirect</h1>
892 <p>
893 We can't serve non-HTML content from the URL you have requested, because
894 Internet Explorer would interpret it as an incorrect and potentially dangerous
895 content type.</p>
896 <p>Instead, please use <a href="$encUrl">this URL</a>, which is the same as the URL you have requested, except that
897 "&amp;*" is appended. This prevents Internet Explorer from seeing a bogus file
898 extension.
899 </p>
900 </body>
901 </html>
902 HTML;
903 echo "\n";
904 return true;
905 }
906
907 /**
908 * Returns true if the PATH_INFO ends with an extension other than a script
909 * extension. This could confuse IE for scripts that send arbitrary data which
910 * is not HTML but may be detected as such.
911 *
912 * Various past attempts to use the URL to make this check have generally
913 * run up against the fact that CGI does not provide a standard method to
914 * determine the URL. PATH_INFO may be mangled (e.g. if cgi.fix_pathinfo=0),
915 * but only by prefixing it with the script name and maybe some other stuff,
916 * the extension is not mangled. So this should be a reasonably portable
917 * way to perform this security check.
918 *
919 * Also checks for anything that looks like a file extension at the end of
920 * QUERY_STRING, since IE 6 and earlier will use this to get the file type
921 * if there was no dot before the question mark (bug 28235).
922 *
923 * @deprecated Use checkUrlExtension().
924 */
925 public function isPathInfoBad( $extWhitelist = array() ) {
926 global $wgScriptExtension;
927 $extWhitelist[] = ltrim( $wgScriptExtension, '.' );
928 return IEUrlExtension::areServerVarsBad( $_SERVER, $extWhitelist );
929 }
930
931 /**
932 * Parse the Accept-Language header sent by the client into an array
933 * @return array( languageCode => q-value ) sorted by q-value in descending order
934 * May contain the "language" '*', which applies to languages other than those explicitly listed.
935 * This is aligned with rfc2616 section 14.4
936 */
937 public function getAcceptLang() {
938 // Modified version of code found at http://www.thefutureoftheweb.com/blog/use-accept-language-header
939 $acceptLang = $this->getHeader( 'Accept-Language' );
940 if ( !$acceptLang ) {
941 return array();
942 }
943
944 // Return the language codes in lower case
945 $acceptLang = strtolower( $acceptLang );
946
947 // Break up string into pieces (languages and q factors)
948 $lang_parse = null;
949 preg_match_all( '/([a-z]{1,8}(-[a-z]{1,8})?|\*)\s*(;\s*q\s*=\s*(1|0(\.[0-9]+)?)?)?/',
950 $acceptLang, $lang_parse );
951
952 if ( !count( $lang_parse[1] ) ) {
953 return array();
954 }
955
956 // Create a list like "en" => 0.8
957 $langs = array_combine( $lang_parse[1], $lang_parse[4] );
958 // Set default q factor to 1
959 foreach ( $langs as $lang => $val ) {
960 if ( $val === '' ) {
961 $langs[$lang] = 1;
962 } elseif ( $val == 0 ) {
963 unset($langs[$lang]);
964 }
965 }
966
967 // Sort list
968 arsort( $langs, SORT_NUMERIC );
969 return $langs;
970 }
971
972 /**
973 * Fetch the raw IP from the request
974 *
975 * @return String
976 */
977 protected function getRawIP() {
978 if ( isset( $_SERVER['REMOTE_ADDR'] ) ) {
979 return IP::canonicalize( $_SERVER['REMOTE_ADDR'] );
980 } else {
981 return null;
982 }
983 }
984
985 /**
986 * Work out the IP address based on various globals
987 * For trusted proxies, use the XFF client IP (first of the chain)
988 * @return string
989 */
990 public function getIP() {
991 global $wgUsePrivateIPs;
992
993 # Return cached result
994 if ( $this->ip !== null ) {
995 return $this->ip;
996 }
997
998 # collect the originating ips
999 $ip = $this->getRawIP();
1000
1001 # Append XFF
1002 $forwardedFor = $this->getHeader( 'X-Forwarded-For' );
1003 if ( $forwardedFor !== false ) {
1004 $ipchain = array_map( 'trim', explode( ',', $forwardedFor ) );
1005 $ipchain = array_reverse( $ipchain );
1006 if ( $ip ) {
1007 array_unshift( $ipchain, $ip );
1008 }
1009
1010 # Step through XFF list and find the last address in the list which is a trusted server
1011 # Set $ip to the IP address given by that trusted server, unless the address is not sensible (e.g. private)
1012 foreach ( $ipchain as $i => $curIP ) {
1013 $curIP = IP::canonicalize( $curIP );
1014 if ( wfIsTrustedProxy( $curIP ) ) {
1015 if ( isset( $ipchain[$i + 1] ) ) {
1016 if ( $wgUsePrivateIPs || IP::isPublic( $ipchain[$i + 1 ] ) ) {
1017 $ip = $ipchain[$i + 1];
1018 }
1019 }
1020 } else {
1021 break;
1022 }
1023 }
1024 }
1025
1026 # Allow extensions to improve our guess
1027 wfRunHooks( 'GetIP', array( &$ip ) );
1028
1029 if ( !$ip ) {
1030 throw new MWException( "Unable to determine IP" );
1031 }
1032
1033 wfDebug( "IP: $ip\n" );
1034 $this->ip = $ip;
1035 return $ip;
1036 }
1037 }
1038
1039 /**
1040 * Object to access the $_FILES array
1041 */
1042 class WebRequestUpload {
1043 protected $request;
1044 protected $doesExist;
1045 protected $fileInfo;
1046
1047 /**
1048 * Constructor. Should only be called by WebRequest
1049 *
1050 * @param $request WebRequest The associated request
1051 * @param $key string Key in $_FILES array (name of form field)
1052 */
1053 public function __construct( $request, $key ) {
1054 $this->request = $request;
1055 $this->doesExist = isset( $_FILES[$key] );
1056 if ( $this->doesExist ) {
1057 $this->fileInfo = $_FILES[$key];
1058 }
1059 }
1060
1061 /**
1062 * Return whether a file with this name was uploaded.
1063 *
1064 * @return bool
1065 */
1066 public function exists() {
1067 return $this->doesExist;
1068 }
1069
1070 /**
1071 * Return the original filename of the uploaded file
1072 *
1073 * @return mixed Filename or null if non-existent
1074 */
1075 public function getName() {
1076 if ( !$this->exists() ) {
1077 return null;
1078 }
1079
1080 global $wgContLang;
1081 $name = $this->fileInfo['name'];
1082
1083 # Safari sends filenames in HTML-encoded Unicode form D...
1084 # Horrid and evil! Let's try to make some kind of sense of it.
1085 $name = Sanitizer::decodeCharReferences( $name );
1086 $name = $wgContLang->normalize( $name );
1087 wfDebug( __METHOD__ . ": {$this->fileInfo['name']} normalized to '$name'\n" );
1088 return $name;
1089 }
1090
1091 /**
1092 * Return the file size of the uploaded file
1093 *
1094 * @return int File size or zero if non-existent
1095 */
1096 public function getSize() {
1097 if ( !$this->exists() ) {
1098 return 0;
1099 }
1100
1101 return $this->fileInfo['size'];
1102 }
1103
1104 /**
1105 * Return the path to the temporary file
1106 *
1107 * @return mixed Path or null if non-existent
1108 */
1109 public function getTempName() {
1110 if ( !$this->exists() ) {
1111 return null;
1112 }
1113
1114 return $this->fileInfo['tmp_name'];
1115 }
1116
1117 /**
1118 * Return the upload error. See link for explanation
1119 * http://www.php.net/manual/en/features.file-upload.errors.php
1120 *
1121 * @return int One of the UPLOAD_ constants, 0 if non-existent
1122 */
1123 public function getError() {
1124 if ( !$this->exists() ) {
1125 return 0; # UPLOAD_ERR_OK
1126 }
1127
1128 return $this->fileInfo['error'];
1129 }
1130
1131 /**
1132 * Returns whether this upload failed because of overflow of a maximum set
1133 * in php.ini
1134 *
1135 * @return bool
1136 */
1137 public function isIniSizeOverflow() {
1138 if ( $this->getError() == UPLOAD_ERR_INI_SIZE ) {
1139 # PHP indicated that upload_max_filesize is exceeded
1140 return true;
1141 }
1142
1143 $contentLength = $this->request->getHeader( 'CONTENT_LENGTH' );
1144 if ( $contentLength > wfShorthandToInteger( ini_get( 'post_max_size' ) ) ) {
1145 # post_max_size is exceeded
1146 return true;
1147 }
1148
1149 return false;
1150 }
1151 }
1152
1153 /**
1154 * WebRequest clone which takes values from a provided array.
1155 *
1156 * @ingroup HTTP
1157 */
1158 class FauxRequest extends WebRequest {
1159 private $wasPosted = false;
1160 private $session = array();
1161
1162 /**
1163 * @param $data Array of *non*-urlencoded key => value pairs, the
1164 * fake GET/POST values
1165 * @param $wasPosted Bool: whether to treat the data as POST
1166 * @param $session Mixed: session array or null
1167 */
1168 public function __construct( $data, $wasPosted = false, $session = null ) {
1169 if( is_array( $data ) ) {
1170 $this->data = $data;
1171 } else {
1172 throw new MWException( "FauxRequest() got bogus data" );
1173 }
1174 $this->wasPosted = $wasPosted;
1175 if( $session )
1176 $this->session = $session;
1177 }
1178
1179 private function notImplemented( $method ) {
1180 throw new MWException( "{$method}() not implemented" );
1181 }
1182
1183 public function getText( $name, $default = '' ) {
1184 # Override; don't recode since we're using internal data
1185 return (string)$this->getVal( $name, $default );
1186 }
1187
1188 public function getValues() {
1189 return $this->data;
1190 }
1191
1192 public function getQueryValues() {
1193 if ( $this->wasPosted ) {
1194 return array();
1195 } else {
1196 return $this->data;
1197 }
1198 }
1199
1200 public function wasPosted() {
1201 return $this->wasPosted;
1202 }
1203
1204 public function checkSessionCookie() {
1205 return false;
1206 }
1207
1208 public function getRequestURL() {
1209 $this->notImplemented( __METHOD__ );
1210 }
1211
1212 public function getHeader( $name ) {
1213 return isset( $this->headers[$name] ) ? $this->headers[$name] : false;
1214 }
1215
1216 public function setHeader( $name, $val ) {
1217 $this->headers[$name] = $val;
1218 }
1219
1220 public function getSessionData( $key ) {
1221 if( isset( $this->session[$key] ) )
1222 return $this->session[$key];
1223 }
1224
1225 public function setSessionData( $key, $data ) {
1226 $this->session[$key] = $data;
1227 }
1228
1229 public function getSessionArray() {
1230 return $this->session;
1231 }
1232
1233 public function isPathInfoBad( $extWhitelist = array() ) {
1234 return false;
1235 }
1236
1237 public function checkUrlExtension( $extWhitelist = array() ) {
1238 return true;
1239 }
1240
1241 protected function getRawIP() {
1242 return '127.0.0.1';
1243 }
1244 }