2c146188a17c6d780dbad50ed12124763bff2679
[lhc/web/wiklou.git] / includes / WebRequest.php
1 <?php
2 /**
3 * Deal with importing all those nasty globals and things
4 *
5 * Copyright © 2003 Brion Vibber <brion@pobox.com>
6 * https://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 use MediaWiki\Session\SessionManager;
27
28 /**
29 * The WebRequest class encapsulates getting at data passed in the
30 * URL or via a POSTed form stripping illegal input characters and
31 * normalizing Unicode sequences.
32 *
33 * @ingroup HTTP
34 */
35 class WebRequest {
36 protected $data, $headers = array();
37
38 /**
39 * Flag to make WebRequest::getHeader return an array of values.
40 * @since 1.26
41 */
42 const GETHEADER_LIST = 1;
43
44 /**
45 * Lazy-init response object
46 * @var WebResponse
47 */
48 private $response;
49
50 /**
51 * Cached client IP address
52 * @var string
53 */
54 private $ip;
55
56 /**
57 * The timestamp of the start of the request, with microsecond precision.
58 * @var float
59 */
60 protected $requestTime;
61
62 /**
63 * Cached URL protocol
64 * @var string
65 */
66 protected $protocol;
67
68 /**
69 * @var \\MediaWiki\\Session\\SessionId|null Session ID to use for this
70 * request. We can't save the session directly due to reference cycles not
71 * working too well (slow GC in Zend and never collected in HHVM).
72 */
73 protected $sessionId = null;
74
75 public function __construct() {
76 $this->requestTime = isset( $_SERVER['REQUEST_TIME_FLOAT'] )
77 ? $_SERVER['REQUEST_TIME_FLOAT'] : microtime( true );
78
79 // POST overrides GET data
80 // We don't use $_REQUEST here to avoid interference from cookies...
81 $this->data = $_POST + $_GET;
82 }
83
84 /**
85 * Extract relevant query arguments from the http request uri's path
86 * to be merged with the normal php provided query arguments.
87 * Tries to use the REQUEST_URI data if available and parses it
88 * according to the wiki's configuration looking for any known pattern.
89 *
90 * If the REQUEST_URI is not provided we'll fall back on the PATH_INFO
91 * provided by the server if any and use that to set a 'title' parameter.
92 *
93 * @param string $want If this is not 'all', then the function
94 * will return an empty array if it determines that the URL is
95 * inside a rewrite path.
96 *
97 * @return array Any query arguments found in path matches.
98 */
99 public static function getPathInfo( $want = 'all' ) {
100 global $wgUsePathInfo;
101 // PATH_INFO is mangled due to http://bugs.php.net/bug.php?id=31892
102 // And also by Apache 2.x, double slashes are converted to single slashes.
103 // So we will use REQUEST_URI if possible.
104 $matches = array();
105 if ( !empty( $_SERVER['REQUEST_URI'] ) ) {
106 // Slurp out the path portion to examine...
107 $url = $_SERVER['REQUEST_URI'];
108 if ( !preg_match( '!^https?://!', $url ) ) {
109 $url = 'http://unused' . $url;
110 }
111 MediaWiki\suppressWarnings();
112 $a = parse_url( $url );
113 MediaWiki\restoreWarnings();
114 if ( $a ) {
115 $path = isset( $a['path'] ) ? $a['path'] : '';
116
117 global $wgScript;
118 if ( $path == $wgScript && $want !== 'all' ) {
119 // Script inside a rewrite path?
120 // Abort to keep from breaking...
121 return $matches;
122 }
123
124 $router = new PathRouter;
125
126 // Raw PATH_INFO style
127 $router->add( "$wgScript/$1" );
128
129 if ( isset( $_SERVER['SCRIPT_NAME'] )
130 && preg_match( '/\.php5?/', $_SERVER['SCRIPT_NAME'] )
131 ) {
132 # Check for SCRIPT_NAME, we handle index.php explicitly
133 # But we do have some other .php files such as img_auth.php
134 # Don't let root article paths clober the parsing for them
135 $router->add( $_SERVER['SCRIPT_NAME'] . "/$1" );
136 }
137
138 global $wgArticlePath;
139 if ( $wgArticlePath ) {
140 $router->add( $wgArticlePath );
141 }
142
143 global $wgActionPaths;
144 if ( $wgActionPaths ) {
145 $router->add( $wgActionPaths, array( 'action' => '$key' ) );
146 }
147
148 global $wgVariantArticlePath, $wgContLang;
149 if ( $wgVariantArticlePath ) {
150 $router->add( $wgVariantArticlePath,
151 array( 'variant' => '$2' ),
152 array( '$2' => $wgContLang->getVariants() )
153 );
154 }
155
156 Hooks::run( 'WebRequestPathInfoRouter', array( $router ) );
157
158 $matches = $router->parse( $path );
159 }
160 } elseif ( $wgUsePathInfo ) {
161 if ( isset( $_SERVER['ORIG_PATH_INFO'] ) && $_SERVER['ORIG_PATH_INFO'] != '' ) {
162 // Mangled PATH_INFO
163 // http://bugs.php.net/bug.php?id=31892
164 // Also reported when ini_get('cgi.fix_pathinfo')==false
165 $matches['title'] = substr( $_SERVER['ORIG_PATH_INFO'], 1 );
166
167 } elseif ( isset( $_SERVER['PATH_INFO'] ) && $_SERVER['PATH_INFO'] != '' ) {
168 // Regular old PATH_INFO yay
169 $matches['title'] = substr( $_SERVER['PATH_INFO'], 1 );
170 }
171 }
172
173 return $matches;
174 }
175
176 /**
177 * Work out an appropriate URL prefix containing scheme and host, based on
178 * information detected from $_SERVER
179 *
180 * @return string
181 */
182 public static function detectServer() {
183 global $wgAssumeProxiesUseDefaultProtocolPorts;
184
185 $proto = self::detectProtocol();
186 $stdPort = $proto === 'https' ? 443 : 80;
187
188 $varNames = array( 'HTTP_HOST', 'SERVER_NAME', 'HOSTNAME', 'SERVER_ADDR' );
189 $host = 'localhost';
190 $port = $stdPort;
191 foreach ( $varNames as $varName ) {
192 if ( !isset( $_SERVER[$varName] ) ) {
193 continue;
194 }
195
196 $parts = IP::splitHostAndPort( $_SERVER[$varName] );
197 if ( !$parts ) {
198 // Invalid, do not use
199 continue;
200 }
201
202 $host = $parts[0];
203 if ( $wgAssumeProxiesUseDefaultProtocolPorts && isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) ) {
204 // Bug 70021: Assume that upstream proxy is running on the default
205 // port based on the protocol. We have no reliable way to determine
206 // the actual port in use upstream.
207 $port = $stdPort;
208 } elseif ( $parts[1] === false ) {
209 if ( isset( $_SERVER['SERVER_PORT'] ) ) {
210 $port = $_SERVER['SERVER_PORT'];
211 } // else leave it as $stdPort
212 } else {
213 $port = $parts[1];
214 }
215 break;
216 }
217
218 return $proto . '://' . IP::combineHostAndPort( $host, $port, $stdPort );
219 }
220
221 /**
222 * Detect the protocol from $_SERVER.
223 * This is for use prior to Setup.php, when no WebRequest object is available.
224 * At other times, use the non-static function getProtocol().
225 *
226 * @return array
227 */
228 public static function detectProtocol() {
229 if ( ( !empty( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] !== 'off' ) ||
230 ( isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) &&
231 $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ) ) {
232 return 'https';
233 } else {
234 return 'http';
235 }
236 }
237
238 /**
239 * Get the number of seconds to have elapsed since request start,
240 * in fractional seconds, with microsecond resolution.
241 *
242 * @return float
243 * @since 1.25
244 */
245 public function getElapsedTime() {
246 return microtime( true ) - $this->requestTime;
247 }
248
249 /**
250 * Get the current URL protocol (http or https)
251 * @return string
252 */
253 public function getProtocol() {
254 if ( $this->protocol === null ) {
255 $this->protocol = self::detectProtocol();
256 }
257 return $this->protocol;
258 }
259
260 /**
261 * Check for title, action, and/or variant data in the URL
262 * and interpolate it into the GET variables.
263 * This should only be run after $wgContLang is available,
264 * as we may need the list of language variants to determine
265 * available variant URLs.
266 */
267 public function interpolateTitle() {
268 // bug 16019: title interpolation on API queries is useless and sometimes harmful
269 if ( defined( 'MW_API' ) ) {
270 return;
271 }
272
273 $matches = self::getPathInfo( 'title' );
274 foreach ( $matches as $key => $val ) {
275 $this->data[$key] = $_GET[$key] = $_REQUEST[$key] = $val;
276 }
277 }
278
279 /**
280 * URL rewriting function; tries to extract page title and,
281 * optionally, one other fixed parameter value from a URL path.
282 *
283 * @param string $path The URL path given from the client
284 * @param array $bases One or more URLs, optionally with $1 at the end
285 * @param string $key If provided, the matching key in $bases will be
286 * passed on as the value of this URL parameter
287 * @return array Array of URL variables to interpolate; empty if no match
288 */
289 static function extractTitle( $path, $bases, $key = false ) {
290 foreach ( (array)$bases as $keyValue => $base ) {
291 // Find the part after $wgArticlePath
292 $base = str_replace( '$1', '', $base );
293 $baseLen = strlen( $base );
294 if ( substr( $path, 0, $baseLen ) == $base ) {
295 $raw = substr( $path, $baseLen );
296 if ( $raw !== '' ) {
297 $matches = array( 'title' => rawurldecode( $raw ) );
298 if ( $key ) {
299 $matches[$key] = $keyValue;
300 }
301 return $matches;
302 }
303 }
304 }
305 return array();
306 }
307
308 /**
309 * Recursively normalizes UTF-8 strings in the given array.
310 *
311 * @param string|array $data
312 * @return array|string Cleaned-up version of the given
313 * @private
314 */
315 function normalizeUnicode( $data ) {
316 if ( is_array( $data ) ) {
317 foreach ( $data as $key => $val ) {
318 $data[$key] = $this->normalizeUnicode( $val );
319 }
320 } else {
321 global $wgContLang;
322 $data = isset( $wgContLang ) ?
323 $wgContLang->normalize( $data ) :
324 UtfNormal\Validator::cleanUp( $data );
325 }
326 return $data;
327 }
328
329 /**
330 * Fetch a value from the given array or return $default if it's not set.
331 *
332 * @param array $arr
333 * @param string $name
334 * @param mixed $default
335 * @return mixed
336 */
337 private function getGPCVal( $arr, $name, $default ) {
338 # PHP is so nice to not touch input data, except sometimes:
339 # http://us2.php.net/variables.external#language.variables.external.dot-in-names
340 # Work around PHP *feature* to avoid *bugs* elsewhere.
341 $name = strtr( $name, '.', '_' );
342 if ( isset( $arr[$name] ) ) {
343 global $wgContLang;
344 $data = $arr[$name];
345 if ( isset( $_GET[$name] ) && !is_array( $data ) ) {
346 # Check for alternate/legacy character encoding.
347 if ( isset( $wgContLang ) ) {
348 $data = $wgContLang->checkTitleEncoding( $data );
349 }
350 }
351 $data = $this->normalizeUnicode( $data );
352 return $data;
353 } else {
354 return $default;
355 }
356 }
357
358 /**
359 * Fetch a scalar from the input or return $default if it's not set.
360 * Returns a string. Arrays are discarded. Useful for
361 * non-freeform text inputs (e.g. predefined internal text keys
362 * selected by a drop-down menu). For freeform input, see getText().
363 *
364 * @param string $name
365 * @param string $default Optional default (or null)
366 * @return string
367 */
368 public function getVal( $name, $default = null ) {
369 $val = $this->getGPCVal( $this->data, $name, $default );
370 if ( is_array( $val ) ) {
371 $val = $default;
372 }
373 if ( is_null( $val ) ) {
374 return $val;
375 } else {
376 return (string)$val;
377 }
378 }
379
380 /**
381 * Set an arbitrary value into our get/post data.
382 *
383 * @param string $key Key name to use
384 * @param mixed $value Value to set
385 * @return mixed Old value if one was present, null otherwise
386 */
387 public function setVal( $key, $value ) {
388 $ret = isset( $this->data[$key] ) ? $this->data[$key] : null;
389 $this->data[$key] = $value;
390 return $ret;
391 }
392
393 /**
394 * Unset an arbitrary value from our get/post data.
395 *
396 * @param string $key Key name to use
397 * @return mixed Old value if one was present, null otherwise
398 */
399 public function unsetVal( $key ) {
400 if ( !isset( $this->data[$key] ) ) {
401 $ret = null;
402 } else {
403 $ret = $this->data[$key];
404 unset( $this->data[$key] );
405 }
406 return $ret;
407 }
408
409 /**
410 * Fetch an array from the input or return $default if it's not set.
411 * If source was scalar, will return an array with a single element.
412 * If no source and no default, returns null.
413 *
414 * @param string $name
415 * @param array $default Optional default (or null)
416 * @return array
417 */
418 public function getArray( $name, $default = null ) {
419 $val = $this->getGPCVal( $this->data, $name, $default );
420 if ( is_null( $val ) ) {
421 return null;
422 } else {
423 return (array)$val;
424 }
425 }
426
427 /**
428 * Fetch an array of integers, or return $default if it's not set.
429 * If source was scalar, will return an array with a single element.
430 * If no source and no default, returns null.
431 * If an array is returned, contents are guaranteed to be integers.
432 *
433 * @param string $name
434 * @param array $default Option default (or null)
435 * @return array Array of ints
436 */
437 public function getIntArray( $name, $default = null ) {
438 $val = $this->getArray( $name, $default );
439 if ( is_array( $val ) ) {
440 $val = array_map( 'intval', $val );
441 }
442 return $val;
443 }
444
445 /**
446 * Fetch an integer value from the input or return $default if not set.
447 * Guaranteed to return an integer; non-numeric input will typically
448 * return 0.
449 *
450 * @param string $name
451 * @param int $default
452 * @return int
453 */
454 public function getInt( $name, $default = 0 ) {
455 return intval( $this->getVal( $name, $default ) );
456 }
457
458 /**
459 * Fetch an integer value from the input or return null if empty.
460 * Guaranteed to return an integer or null; non-numeric input will
461 * typically return null.
462 *
463 * @param string $name
464 * @return int|null
465 */
466 public function getIntOrNull( $name ) {
467 $val = $this->getVal( $name );
468 return is_numeric( $val )
469 ? intval( $val )
470 : null;
471 }
472
473 /**
474 * Fetch a floating point value from the input or return $default if not set.
475 * Guaranteed to return a float; non-numeric input will typically
476 * return 0.
477 *
478 * @since 1.23
479 * @param string $name
480 * @param float $default
481 * @return float
482 */
483 public function getFloat( $name, $default = 0.0 ) {
484 return floatval( $this->getVal( $name, $default ) );
485 }
486
487 /**
488 * Fetch a boolean value from the input or return $default if not set.
489 * Guaranteed to return true or false, with normal PHP semantics for
490 * boolean interpretation of strings.
491 *
492 * @param string $name
493 * @param bool $default
494 * @return bool
495 */
496 public function getBool( $name, $default = false ) {
497 return (bool)$this->getVal( $name, $default );
498 }
499
500 /**
501 * Fetch a boolean value from the input or return $default if not set.
502 * Unlike getBool, the string "false" will result in boolean false, which is
503 * useful when interpreting information sent from JavaScript.
504 *
505 * @param string $name
506 * @param bool $default
507 * @return bool
508 */
509 public function getFuzzyBool( $name, $default = false ) {
510 return $this->getBool( $name, $default ) && strcasecmp( $this->getVal( $name ), 'false' ) !== 0;
511 }
512
513 /**
514 * Return true if the named value is set in the input, whatever that
515 * value is (even "0"). Return false if the named value is not set.
516 * Example use is checking for the presence of check boxes in forms.
517 *
518 * @param string $name
519 * @return bool
520 */
521 public function getCheck( $name ) {
522 # Checkboxes and buttons are only present when clicked
523 # Presence connotes truth, absence false
524 return $this->getVal( $name, null ) !== null;
525 }
526
527 /**
528 * Fetch a text string from the given array or return $default if it's not
529 * set. Carriage returns are stripped from the text, and with some language
530 * modules there is an input transliteration applied. This should generally
531 * be used for form "<textarea>" and "<input>" fields. Used for
532 * user-supplied freeform text input (for which input transformations may
533 * be required - e.g. Esperanto x-coding).
534 *
535 * @param string $name
536 * @param string $default Optional
537 * @return string
538 */
539 public function getText( $name, $default = '' ) {
540 global $wgContLang;
541 $val = $this->getVal( $name, $default );
542 return str_replace( "\r\n", "\n",
543 $wgContLang->recodeInput( $val ) );
544 }
545
546 /**
547 * Extracts the given named values into an array.
548 * If no arguments are given, returns all input values.
549 * No transformation is performed on the values.
550 *
551 * @return array
552 */
553 public function getValues() {
554 $names = func_get_args();
555 if ( count( $names ) == 0 ) {
556 $names = array_keys( $this->data );
557 }
558
559 $retVal = array();
560 foreach ( $names as $name ) {
561 $value = $this->getGPCVal( $this->data, $name, null );
562 if ( !is_null( $value ) ) {
563 $retVal[$name] = $value;
564 }
565 }
566 return $retVal;
567 }
568
569 /**
570 * Returns the names of all input values excluding those in $exclude.
571 *
572 * @param array $exclude
573 * @return array
574 */
575 public function getValueNames( $exclude = array() ) {
576 return array_diff( array_keys( $this->getValues() ), $exclude );
577 }
578
579 /**
580 * Get the values passed in the query string.
581 * No transformation is performed on the values.
582 *
583 * @return array
584 */
585 public function getQueryValues() {
586 return $_GET;
587 }
588
589 /**
590 * Return the contents of the Query with no decoding. Use when you need to
591 * know exactly what was sent, e.g. for an OAuth signature over the elements.
592 *
593 * @return string
594 */
595 public function getRawQueryString() {
596 return $_SERVER['QUERY_STRING'];
597 }
598
599 /**
600 * Return the contents of the POST with no decoding. Use when you need to
601 * know exactly what was sent, e.g. for an OAuth signature over the elements.
602 *
603 * @return string
604 */
605 public function getRawPostString() {
606 if ( !$this->wasPosted() ) {
607 return '';
608 }
609 return $this->getRawInput();
610 }
611
612 /**
613 * Return the raw request body, with no processing. Cached since some methods
614 * disallow reading the stream more than once. As stated in the php docs, this
615 * does not work with enctype="multipart/form-data".
616 *
617 * @return string
618 */
619 public function getRawInput() {
620 static $input = null;
621 if ( $input === null ) {
622 $input = file_get_contents( 'php://input' );
623 }
624 return $input;
625 }
626
627 /**
628 * Get the HTTP method used for this request.
629 *
630 * @return string
631 */
632 public function getMethod() {
633 return isset( $_SERVER['REQUEST_METHOD'] ) ? $_SERVER['REQUEST_METHOD'] : 'GET';
634 }
635
636 /**
637 * Returns true if the present request was reached by a POST operation,
638 * false otherwise (GET, HEAD, or command-line).
639 *
640 * Note that values retrieved by the object may come from the
641 * GET URL etc even on a POST request.
642 *
643 * @return bool
644 */
645 public function wasPosted() {
646 return $this->getMethod() == 'POST';
647 }
648
649 /**
650 * Return the session for this request
651 * @since 1.27
652 * @note For performance, keep the session locally if you will be making
653 * much use of it instead of calling this method repeatedly.
654 * @return MediaWiki\\Session\\Session
655 */
656 public function getSession() {
657 if ( $this->sessionId !== null ) {
658 $session = SessionManager::singleton()->getSessionById( (string)$this->sessionId, true, $this );
659 if ( $session ) {
660 return $session;
661 }
662 }
663
664 $session = SessionManager::singleton()->getSessionForRequest( $this );
665 $this->sessionId = $session->getSessionId();
666 return $session;
667 }
668
669 /**
670 * Set the session for this request
671 * @since 1.27
672 * @private For use by MediaWiki\\Session classes only
673 * @param MediaWiki\\Session\\SessionId $sessionId
674 */
675 public function setSessionId( MediaWiki\Session\SessionId $sessionId ) {
676 $this->sessionId = $sessionId;
677 }
678
679 /**
680 * Returns true if the request has a persistent session.
681 * This does not necessarily mean that the user is logged in!
682 *
683 * @deprecated since 1.27, use
684 * \\MediaWiki\\Session\\SessionManager::singleton()->getPersistedSessionId()
685 * instead.
686 * @return bool
687 */
688 public function checkSessionCookie() {
689 wfDeprecated( __METHOD__, '1.27' );
690 return SessionManager::singleton()->getPersistedSessionId( $this ) !== null;
691 }
692
693 /**
694 * Get a cookie from the $_COOKIE jar
695 *
696 * @param string $key The name of the cookie
697 * @param string $prefix A prefix to use for the cookie name, if not $wgCookiePrefix
698 * @param mixed $default What to return if the value isn't found
699 * @return mixed Cookie value or $default if the cookie not set
700 */
701 public function getCookie( $key, $prefix = null, $default = null ) {
702 if ( $prefix === null ) {
703 global $wgCookiePrefix;
704 $prefix = $wgCookiePrefix;
705 }
706 return $this->getGPCVal( $_COOKIE, $prefix . $key, $default );
707 }
708
709 /**
710 * Return the path and query string portion of the request URI.
711 * This will be suitable for use as a relative link in HTML output.
712 *
713 * @throws MWException
714 * @return string
715 */
716 public function getRequestURL() {
717 if ( isset( $_SERVER['REQUEST_URI'] ) && strlen( $_SERVER['REQUEST_URI'] ) ) {
718 $base = $_SERVER['REQUEST_URI'];
719 } elseif ( isset( $_SERVER['HTTP_X_ORIGINAL_URL'] )
720 && strlen( $_SERVER['HTTP_X_ORIGINAL_URL'] )
721 ) {
722 // Probably IIS; doesn't set REQUEST_URI
723 $base = $_SERVER['HTTP_X_ORIGINAL_URL'];
724 } elseif ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
725 $base = $_SERVER['SCRIPT_NAME'];
726 if ( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
727 $base .= '?' . $_SERVER['QUERY_STRING'];
728 }
729 } else {
730 // This shouldn't happen!
731 throw new MWException( "Web server doesn't provide either " .
732 "REQUEST_URI, HTTP_X_ORIGINAL_URL or SCRIPT_NAME. Report details " .
733 "of your web server configuration to https://phabricator.wikimedia.org/" );
734 }
735 // User-agents should not send a fragment with the URI, but
736 // if they do, and the web server passes it on to us, we
737 // need to strip it or we get false-positive redirect loops
738 // or weird output URLs
739 $hash = strpos( $base, '#' );
740 if ( $hash !== false ) {
741 $base = substr( $base, 0, $hash );
742 }
743
744 if ( $base[0] == '/' ) {
745 // More than one slash will look like it is protocol relative
746 return preg_replace( '!^/+!', '/', $base );
747 } else {
748 // We may get paths with a host prepended; strip it.
749 return preg_replace( '!^[^:]+://[^/]+/+!', '/', $base );
750 }
751 }
752
753 /**
754 * Return the request URI with the canonical service and hostname, path,
755 * and query string. This will be suitable for use as an absolute link
756 * in HTML or other output.
757 *
758 * If $wgServer is protocol-relative, this will return a fully
759 * qualified URL with the protocol that was used for this request.
760 *
761 * @return string
762 */
763 public function getFullRequestURL() {
764 return wfExpandUrl( $this->getRequestURL(), PROTO_CURRENT );
765 }
766
767 /**
768 * @param string $key
769 * @param string $value
770 * @return string
771 */
772 public function appendQueryValue( $key, $value ) {
773 return $this->appendQueryArray( array( $key => $value ) );
774 }
775
776 /**
777 * Appends or replaces value of query variables.
778 *
779 * @param array $array Array of values to replace/add to query
780 * @return string
781 */
782 public function appendQueryArray( $array ) {
783 $newquery = $this->getQueryValues();
784 unset( $newquery['title'] );
785 $newquery = array_merge( $newquery, $array );
786
787 return wfArrayToCgi( $newquery );
788 }
789
790 /**
791 * Check for limit and offset parameters on the input, and return sensible
792 * defaults if not given. The limit must be positive and is capped at 5000.
793 * Offset must be positive but is not capped.
794 *
795 * @param int $deflimit Limit to use if no input and the user hasn't set the option.
796 * @param string $optionname To specify an option other than rclimit to pull from.
797 * @return int[] First element is limit, second is offset
798 */
799 public function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
800 global $wgUser;
801
802 $limit = $this->getInt( 'limit', 0 );
803 if ( $limit < 0 ) {
804 $limit = 0;
805 }
806 if ( ( $limit == 0 ) && ( $optionname != '' ) ) {
807 $limit = $wgUser->getIntOption( $optionname );
808 }
809 if ( $limit <= 0 ) {
810 $limit = $deflimit;
811 }
812 if ( $limit > 5000 ) {
813 $limit = 5000; # We have *some* limits...
814 }
815
816 $offset = $this->getInt( 'offset', 0 );
817 if ( $offset < 0 ) {
818 $offset = 0;
819 }
820
821 return array( $limit, $offset );
822 }
823
824 /**
825 * Return the path to the temporary file where PHP has stored the upload.
826 *
827 * @param string $key
828 * @return string|null String or null if no such file.
829 */
830 public function getFileTempname( $key ) {
831 $file = new WebRequestUpload( $this, $key );
832 return $file->getTempName();
833 }
834
835 /**
836 * Return the upload error or 0
837 *
838 * @param string $key
839 * @return int
840 */
841 public function getUploadError( $key ) {
842 $file = new WebRequestUpload( $this, $key );
843 return $file->getError();
844 }
845
846 /**
847 * Return the original filename of the uploaded file, as reported by
848 * the submitting user agent. HTML-style character entities are
849 * interpreted and normalized to Unicode normalization form C, in part
850 * to deal with weird input from Safari with non-ASCII filenames.
851 *
852 * Other than this the name is not verified for being a safe filename.
853 *
854 * @param string $key
855 * @return string|null String or null if no such file.
856 */
857 public function getFileName( $key ) {
858 $file = new WebRequestUpload( $this, $key );
859 return $file->getName();
860 }
861
862 /**
863 * Return a WebRequestUpload object corresponding to the key
864 *
865 * @param string $key
866 * @return WebRequestUpload
867 */
868 public function getUpload( $key ) {
869 return new WebRequestUpload( $this, $key );
870 }
871
872 /**
873 * Return a handle to WebResponse style object, for setting cookies,
874 * headers and other stuff, for Request being worked on.
875 *
876 * @return WebResponse
877 */
878 public function response() {
879 /* Lazy initialization of response object for this request */
880 if ( !is_object( $this->response ) ) {
881 $class = ( $this instanceof FauxRequest ) ? 'FauxResponse' : 'WebResponse';
882 $this->response = new $class();
883 }
884 return $this->response;
885 }
886
887 /**
888 * Initialise the header list
889 */
890 protected function initHeaders() {
891 if ( count( $this->headers ) ) {
892 return;
893 }
894
895 $apacheHeaders = function_exists( 'apache_request_headers' ) ? apache_request_headers() : false;
896 if ( $apacheHeaders ) {
897 foreach ( $apacheHeaders as $tempName => $tempValue ) {
898 $this->headers[strtoupper( $tempName )] = $tempValue;
899 }
900 } else {
901 foreach ( $_SERVER as $name => $value ) {
902 if ( substr( $name, 0, 5 ) === 'HTTP_' ) {
903 $name = str_replace( '_', '-', substr( $name, 5 ) );
904 $this->headers[$name] = $value;
905 } elseif ( $name === 'CONTENT_LENGTH' ) {
906 $this->headers['CONTENT-LENGTH'] = $value;
907 }
908 }
909 }
910 }
911
912 /**
913 * Get an array containing all request headers
914 *
915 * @return array Mapping header name to its value
916 */
917 public function getAllHeaders() {
918 $this->initHeaders();
919 return $this->headers;
920 }
921
922 /**
923 * Get a request header, or false if it isn't set.
924 *
925 * @param string $name Case-insensitive header name
926 * @param int $flags Bitwise combination of:
927 * WebRequest::GETHEADER_LIST Treat the header as a comma-separated list
928 * of values, as described in RFC 2616 § 4.2.
929 * (since 1.26).
930 * @return string|array|bool False if header is unset; otherwise the
931 * header value(s) as either a string (the default) or an array, if
932 * WebRequest::GETHEADER_LIST flag was set.
933 */
934 public function getHeader( $name, $flags = 0 ) {
935 $this->initHeaders();
936 $name = strtoupper( $name );
937 if ( !isset( $this->headers[$name] ) ) {
938 return false;
939 }
940 $value = $this->headers[$name];
941 if ( $flags & self::GETHEADER_LIST ) {
942 $value = array_map( 'trim', explode( ',', $value ) );
943 }
944 return $value;
945 }
946
947 /**
948 * Get data from the session
949 *
950 * @note Prefer $this->getSession() instead if making multiple calls.
951 * @param string $key Name of key in the session
952 * @return mixed
953 */
954 public function getSessionData( $key ) {
955 return $this->getSession()->get( $key );
956 }
957
958 /**
959 * Set session data
960 *
961 * @note Prefer $this->getSession() instead if making multiple calls.
962 * @param string $key Name of key in the session
963 * @param mixed $data
964 */
965 public function setSessionData( $key, $data ) {
966 return $this->getSession()->set( $key, $data );
967 }
968
969 /**
970 * Check if Internet Explorer will detect an incorrect cache extension in
971 * PATH_INFO or QUERY_STRING. If the request can't be allowed, show an error
972 * message or redirect to a safer URL. Returns true if the URL is OK, and
973 * false if an error message has been shown and the request should be aborted.
974 *
975 * @param array $extWhitelist
976 * @throws HttpError
977 * @return bool
978 */
979 public function checkUrlExtension( $extWhitelist = array() ) {
980 $extWhitelist[] = 'php';
981 if ( IEUrlExtension::areServerVarsBad( $_SERVER, $extWhitelist ) ) {
982 if ( !$this->wasPosted() ) {
983 $newUrl = IEUrlExtension::fixUrlForIE6(
984 $this->getFullRequestURL(), $extWhitelist );
985 if ( $newUrl !== false ) {
986 $this->doSecurityRedirect( $newUrl );
987 return false;
988 }
989 }
990 throw new HttpError( 403,
991 'Invalid file extension found in the path info or query string.' );
992 }
993 return true;
994 }
995
996 /**
997 * Attempt to redirect to a URL with a QUERY_STRING that's not dangerous in
998 * IE 6. Returns true if it was successful, false otherwise.
999 *
1000 * @param string $url
1001 * @return bool
1002 */
1003 protected function doSecurityRedirect( $url ) {
1004 header( 'Location: ' . $url );
1005 header( 'Content-Type: text/html' );
1006 $encUrl = htmlspecialchars( $url );
1007 echo <<<HTML
1008 <html>
1009 <head>
1010 <title>Security redirect</title>
1011 </head>
1012 <body>
1013 <h1>Security redirect</h1>
1014 <p>
1015 We can't serve non-HTML content from the URL you have requested, because
1016 Internet Explorer would interpret it as an incorrect and potentially dangerous
1017 content type.</p>
1018 <p>Instead, please use <a href="$encUrl">this URL</a>, which is the same as the
1019 URL you have requested, except that "&amp;*" is appended. This prevents Internet
1020 Explorer from seeing a bogus file extension.
1021 </p>
1022 </body>
1023 </html>
1024 HTML;
1025 echo "\n";
1026 return true;
1027 }
1028
1029 /**
1030 * Parse the Accept-Language header sent by the client into an array
1031 *
1032 * @return array Array( languageCode => q-value ) sorted by q-value in
1033 * descending order then appearing time in the header in ascending order.
1034 * May contain the "language" '*', which applies to languages other than those explicitly listed.
1035 * This is aligned with rfc2616 section 14.4
1036 * Preference for earlier languages appears in rfc3282 as an extension to HTTP/1.1.
1037 */
1038 public function getAcceptLang() {
1039 // Modified version of code found at
1040 // http://www.thefutureoftheweb.com/blog/use-accept-language-header
1041 $acceptLang = $this->getHeader( 'Accept-Language' );
1042 if ( !$acceptLang ) {
1043 return array();
1044 }
1045
1046 // Return the language codes in lower case
1047 $acceptLang = strtolower( $acceptLang );
1048
1049 // Break up string into pieces (languages and q factors)
1050 $lang_parse = null;
1051 preg_match_all(
1052 '/([a-z]{1,8}(-[a-z]{1,8})*|\*)\s*(;\s*q\s*=\s*(1(\.0{0,3})?|0(\.[0-9]{0,3})?)?)?/',
1053 $acceptLang,
1054 $lang_parse
1055 );
1056
1057 if ( !count( $lang_parse[1] ) ) {
1058 return array();
1059 }
1060
1061 $langcodes = $lang_parse[1];
1062 $qvalues = $lang_parse[4];
1063 $indices = range( 0, count( $lang_parse[1] ) - 1 );
1064
1065 // Set default q factor to 1
1066 foreach ( $indices as $index ) {
1067 if ( $qvalues[$index] === '' ) {
1068 $qvalues[$index] = 1;
1069 } elseif ( $qvalues[$index] == 0 ) {
1070 unset( $langcodes[$index], $qvalues[$index], $indices[$index] );
1071 }
1072 }
1073
1074 // Sort list. First by $qvalues, then by order. Reorder $langcodes the same way
1075 array_multisort( $qvalues, SORT_DESC, SORT_NUMERIC, $indices, $langcodes );
1076
1077 // Create a list like "en" => 0.8
1078 $langs = array_combine( $langcodes, $qvalues );
1079
1080 return $langs;
1081 }
1082
1083 /**
1084 * Fetch the raw IP from the request
1085 *
1086 * @since 1.19
1087 *
1088 * @throws MWException
1089 * @return string
1090 */
1091 protected function getRawIP() {
1092 if ( !isset( $_SERVER['REMOTE_ADDR'] ) ) {
1093 return null;
1094 }
1095
1096 if ( is_array( $_SERVER['REMOTE_ADDR'] ) || strpos( $_SERVER['REMOTE_ADDR'], ',' ) !== false ) {
1097 throw new MWException( __METHOD__
1098 . " : Could not determine the remote IP address due to multiple values." );
1099 } else {
1100 $ipchain = $_SERVER['REMOTE_ADDR'];
1101 }
1102
1103 return IP::canonicalize( $ipchain );
1104 }
1105
1106 /**
1107 * Work out the IP address based on various globals
1108 * For trusted proxies, use the XFF client IP (first of the chain)
1109 *
1110 * @since 1.19
1111 *
1112 * @throws MWException
1113 * @return string
1114 */
1115 public function getIP() {
1116 global $wgUsePrivateIPs;
1117
1118 # Return cached result
1119 if ( $this->ip !== null ) {
1120 return $this->ip;
1121 }
1122
1123 # collect the originating ips
1124 $ip = $this->getRawIP();
1125 if ( !$ip ) {
1126 throw new MWException( 'Unable to determine IP.' );
1127 }
1128
1129 # Append XFF
1130 $forwardedFor = $this->getHeader( 'X-Forwarded-For' );
1131 if ( $forwardedFor !== false ) {
1132 $isConfigured = IP::isConfiguredProxy( $ip );
1133 $ipchain = array_map( 'trim', explode( ',', $forwardedFor ) );
1134 $ipchain = array_reverse( $ipchain );
1135 array_unshift( $ipchain, $ip );
1136
1137 # Step through XFF list and find the last address in the list which is a
1138 # trusted server. Set $ip to the IP address given by that trusted server,
1139 # unless the address is not sensible (e.g. private). However, prefer private
1140 # IP addresses over proxy servers controlled by this site (more sensible).
1141 # Note that some XFF values might be "unknown" with Squid/Varnish.
1142 foreach ( $ipchain as $i => $curIP ) {
1143 $curIP = IP::sanitizeIP( IP::canonicalize( $curIP ) );
1144 if ( !$curIP || !isset( $ipchain[$i + 1] ) || $ipchain[$i + 1] === 'unknown'
1145 || !IP::isTrustedProxy( $curIP )
1146 ) {
1147 break; // IP is not valid/trusted or does not point to anything
1148 }
1149 if (
1150 IP::isPublic( $ipchain[$i + 1] ) ||
1151 $wgUsePrivateIPs ||
1152 IP::isConfiguredProxy( $curIP ) // bug 48919; treat IP as sane
1153 ) {
1154 // Follow the next IP according to the proxy
1155 $nextIP = IP::canonicalize( $ipchain[$i + 1] );
1156 if ( !$nextIP && $isConfigured ) {
1157 // We have not yet made it past CDN/proxy servers of this site,
1158 // so either they are misconfigured or there is some IP spoofing.
1159 throw new MWException( "Invalid IP given in XFF '$forwardedFor'." );
1160 }
1161 $ip = $nextIP;
1162 // keep traversing the chain
1163 continue;
1164 }
1165 break;
1166 }
1167 }
1168
1169 # Allow extensions to improve our guess
1170 Hooks::run( 'GetIP', array( &$ip ) );
1171
1172 if ( !$ip ) {
1173 throw new MWException( "Unable to determine IP." );
1174 }
1175
1176 wfDebug( "IP: $ip\n" );
1177 $this->ip = $ip;
1178 return $ip;
1179 }
1180
1181 /**
1182 * @param string $ip
1183 * @return void
1184 * @since 1.21
1185 */
1186 public function setIP( $ip ) {
1187 $this->ip = $ip;
1188 }
1189 }