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