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