* Fixes for r91123:
[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 * Get the values passed in the query string.
490 * No transformation is performed on the values.
491 *
492 * @return Array
493 */
494 public function getQueryValues() {
495 return $_GET;
496 }
497
498 /**
499 * Returns true if the present request was reached by a POST operation,
500 * false otherwise (GET, HEAD, or command-line).
501 *
502 * Note that values retrieved by the object may come from the
503 * GET URL etc even on a POST request.
504 *
505 * @return Boolean
506 */
507 public function wasPosted() {
508 return $_SERVER['REQUEST_METHOD'] == 'POST';
509 }
510
511 /**
512 * Returns true if there is a session cookie set.
513 * This does not necessarily mean that the user is logged in!
514 *
515 * If you want to check for an open session, use session_id()
516 * instead; that will also tell you if the session was opened
517 * during the current request (in which case the cookie will
518 * be sent back to the client at the end of the script run).
519 *
520 * @return Boolean
521 */
522 public function checkSessionCookie() {
523 return isset( $_COOKIE[ session_name() ] );
524 }
525
526 /**
527 * Get a cookie from the $_COOKIE jar
528 *
529 * @param $key String: the name of the cookie
530 * @param $prefix String: a prefix to use for the cookie name, if not $wgCookiePrefix
531 * @param $default Mixed: what to return if the value isn't found
532 * @return Mixed: cookie value or $default if the cookie not set
533 */
534 public function getCookie( $key, $prefix = null, $default = null ) {
535 if( $prefix === null ) {
536 global $wgCookiePrefix;
537 $prefix = $wgCookiePrefix;
538 }
539 return $this->getGPCVal( $_COOKIE, $prefix . $key , $default );
540 }
541
542 /**
543 * Return the path and query string portion of the request URI.
544 * This will be suitable for use as a relative link in HTML output.
545 *
546 * @return String
547 */
548 public function getRequestURL() {
549 if( isset( $_SERVER['REQUEST_URI'] ) && strlen( $_SERVER['REQUEST_URI'] ) ) {
550 $base = $_SERVER['REQUEST_URI'];
551 } elseif ( isset( $_SERVER['HTTP_X_ORIGINAL_URL'] ) && strlen( $_SERVER['HTTP_X_ORIGINAL_URL'] ) ) {
552 // Probably IIS; doesn't set REQUEST_URI
553 $base = $_SERVER['HTTP_X_ORIGINAL_URL'];
554 } elseif( isset( $_SERVER['SCRIPT_NAME'] ) ) {
555 $base = $_SERVER['SCRIPT_NAME'];
556 if( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
557 $base .= '?' . $_SERVER['QUERY_STRING'];
558 }
559 } else {
560 // This shouldn't happen!
561 throw new MWException( "Web server doesn't provide either " .
562 "REQUEST_URI, HTTP_X_ORIGINAL_URL or SCRIPT_NAME. Report details " .
563 "of your web server configuration to http://bugzilla.wikimedia.org/" );
564 }
565 // User-agents should not send a fragment with the URI, but
566 // if they do, and the web server passes it on to us, we
567 // need to strip it or we get false-positive redirect loops
568 // or weird output URLs
569 $hash = strpos( $base, '#' );
570 if( $hash !== false ) {
571 $base = substr( $base, 0, $hash );
572 }
573 if( $base[0] == '/' ) {
574 return $base;
575 } else {
576 // We may get paths with a host prepended; strip it.
577 return preg_replace( '!^[^:]+://[^/]+/!', '/', $base );
578 }
579 }
580
581 /**
582 * Return the request URI with the canonical service and hostname, path,
583 * and query string. This will be suitable for use as an absolute link
584 * in HTML or other output.
585 *
586 * @return String
587 */
588 public function getFullRequestURL() {
589 global $wgServer;
590 return $wgServer . $this->getRequestURL();
591 }
592
593 /**
594 * Take an arbitrary query and rewrite the present URL to include it
595 * @param $query String: query string fragment; do not include initial '?'
596 *
597 * @return String
598 */
599 public function appendQuery( $query ) {
600 return $this->appendQueryArray( wfCgiToArray( $query ) );
601 }
602
603 /**
604 * HTML-safe version of appendQuery().
605 *
606 * @param $query String: query string fragment; do not include initial '?'
607 * @return String
608 */
609 public function escapeAppendQuery( $query ) {
610 return htmlspecialchars( $this->appendQuery( $query ) );
611 }
612
613 /**
614 * @param $key
615 * @param $value
616 * @param $onlyquery bool
617 * @return String
618 */
619 public function appendQueryValue( $key, $value, $onlyquery = false ) {
620 return $this->appendQueryArray( array( $key => $value ), $onlyquery );
621 }
622
623 /**
624 * Appends or replaces value of query variables.
625 *
626 * @param $array Array of values to replace/add to query
627 * @param $onlyquery Bool: whether to only return the query string and not
628 * the complete URL
629 * @return String
630 */
631 public function appendQueryArray( $array, $onlyquery = false ) {
632 global $wgTitle;
633 $newquery = $this->getQueryValues();
634 unset( $newquery['title'] );
635 $newquery = array_merge( $newquery, $array );
636 $query = wfArrayToCGI( $newquery );
637 return $onlyquery ? $query : $wgTitle->getLocalURL( $query );
638 }
639
640 /**
641 * Check for limit and offset parameters on the input, and return sensible
642 * defaults if not given. The limit must be positive and is capped at 5000.
643 * Offset must be positive but is not capped.
644 *
645 * @param $deflimit Integer: limit to use if no input and the user hasn't set the option.
646 * @param $optionname String: to specify an option other than rclimit to pull from.
647 * @return array first element is limit, second is offset
648 */
649 public function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
650 global $wgUser;
651
652 $limit = $this->getInt( 'limit', 0 );
653 if( $limit < 0 ) {
654 $limit = 0;
655 }
656 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
657 $limit = (int)$wgUser->getOption( $optionname );
658 }
659 if( $limit <= 0 ) {
660 $limit = $deflimit;
661 }
662 if( $limit > 5000 ) {
663 $limit = 5000; # We have *some* limits...
664 }
665
666 $offset = $this->getInt( 'offset', 0 );
667 if( $offset < 0 ) {
668 $offset = 0;
669 }
670
671 return array( $limit, $offset );
672 }
673
674 /**
675 * Return the path to the temporary file where PHP has stored the upload.
676 *
677 * @param $key String:
678 * @return string or NULL if no such file.
679 */
680 public function getFileTempname( $key ) {
681 $file = new WebRequestUpload( $this, $key );
682 return $file->getTempName();
683 }
684
685 /**
686 * Return the size of the upload, or 0.
687 *
688 * @deprecated since 1.17
689 * @param $key String:
690 * @return integer
691 */
692 public function getFileSize( $key ) {
693 $file = new WebRequestUpload( $this, $key );
694 return $file->getSize();
695 }
696
697 /**
698 * Return the upload error or 0
699 *
700 * @param $key String:
701 * @return integer
702 */
703 public function getUploadError( $key ) {
704 $file = new WebRequestUpload( $this, $key );
705 return $file->getError();
706 }
707
708 /**
709 * Return the original filename of the uploaded file, as reported by
710 * the submitting user agent. HTML-style character entities are
711 * interpreted and normalized to Unicode normalization form C, in part
712 * to deal with weird input from Safari with non-ASCII filenames.
713 *
714 * Other than this the name is not verified for being a safe filename.
715 *
716 * @param $key String:
717 * @return string or NULL if no such file.
718 */
719 public function getFileName( $key ) {
720 $file = new WebRequestUpload( $this, $key );
721 return $file->getName();
722 }
723
724 /**
725 * Return a WebRequestUpload object corresponding to the key
726 *
727 * @param $key string
728 * @return WebRequestUpload
729 */
730 public function getUpload( $key ) {
731 return new WebRequestUpload( $this, $key );
732 }
733
734 /**
735 * Return a handle to WebResponse style object, for setting cookies,
736 * headers and other stuff, for Request being worked on.
737 *
738 * @return WebResponse
739 */
740 public function response() {
741 /* Lazy initialization of response object for this request */
742 if ( !is_object( $this->response ) ) {
743 $class = ( $this instanceof FauxRequest ) ? 'FauxResponse' : 'WebResponse';
744 $this->response = new $class();
745 }
746 return $this->response;
747 }
748
749 /**
750 * Initialise the header list
751 */
752 private function initHeaders() {
753 if ( count( $this->headers ) ) {
754 return;
755 }
756
757 if ( function_exists( 'apache_request_headers' ) ) {
758 foreach ( apache_request_headers() as $tempName => $tempValue ) {
759 $this->headers[ strtoupper( $tempName ) ] = $tempValue;
760 }
761 } else {
762 foreach ( $_SERVER as $name => $value ) {
763 if ( substr( $name, 0, 5 ) === 'HTTP_' ) {
764 $name = str_replace( '_', '-', substr( $name, 5 ) );
765 $this->headers[$name] = $value;
766 } elseif ( $name === 'CONTENT_LENGTH' ) {
767 $this->headers['CONTENT-LENGTH'] = $value;
768 }
769 }
770 }
771 }
772
773 /**
774 * Get an array containing all request headers
775 *
776 * @return Array mapping header name to its value
777 */
778 public function getAllHeaders() {
779 $this->initHeaders();
780 return $this->headers;
781 }
782
783 /**
784 * Get a request header, or false if it isn't set
785 * @param $name String: case-insensitive header name
786 *
787 * @return string|false
788 */
789 public function getHeader( $name ) {
790 $this->initHeaders();
791 $name = strtoupper( $name );
792 if ( isset( $this->headers[$name] ) ) {
793 return $this->headers[$name];
794 } else {
795 return false;
796 }
797 }
798
799 /**
800 * Get data from $_SESSION
801 *
802 * @param $key String: name of key in $_SESSION
803 * @return Mixed
804 */
805 public function getSessionData( $key ) {
806 if( !isset( $_SESSION[$key] ) ) {
807 return null;
808 }
809 return $_SESSION[$key];
810 }
811
812 /**
813 * Set session data
814 *
815 * @param $key String: name of key in $_SESSION
816 * @param $data Mixed
817 */
818 public function setSessionData( $key, $data ) {
819 $_SESSION[$key] = $data;
820 }
821
822 /**
823 * Check if Internet Explorer will detect an incorrect cache extension in
824 * PATH_INFO or QUERY_STRING. If the request can't be allowed, show an error
825 * message or redirect to a safer URL. Returns true if the URL is OK, and
826 * false if an error message has been shown and the request should be aborted.
827 *
828 * @param $extWhitelist array
829 * @return bool
830 */
831 public function checkUrlExtension( $extWhitelist = array() ) {
832 global $wgScriptExtension;
833 $extWhitelist[] = ltrim( $wgScriptExtension, '.' );
834 if ( IEUrlExtension::areServerVarsBad( $_SERVER, $extWhitelist ) ) {
835 if ( !$this->wasPosted() ) {
836 $newUrl = IEUrlExtension::fixUrlForIE6(
837 $this->getFullRequestURL(), $extWhitelist );
838 if ( $newUrl !== false ) {
839 $this->doSecurityRedirect( $newUrl );
840 return false;
841 }
842 }
843 wfHttpError( 403, 'Forbidden',
844 'Invalid file extension found in the path info or query string.' );
845
846 return false;
847 }
848 return true;
849 }
850
851 /**
852 * Attempt to redirect to a URL with a QUERY_STRING that's not dangerous in
853 * IE 6. Returns true if it was successful, false otherwise.
854 *
855 * @param $url string
856 * @return bool
857 */
858 protected function doSecurityRedirect( $url ) {
859 header( 'Location: ' . $url );
860 header( 'Content-Type: text/html' );
861 $encUrl = htmlspecialchars( $url );
862 echo <<<HTML
863 <html>
864 <head>
865 <title>Security redirect</title>
866 </head>
867 <body>
868 <h1>Security redirect</h1>
869 <p>
870 We can't serve non-HTML content from the URL you have requested, because
871 Internet Explorer would interpret it as an incorrect and potentially dangerous
872 content type.</p>
873 <p>Instead, please use <a href="$encUrl">this URL</a>, which is the same as the URL you have requested, except that
874 "&amp;*" is appended. This prevents Internet Explorer from seeing a bogus file
875 extension.
876 </p>
877 </body>
878 </html>
879 HTML;
880 echo "\n";
881 return true;
882 }
883
884 /**
885 * Returns true if the PATH_INFO ends with an extension other than a script
886 * extension. This could confuse IE for scripts that send arbitrary data which
887 * is not HTML but may be detected as such.
888 *
889 * Various past attempts to use the URL to make this check have generally
890 * run up against the fact that CGI does not provide a standard method to
891 * determine the URL. PATH_INFO may be mangled (e.g. if cgi.fix_pathinfo=0),
892 * but only by prefixing it with the script name and maybe some other stuff,
893 * the extension is not mangled. So this should be a reasonably portable
894 * way to perform this security check.
895 *
896 * Also checks for anything that looks like a file extension at the end of
897 * QUERY_STRING, since IE 6 and earlier will use this to get the file type
898 * if there was no dot before the question mark (bug 28235).
899 *
900 * @deprecated Use checkUrlExtension().
901 */
902 public function isPathInfoBad( $extWhitelist = array() ) {
903 global $wgScriptExtension;
904 $extWhitelist[] = ltrim( $wgScriptExtension, '.' );
905 return IEUrlExtension::areServerVarsBad( $_SERVER, $extWhitelist );
906 }
907
908 /**
909 * Parse the Accept-Language header sent by the client into an array
910 * @return array( languageCode => q-value ) sorted by q-value in descending order
911 * May contain the "language" '*', which applies to languages other than those explicitly listed.
912 * This is aligned with rfc2616 section 14.4
913 */
914 public function getAcceptLang() {
915 // Modified version of code found at http://www.thefutureoftheweb.com/blog/use-accept-language-header
916 $acceptLang = $this->getHeader( 'Accept-Language' );
917 if ( !$acceptLang ) {
918 return array();
919 }
920
921 // Return the language codes in lower case
922 $acceptLang = strtolower( $acceptLang );
923
924 // Break up string into pieces (languages and q factors)
925 $lang_parse = null;
926 preg_match_all( '/([a-z]{1,8}(-[a-z]{1,8})?|\*)\s*(;\s*q\s*=\s*(1|0(\.[0-9]+)?)?)?/',
927 $acceptLang, $lang_parse );
928
929 if ( !count( $lang_parse[1] ) ) {
930 return array();
931 }
932
933 // Create a list like "en" => 0.8
934 $langs = array_combine( $lang_parse[1], $lang_parse[4] );
935 // Set default q factor to 1
936 foreach ( $langs as $lang => $val ) {
937 if ( $val === '' ) {
938 $langs[$lang] = 1;
939 } elseif ( $val == 0 ) {
940 unset($langs[$lang]);
941 }
942 }
943
944 // Sort list
945 arsort( $langs, SORT_NUMERIC );
946 return $langs;
947 }
948 }
949
950 /**
951 * Object to access the $_FILES array
952 */
953 class WebRequestUpload {
954 protected $request;
955 protected $doesExist;
956 protected $fileInfo;
957
958 /**
959 * Constructor. Should only be called by WebRequest
960 *
961 * @param $request WebRequest The associated request
962 * @param $key string Key in $_FILES array (name of form field)
963 */
964 public function __construct( $request, $key ) {
965 $this->request = $request;
966 $this->doesExist = isset( $_FILES[$key] );
967 if ( $this->doesExist ) {
968 $this->fileInfo = $_FILES[$key];
969 }
970 }
971
972 /**
973 * Return whether a file with this name was uploaded.
974 *
975 * @return bool
976 */
977 public function exists() {
978 return $this->doesExist;
979 }
980
981 /**
982 * Return the original filename of the uploaded file
983 *
984 * @return mixed Filename or null if non-existent
985 */
986 public function getName() {
987 if ( !$this->exists() ) {
988 return null;
989 }
990
991 global $wgContLang;
992 $name = $this->fileInfo['name'];
993
994 # Safari sends filenames in HTML-encoded Unicode form D...
995 # Horrid and evil! Let's try to make some kind of sense of it.
996 $name = Sanitizer::decodeCharReferences( $name );
997 $name = $wgContLang->normalize( $name );
998 wfDebug( __METHOD__ . ": {$this->fileInfo['name']} normalized to '$name'\n" );
999 return $name;
1000 }
1001
1002 /**
1003 * Return the file size of the uploaded file
1004 *
1005 * @return int File size or zero if non-existent
1006 */
1007 public function getSize() {
1008 if ( !$this->exists() ) {
1009 return 0;
1010 }
1011
1012 return $this->fileInfo['size'];
1013 }
1014
1015 /**
1016 * Return the path to the temporary file
1017 *
1018 * @return mixed Path or null if non-existent
1019 */
1020 public function getTempName() {
1021 if ( !$this->exists() ) {
1022 return null;
1023 }
1024
1025 return $this->fileInfo['tmp_name'];
1026 }
1027
1028 /**
1029 * Return the upload error. See link for explanation
1030 * http://www.php.net/manual/en/features.file-upload.errors.php
1031 *
1032 * @return int One of the UPLOAD_ constants, 0 if non-existent
1033 */
1034 public function getError() {
1035 if ( !$this->exists() ) {
1036 return 0; # UPLOAD_ERR_OK
1037 }
1038
1039 return $this->fileInfo['error'];
1040 }
1041
1042 /**
1043 * Returns whether this upload failed because of overflow of a maximum set
1044 * in php.ini
1045 *
1046 * @return bool
1047 */
1048 public function isIniSizeOverflow() {
1049 if ( $this->getError() == UPLOAD_ERR_INI_SIZE ) {
1050 # PHP indicated that upload_max_filesize is exceeded
1051 return true;
1052 }
1053
1054 $contentLength = $this->request->getHeader( 'CONTENT_LENGTH' );
1055 if ( $contentLength > wfShorthandToInteger( ini_get( 'post_max_size' ) ) ) {
1056 # post_max_size is exceeded
1057 return true;
1058 }
1059
1060 return false;
1061 }
1062 }
1063
1064 /**
1065 * WebRequest clone which takes values from a provided array.
1066 *
1067 * @ingroup HTTP
1068 */
1069 class FauxRequest extends WebRequest {
1070 private $wasPosted = false;
1071 private $session = array();
1072
1073 /**
1074 * @param $data Array of *non*-urlencoded key => value pairs, the
1075 * fake GET/POST values
1076 * @param $wasPosted Bool: whether to treat the data as POST
1077 * @param $session Mixed: session array or null
1078 */
1079 public function __construct( $data, $wasPosted = false, $session = null ) {
1080 if( is_array( $data ) ) {
1081 $this->data = $data;
1082 } else {
1083 throw new MWException( "FauxRequest() got bogus data" );
1084 }
1085 $this->wasPosted = $wasPosted;
1086 if( $session )
1087 $this->session = $session;
1088 }
1089
1090 private function notImplemented( $method ) {
1091 throw new MWException( "{$method}() not implemented" );
1092 }
1093
1094 public function getText( $name, $default = '' ) {
1095 # Override; don't recode since we're using internal data
1096 return (string)$this->getVal( $name, $default );
1097 }
1098
1099 public function getValues() {
1100 return $this->data;
1101 }
1102
1103 public function getQueryValues() {
1104 if ( $this->wasPosted ) {
1105 return array();
1106 } else {
1107 return $this->data;
1108 }
1109 }
1110
1111 public function wasPosted() {
1112 return $this->wasPosted;
1113 }
1114
1115 public function checkSessionCookie() {
1116 return false;
1117 }
1118
1119 public function getRequestURL() {
1120 $this->notImplemented( __METHOD__ );
1121 }
1122
1123 public function getHeader( $name ) {
1124 return isset( $this->headers[$name] ) ? $this->headers[$name] : false;
1125 }
1126
1127 public function setHeader( $name, $val ) {
1128 $this->headers[$name] = $val;
1129 }
1130
1131 public function getSessionData( $key ) {
1132 if( isset( $this->session[$key] ) )
1133 return $this->session[$key];
1134 }
1135
1136 public function setSessionData( $key, $data ) {
1137 $this->session[$key] = $data;
1138 }
1139
1140 public function getSessionArray() {
1141 return $this->session;
1142 }
1143
1144 public function isPathInfoBad( $extWhitelist = array() ) {
1145 return false;
1146 }
1147
1148 public function checkUrlExtension( $extWhitelist = array() ) {
1149 return true;
1150 }
1151 }