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