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