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