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