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