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