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