Merge "Actually assign suppression-related rights to 'suppress' group"
[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
399 if ( !isset( $arr[$name] ) ) {
400 return $default;
401 }
402
403 $data = $arr[$name];
404 # Optimisation: Skip UTF-8 normalization and legacy transcoding for simple ASCII strings.
405 $isAsciiStr = ( is_string( $data ) && preg_match( '/[^\x20-\x7E]/', $data ) === 0 );
406 if ( !$isAsciiStr ) {
407 if ( isset( $_GET[$name] ) && is_string( $data ) ) {
408 # Check for alternate/legacy character encoding.
409 $data = MediaWikiServices::getInstance()
410 ->getContentLanguage()
411 ->checkTitleEncoding( $data );
412 }
413 $data = $this->normalizeUnicode( $data );
414 }
415
416 return $data;
417 }
418
419 /**
420 * Fetch a scalar from the input without normalization, or return $default
421 * if it's not set.
422 *
423 * Unlike self::getVal(), this does not perform any normalization on the
424 * input value.
425 *
426 * @since 1.28
427 * @param string $name
428 * @param string|null $default
429 * @return string|null
430 */
431 public function getRawVal( $name, $default = null ) {
432 $name = strtr( $name, '.', '_' ); // See comment in self::getGPCVal()
433 if ( isset( $this->data[$name] ) && !is_array( $this->data[$name] ) ) {
434 $val = $this->data[$name];
435 } else {
436 $val = $default;
437 }
438 if ( is_null( $val ) ) {
439 return $val;
440 } else {
441 return (string)$val;
442 }
443 }
444
445 /**
446 * Fetch a scalar from the input or return $default if it's not set.
447 * Returns a string. Arrays are discarded. Useful for
448 * non-freeform text inputs (e.g. predefined internal text keys
449 * selected by a drop-down menu). For freeform input, see getText().
450 *
451 * @param string $name
452 * @param string|null $default Optional default (or null)
453 * @return string|null
454 */
455 public function getVal( $name, $default = null ) {
456 $val = $this->getGPCVal( $this->data, $name, $default );
457 if ( is_array( $val ) ) {
458 $val = $default;
459 }
460 if ( is_null( $val ) ) {
461 return $val;
462 } else {
463 return (string)$val;
464 }
465 }
466
467 /**
468 * Set an arbitrary value into our get/post data.
469 *
470 * @param string $key Key name to use
471 * @param mixed $value Value to set
472 * @return mixed Old value if one was present, null otherwise
473 */
474 public function setVal( $key, $value ) {
475 $ret = $this->data[$key] ?? null;
476 $this->data[$key] = $value;
477 return $ret;
478 }
479
480 /**
481 * Unset an arbitrary value from our get/post data.
482 *
483 * @param string $key Key name to use
484 * @return mixed Old value if one was present, null otherwise
485 */
486 public function unsetVal( $key ) {
487 if ( !isset( $this->data[$key] ) ) {
488 $ret = null;
489 } else {
490 $ret = $this->data[$key];
491 unset( $this->data[$key] );
492 }
493 return $ret;
494 }
495
496 /**
497 * Fetch an array from the input or return $default if it's not set.
498 * If source was scalar, will return an array with a single element.
499 * If no source and no default, returns null.
500 *
501 * @param string $name
502 * @param array|null $default Optional default (or null)
503 * @return array|null
504 */
505 public function getArray( $name, $default = null ) {
506 $val = $this->getGPCVal( $this->data, $name, $default );
507 if ( is_null( $val ) ) {
508 return null;
509 } else {
510 return (array)$val;
511 }
512 }
513
514 /**
515 * Fetch an array of integers, or return $default if it's not set.
516 * If source was scalar, will return an array with a single element.
517 * If no source and no default, returns null.
518 * If an array is returned, contents are guaranteed to be integers.
519 *
520 * @param string $name
521 * @param array|null $default Option default (or null)
522 * @return array Array of ints
523 */
524 public function getIntArray( $name, $default = null ) {
525 $val = $this->getArray( $name, $default );
526 if ( is_array( $val ) ) {
527 $val = array_map( 'intval', $val );
528 }
529 return $val;
530 }
531
532 /**
533 * Fetch an integer value from the input or return $default if not set.
534 * Guaranteed to return an integer; non-numeric input will typically
535 * return 0.
536 *
537 * @param string $name
538 * @param int $default
539 * @return int
540 */
541 public function getInt( $name, $default = 0 ) {
542 return intval( $this->getRawVal( $name, $default ) );
543 }
544
545 /**
546 * Fetch an integer value from the input or return null if empty.
547 * Guaranteed to return an integer or null; non-numeric input will
548 * typically return null.
549 *
550 * @param string $name
551 * @return int|null
552 */
553 public function getIntOrNull( $name ) {
554 $val = $this->getRawVal( $name );
555 return is_numeric( $val )
556 ? intval( $val )
557 : null;
558 }
559
560 /**
561 * Fetch a floating point value from the input or return $default if not set.
562 * Guaranteed to return a float; non-numeric input will typically
563 * return 0.
564 *
565 * @since 1.23
566 * @param string $name
567 * @param float $default
568 * @return float
569 */
570 public function getFloat( $name, $default = 0.0 ) {
571 return floatval( $this->getRawVal( $name, $default ) );
572 }
573
574 /**
575 * Fetch a boolean value from the input or return $default if not set.
576 * Guaranteed to return true or false, with normal PHP semantics for
577 * boolean interpretation of strings.
578 *
579 * @param string $name
580 * @param bool $default
581 * @return bool
582 */
583 public function getBool( $name, $default = false ) {
584 return (bool)$this->getRawVal( $name, $default );
585 }
586
587 /**
588 * Fetch a boolean value from the input or return $default if not set.
589 * Unlike getBool, the string "false" will result in boolean false, which is
590 * useful when interpreting information sent from JavaScript.
591 *
592 * @param string $name
593 * @param bool $default
594 * @return bool
595 */
596 public function getFuzzyBool( $name, $default = false ) {
597 return $this->getBool( $name, $default )
598 && strcasecmp( $this->getRawVal( $name ), 'false' ) !== 0;
599 }
600
601 /**
602 * Return true if the named value is set in the input, whatever that
603 * value is (even "0"). Return false if the named value is not set.
604 * Example use is checking for the presence of check boxes in forms.
605 *
606 * @param string $name
607 * @return bool
608 */
609 public function getCheck( $name ) {
610 # Checkboxes and buttons are only present when clicked
611 # Presence connotes truth, absence false
612 return $this->getRawVal( $name, null ) !== null;
613 }
614
615 /**
616 * Fetch a text string from the given array or return $default if it's not
617 * set. Carriage returns are stripped from the text. This should generally
618 * be used for form "<textarea>" and "<input>" fields, and for
619 * user-supplied freeform text input.
620 *
621 * @param string $name
622 * @param string $default Optional
623 * @return string
624 */
625 public function getText( $name, $default = '' ) {
626 $val = $this->getVal( $name, $default );
627 return str_replace( "\r\n", "\n", $val );
628 }
629
630 /**
631 * Extracts the given named values into an array.
632 * If no arguments are given, returns all input values.
633 * No transformation is performed on the values.
634 *
635 * @return array
636 */
637 public function getValues() {
638 $names = func_get_args();
639 if ( count( $names ) == 0 ) {
640 $names = array_keys( $this->data );
641 }
642
643 $retVal = [];
644 foreach ( $names as $name ) {
645 $value = $this->getGPCVal( $this->data, $name, null );
646 if ( !is_null( $value ) ) {
647 $retVal[$name] = $value;
648 }
649 }
650 return $retVal;
651 }
652
653 /**
654 * Returns the names of all input values excluding those in $exclude.
655 *
656 * @param array $exclude
657 * @return array
658 */
659 public function getValueNames( $exclude = [] ) {
660 return array_diff( array_keys( $this->getValues() ), $exclude );
661 }
662
663 /**
664 * Get the values passed in the query string.
665 * No transformation is performed on the values.
666 *
667 * @codeCoverageIgnore
668 * @return array
669 */
670 public function getQueryValues() {
671 return $_GET;
672 }
673
674 /**
675 * Get the values passed via POST.
676 * No transformation is performed on the values.
677 *
678 * @since 1.32
679 * @codeCoverageIgnore
680 * @return array
681 */
682 public function getPostValues() {
683 return $_POST;
684 }
685
686 /**
687 * Return the contents of the Query with no decoding. Use when you need to
688 * know exactly what was sent, e.g. for an OAuth signature over the elements.
689 *
690 * @codeCoverageIgnore
691 * @return string
692 */
693 public function getRawQueryString() {
694 return $_SERVER['QUERY_STRING'];
695 }
696
697 /**
698 * Return the contents of the POST with no decoding. Use when you need to
699 * know exactly what was sent, e.g. for an OAuth signature over the elements.
700 *
701 * @return string
702 */
703 public function getRawPostString() {
704 if ( !$this->wasPosted() ) {
705 return '';
706 }
707 return $this->getRawInput();
708 }
709
710 /**
711 * Return the raw request body, with no processing. Cached since some methods
712 * disallow reading the stream more than once. As stated in the php docs, this
713 * does not work with enctype="multipart/form-data".
714 *
715 * @return string
716 */
717 public function getRawInput() {
718 static $input = null;
719 if ( $input === null ) {
720 $input = file_get_contents( 'php://input' );
721 }
722 return $input;
723 }
724
725 /**
726 * Get the HTTP method used for this request.
727 *
728 * @return string
729 */
730 public function getMethod() {
731 return $_SERVER['REQUEST_METHOD'] ?? 'GET';
732 }
733
734 /**
735 * Returns true if the present request was reached by a POST operation,
736 * false otherwise (GET, HEAD, or command-line).
737 *
738 * Note that values retrieved by the object may come from the
739 * GET URL etc even on a POST request.
740 *
741 * @return bool
742 */
743 public function wasPosted() {
744 return $this->getMethod() == 'POST';
745 }
746
747 /**
748 * Return the session for this request
749 *
750 * This might unpersist an existing session if it was invalid.
751 *
752 * @since 1.27
753 * @note For performance, keep the session locally if you will be making
754 * much use of it instead of calling this method repeatedly.
755 * @return Session
756 */
757 public function getSession() {
758 if ( $this->sessionId !== null ) {
759 $session = SessionManager::singleton()->getSessionById( (string)$this->sessionId, true, $this );
760 if ( $session ) {
761 return $session;
762 }
763 }
764
765 $session = SessionManager::singleton()->getSessionForRequest( $this );
766 $this->sessionId = $session->getSessionId();
767 return $session;
768 }
769
770 /**
771 * Set the session for this request
772 * @since 1.27
773 * @private For use by MediaWiki\Session classes only
774 * @param SessionId $sessionId
775 */
776 public function setSessionId( SessionId $sessionId ) {
777 $this->sessionId = $sessionId;
778 }
779
780 /**
781 * Get the session id for this request, if any
782 * @since 1.27
783 * @private For use by MediaWiki\Session classes only
784 * @return SessionId|null
785 */
786 public function getSessionId() {
787 return $this->sessionId;
788 }
789
790 /**
791 * Get a cookie from the $_COOKIE jar
792 *
793 * @param string $key The name of the cookie
794 * @param string|null $prefix A prefix to use for the cookie name, if not $wgCookiePrefix
795 * @param mixed|null $default What to return if the value isn't found
796 * @return mixed Cookie value or $default if the cookie not set
797 */
798 public function getCookie( $key, $prefix = null, $default = null ) {
799 if ( $prefix === null ) {
800 global $wgCookiePrefix;
801 $prefix = $wgCookiePrefix;
802 }
803 return $this->getGPCVal( $_COOKIE, $prefix . $key, $default );
804 }
805
806 /**
807 * Return the path and query string portion of the main request URI.
808 * This will be suitable for use as a relative link in HTML output.
809 *
810 * @throws MWException
811 * @return string
812 */
813 public static function getGlobalRequestURL() {
814 // This method is called on fatal errors; it should not depend on anything complex.
815
816 if ( isset( $_SERVER['REQUEST_URI'] ) && strlen( $_SERVER['REQUEST_URI'] ) ) {
817 $base = $_SERVER['REQUEST_URI'];
818 } elseif ( isset( $_SERVER['HTTP_X_ORIGINAL_URL'] )
819 && strlen( $_SERVER['HTTP_X_ORIGINAL_URL'] )
820 ) {
821 // Probably IIS; doesn't set REQUEST_URI
822 $base = $_SERVER['HTTP_X_ORIGINAL_URL'];
823 } elseif ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
824 $base = $_SERVER['SCRIPT_NAME'];
825 if ( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
826 $base .= '?' . $_SERVER['QUERY_STRING'];
827 }
828 } else {
829 // This shouldn't happen!
830 throw new MWException( "Web server doesn't provide either " .
831 "REQUEST_URI, HTTP_X_ORIGINAL_URL or SCRIPT_NAME. Report details " .
832 "of your web server configuration to https://phabricator.wikimedia.org/" );
833 }
834 // User-agents should not send a fragment with the URI, but
835 // if they do, and the web server passes it on to us, we
836 // need to strip it or we get false-positive redirect loops
837 // or weird output URLs
838 $hash = strpos( $base, '#' );
839 if ( $hash !== false ) {
840 $base = substr( $base, 0, $hash );
841 }
842
843 if ( $base[0] == '/' ) {
844 // More than one slash will look like it is protocol relative
845 return preg_replace( '!^/+!', '/', $base );
846 } else {
847 // We may get paths with a host prepended; strip it.
848 return preg_replace( '!^[^:]+://[^/]+/+!', '/', $base );
849 }
850 }
851
852 /**
853 * Return the path and query string portion of the request URI.
854 * This will be suitable for use as a relative link in HTML output.
855 *
856 * @throws MWException
857 * @return string
858 */
859 public function getRequestURL() {
860 return self::getGlobalRequestURL();
861 }
862
863 /**
864 * Return the request URI with the canonical service and hostname, path,
865 * and query string. This will be suitable for use as an absolute link
866 * in HTML or other output.
867 *
868 * If $wgServer is protocol-relative, this will return a fully
869 * qualified URL with the protocol of this request object.
870 *
871 * @return string
872 */
873 public function getFullRequestURL() {
874 // Pass an explicit PROTO constant instead of PROTO_CURRENT so that we
875 // do not rely on state from the global $wgRequest object (which it would,
876 // via wfGetServerUrl/wfExpandUrl/$wgRequest->protocol).
877 if ( $this->getProtocol() === 'http' ) {
878 return wfGetServerUrl( PROTO_HTTP ) . $this->getRequestURL();
879 } else {
880 return wfGetServerUrl( PROTO_HTTPS ) . $this->getRequestURL();
881 }
882 }
883
884 /**
885 * @param string $key
886 * @param string $value
887 * @return string
888 */
889 public function appendQueryValue( $key, $value ) {
890 return $this->appendQueryArray( [ $key => $value ] );
891 }
892
893 /**
894 * Appends or replaces value of query variables.
895 *
896 * @param array $array Array of values to replace/add to query
897 * @return string
898 */
899 public function appendQueryArray( $array ) {
900 $newquery = $this->getQueryValues();
901 unset( $newquery['title'] );
902 $newquery = array_merge( $newquery, $array );
903
904 return wfArrayToCgi( $newquery );
905 }
906
907 /**
908 * Check for limit and offset parameters on the input, and return sensible
909 * defaults if not given. The limit must be positive and is capped at 5000.
910 * Offset must be positive but is not capped.
911 *
912 * @param int $deflimit Limit to use if no input and the user hasn't set the option.
913 * @param string $optionname To specify an option other than rclimit to pull from.
914 * @return int[] First element is limit, second is offset
915 */
916 public function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
917 global $wgUser;
918
919 $limit = $this->getInt( 'limit', 0 );
920 if ( $limit < 0 ) {
921 $limit = 0;
922 }
923 if ( ( $limit == 0 ) && ( $optionname != '' ) ) {
924 $limit = $wgUser->getIntOption( $optionname );
925 }
926 if ( $limit <= 0 ) {
927 $limit = $deflimit;
928 }
929 if ( $limit > 5000 ) {
930 $limit = 5000; # We have *some* limits...
931 }
932
933 $offset = $this->getInt( 'offset', 0 );
934 if ( $offset < 0 ) {
935 $offset = 0;
936 }
937
938 return [ $limit, $offset ];
939 }
940
941 /**
942 * Return the path to the temporary file where PHP has stored the upload.
943 *
944 * @param string $key
945 * @return string|null String or null if no such file.
946 */
947 public function getFileTempname( $key ) {
948 $file = new WebRequestUpload( $this, $key );
949 return $file->getTempName();
950 }
951
952 /**
953 * Return the upload error or 0
954 *
955 * @param string $key
956 * @return int
957 */
958 public function getUploadError( $key ) {
959 $file = new WebRequestUpload( $this, $key );
960 return $file->getError();
961 }
962
963 /**
964 * Return the original filename of the uploaded file, as reported by
965 * the submitting user agent. HTML-style character entities are
966 * interpreted and normalized to Unicode normalization form C, in part
967 * to deal with weird input from Safari with non-ASCII filenames.
968 *
969 * Other than this the name is not verified for being a safe filename.
970 *
971 * @param string $key
972 * @return string|null String or null if no such file.
973 */
974 public function getFileName( $key ) {
975 $file = new WebRequestUpload( $this, $key );
976 return $file->getName();
977 }
978
979 /**
980 * Return a WebRequestUpload object corresponding to the key
981 *
982 * @param string $key
983 * @return WebRequestUpload
984 */
985 public function getUpload( $key ) {
986 return new WebRequestUpload( $this, $key );
987 }
988
989 /**
990 * Return a handle to WebResponse style object, for setting cookies,
991 * headers and other stuff, for Request being worked on.
992 *
993 * @return WebResponse
994 */
995 public function response() {
996 /* Lazy initialization of response object for this request */
997 if ( !is_object( $this->response ) ) {
998 $class = ( $this instanceof FauxRequest ) ? FauxResponse::class : WebResponse::class;
999 $this->response = new $class();
1000 }
1001 return $this->response;
1002 }
1003
1004 /**
1005 * Initialise the header list
1006 */
1007 protected function initHeaders() {
1008 if ( count( $this->headers ) ) {
1009 return;
1010 }
1011
1012 $apacheHeaders = function_exists( 'apache_request_headers' ) ? apache_request_headers() : false;
1013 if ( $apacheHeaders ) {
1014 foreach ( $apacheHeaders as $tempName => $tempValue ) {
1015 $this->headers[strtoupper( $tempName )] = $tempValue;
1016 }
1017 } else {
1018 foreach ( $_SERVER as $name => $value ) {
1019 if ( substr( $name, 0, 5 ) === 'HTTP_' ) {
1020 $name = str_replace( '_', '-', substr( $name, 5 ) );
1021 $this->headers[$name] = $value;
1022 } elseif ( $name === 'CONTENT_LENGTH' ) {
1023 $this->headers['CONTENT-LENGTH'] = $value;
1024 }
1025 }
1026 }
1027 }
1028
1029 /**
1030 * Get an array containing all request headers
1031 *
1032 * @return array Mapping header name to its value
1033 */
1034 public function getAllHeaders() {
1035 $this->initHeaders();
1036 return $this->headers;
1037 }
1038
1039 /**
1040 * Get a request header, or false if it isn't set.
1041 *
1042 * @param string $name Case-insensitive header name
1043 * @param int $flags Bitwise combination of:
1044 * WebRequest::GETHEADER_LIST Treat the header as a comma-separated list
1045 * of values, as described in RFC 2616 § 4.2.
1046 * (since 1.26).
1047 * @return string|array|bool False if header is unset; otherwise the
1048 * header value(s) as either a string (the default) or an array, if
1049 * WebRequest::GETHEADER_LIST flag was set.
1050 */
1051 public function getHeader( $name, $flags = 0 ) {
1052 $this->initHeaders();
1053 $name = strtoupper( $name );
1054 if ( !isset( $this->headers[$name] ) ) {
1055 return false;
1056 }
1057 $value = $this->headers[$name];
1058 if ( $flags & self::GETHEADER_LIST ) {
1059 $value = array_map( 'trim', explode( ',', $value ) );
1060 }
1061 return $value;
1062 }
1063
1064 /**
1065 * Get data from the session
1066 *
1067 * @note Prefer $this->getSession() instead if making multiple calls.
1068 * @param string $key Name of key in the session
1069 * @return mixed
1070 */
1071 public function getSessionData( $key ) {
1072 return $this->getSession()->get( $key );
1073 }
1074
1075 /**
1076 * Set session data
1077 *
1078 * @note Prefer $this->getSession() instead if making multiple calls.
1079 * @param string $key Name of key in the session
1080 * @param mixed $data
1081 */
1082 public function setSessionData( $key, $data ) {
1083 $this->getSession()->set( $key, $data );
1084 }
1085
1086 /**
1087 * Check if Internet Explorer will detect an incorrect cache extension in
1088 * PATH_INFO or QUERY_STRING. If the request can't be allowed, show an error
1089 * message or redirect to a safer URL. Returns true if the URL is OK, and
1090 * false if an error message has been shown and the request should be aborted.
1091 *
1092 * @param array $extWhitelist
1093 * @throws HttpError
1094 * @return bool
1095 */
1096 public function checkUrlExtension( $extWhitelist = [] ) {
1097 $extWhitelist[] = 'php';
1098 if ( IEUrlExtension::areServerVarsBad( $_SERVER, $extWhitelist ) ) {
1099 if ( !$this->wasPosted() ) {
1100 $newUrl = IEUrlExtension::fixUrlForIE6(
1101 $this->getFullRequestURL(), $extWhitelist );
1102 if ( $newUrl !== false ) {
1103 $this->doSecurityRedirect( $newUrl );
1104 return false;
1105 }
1106 }
1107 throw new HttpError( 403,
1108 'Invalid file extension found in the path info or query string.' );
1109 }
1110 return true;
1111 }
1112
1113 /**
1114 * Attempt to redirect to a URL with a QUERY_STRING that's not dangerous in
1115 * IE 6. Returns true if it was successful, false otherwise.
1116 *
1117 * @param string $url
1118 * @return bool
1119 */
1120 protected function doSecurityRedirect( $url ) {
1121 header( 'Location: ' . $url );
1122 header( 'Content-Type: text/html' );
1123 $encUrl = htmlspecialchars( $url );
1124 echo <<<HTML
1125 <!DOCTYPE html>
1126 <html>
1127 <head>
1128 <title>Security redirect</title>
1129 </head>
1130 <body>
1131 <h1>Security redirect</h1>
1132 <p>
1133 We can't serve non-HTML content from the URL you have requested, because
1134 Internet Explorer would interpret it as an incorrect and potentially dangerous
1135 content type.</p>
1136 <p>Instead, please use <a href="$encUrl">this URL</a>, which is the same as the
1137 URL you have requested, except that "&amp;*" is appended. This prevents Internet
1138 Explorer from seeing a bogus file extension.
1139 </p>
1140 </body>
1141 </html>
1142 HTML;
1143 echo "\n";
1144 return true;
1145 }
1146
1147 /**
1148 * Parse the Accept-Language header sent by the client into an array
1149 *
1150 * @return array [ languageCode => q-value ] sorted by q-value in
1151 * descending order then appearing time in the header in ascending order.
1152 * May contain the "language" '*', which applies to languages other than those explicitly listed.
1153 * This is aligned with rfc2616 section 14.4
1154 * Preference for earlier languages appears in rfc3282 as an extension to HTTP/1.1.
1155 */
1156 public function getAcceptLang() {
1157 // Modified version of code found at
1158 // http://www.thefutureoftheweb.com/blog/use-accept-language-header
1159 $acceptLang = $this->getHeader( 'Accept-Language' );
1160 if ( !$acceptLang ) {
1161 return [];
1162 }
1163
1164 // Return the language codes in lower case
1165 $acceptLang = strtolower( $acceptLang );
1166
1167 // Break up string into pieces (languages and q factors)
1168 $lang_parse = null;
1169 preg_match_all(
1170 '/([a-z]{1,8}(-[a-z]{1,8})*|\*)\s*(;\s*q\s*=\s*(1(\.0{0,3})?|0(\.[0-9]{0,3})?)?)?/',
1171 $acceptLang,
1172 $lang_parse
1173 );
1174
1175 if ( !count( $lang_parse[1] ) ) {
1176 return [];
1177 }
1178
1179 $langcodes = $lang_parse[1];
1180 $qvalues = $lang_parse[4];
1181 $indices = range( 0, count( $lang_parse[1] ) - 1 );
1182
1183 // Set default q factor to 1
1184 foreach ( $indices as $index ) {
1185 if ( $qvalues[$index] === '' ) {
1186 $qvalues[$index] = 1;
1187 } elseif ( $qvalues[$index] == 0 ) {
1188 unset( $langcodes[$index], $qvalues[$index], $indices[$index] );
1189 }
1190 }
1191
1192 // Sort list. First by $qvalues, then by order. Reorder $langcodes the same way
1193 array_multisort( $qvalues, SORT_DESC, SORT_NUMERIC, $indices, $langcodes );
1194
1195 // Create a list like "en" => 0.8
1196 $langs = array_combine( $langcodes, $qvalues );
1197
1198 return $langs;
1199 }
1200
1201 /**
1202 * Fetch the raw IP from the request
1203 *
1204 * @since 1.19
1205 *
1206 * @throws MWException
1207 * @return string
1208 */
1209 protected function getRawIP() {
1210 if ( !isset( $_SERVER['REMOTE_ADDR'] ) ) {
1211 return null;
1212 }
1213
1214 if ( is_array( $_SERVER['REMOTE_ADDR'] ) || strpos( $_SERVER['REMOTE_ADDR'], ',' ) !== false ) {
1215 throw new MWException( __METHOD__
1216 . " : Could not determine the remote IP address due to multiple values." );
1217 } else {
1218 $ipchain = $_SERVER['REMOTE_ADDR'];
1219 }
1220
1221 return IP::canonicalize( $ipchain );
1222 }
1223
1224 /**
1225 * Work out the IP address based on various globals
1226 * For trusted proxies, use the XFF client IP (first of the chain)
1227 *
1228 * @since 1.19
1229 *
1230 * @throws MWException
1231 * @return string
1232 */
1233 public function getIP() {
1234 global $wgUsePrivateIPs;
1235
1236 # Return cached result
1237 if ( $this->ip !== null ) {
1238 return $this->ip;
1239 }
1240
1241 # collect the originating ips
1242 $ip = $this->getRawIP();
1243 if ( !$ip ) {
1244 throw new MWException( 'Unable to determine IP.' );
1245 }
1246
1247 # Append XFF
1248 $forwardedFor = $this->getHeader( 'X-Forwarded-For' );
1249 if ( $forwardedFor !== false ) {
1250 $proxyLookup = MediaWikiServices::getInstance()->getProxyLookup();
1251 $isConfigured = $proxyLookup->isConfiguredProxy( $ip );
1252 $ipchain = array_map( 'trim', explode( ',', $forwardedFor ) );
1253 $ipchain = array_reverse( $ipchain );
1254 array_unshift( $ipchain, $ip );
1255
1256 # Step through XFF list and find the last address in the list which is a
1257 # trusted server. Set $ip to the IP address given by that trusted server,
1258 # unless the address is not sensible (e.g. private). However, prefer private
1259 # IP addresses over proxy servers controlled by this site (more sensible).
1260 # Note that some XFF values might be "unknown" with Squid/Varnish.
1261 foreach ( $ipchain as $i => $curIP ) {
1262 $curIP = IP::sanitizeIP( IP::canonicalize( $curIP ) );
1263 if ( !$curIP || !isset( $ipchain[$i + 1] ) || $ipchain[$i + 1] === 'unknown'
1264 || !$proxyLookup->isTrustedProxy( $curIP )
1265 ) {
1266 break; // IP is not valid/trusted or does not point to anything
1267 }
1268 if (
1269 IP::isPublic( $ipchain[$i + 1] ) ||
1270 $wgUsePrivateIPs ||
1271 $proxyLookup->isConfiguredProxy( $curIP ) // T50919; treat IP as sane
1272 ) {
1273 // Follow the next IP according to the proxy
1274 $nextIP = IP::canonicalize( $ipchain[$i + 1] );
1275 if ( !$nextIP && $isConfigured ) {
1276 // We have not yet made it past CDN/proxy servers of this site,
1277 // so either they are misconfigured or there is some IP spoofing.
1278 throw new MWException( "Invalid IP given in XFF '$forwardedFor'." );
1279 }
1280 $ip = $nextIP;
1281 // keep traversing the chain
1282 continue;
1283 }
1284 break;
1285 }
1286 }
1287
1288 # Allow extensions to improve our guess
1289 Hooks::run( 'GetIP', [ &$ip ] );
1290
1291 if ( !$ip ) {
1292 throw new MWException( "Unable to determine IP." );
1293 }
1294
1295 wfDebug( "IP: $ip\n" );
1296 $this->ip = $ip;
1297 return $ip;
1298 }
1299
1300 /**
1301 * @param string $ip
1302 * @return void
1303 * @since 1.21
1304 */
1305 public function setIP( $ip ) {
1306 $this->ip = $ip;
1307 }
1308
1309 /**
1310 * Check if this request uses a "safe" HTTP method
1311 *
1312 * Safe methods are verbs (e.g. GET/HEAD/OPTIONS) used for obtaining content. Such requests
1313 * are not expected to mutate content, especially in ways attributable to the client. Verbs
1314 * like POST and PUT are typical of non-safe requests which often change content.
1315 *
1316 * @return bool
1317 * @see https://tools.ietf.org/html/rfc7231#section-4.2.1
1318 * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
1319 * @since 1.28
1320 */
1321 public function hasSafeMethod() {
1322 if ( !isset( $_SERVER['REQUEST_METHOD'] ) ) {
1323 return false; // CLI mode
1324 }
1325
1326 return in_array( $_SERVER['REQUEST_METHOD'], [ 'GET', 'HEAD', 'OPTIONS', 'TRACE' ] );
1327 }
1328
1329 /**
1330 * Whether this request should be identified as being "safe"
1331 *
1332 * This means that the client is not requesting any state changes and that database writes
1333 * are not inherently required. Ideally, no visible updates would happen at all. If they
1334 * must, then they should not be publicly attributed to the end user.
1335 *
1336 * In more detail:
1337 * - Cache populations and refreshes MAY occur.
1338 * - Private user session updates and private server logging MAY occur.
1339 * - Updates to private viewing activity data MAY occur via DeferredUpdates.
1340 * - Other updates SHOULD NOT occur (e.g. modifying content assets).
1341 *
1342 * @return bool
1343 * @see https://tools.ietf.org/html/rfc7231#section-4.2.1
1344 * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
1345 * @since 1.28
1346 */
1347 public function isSafeRequest() {
1348 if ( $this->markedAsSafe && $this->wasPosted() ) {
1349 return true; // marked as a "safe" POST
1350 }
1351
1352 return $this->hasSafeMethod();
1353 }
1354
1355 /**
1356 * Mark this request as identified as being nullipotent even if it is a POST request
1357 *
1358 * POST requests are often used due to the need for a client payload, even if the request
1359 * is otherwise equivalent to a "safe method" request.
1360 *
1361 * @see https://tools.ietf.org/html/rfc7231#section-4.2.1
1362 * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
1363 * @since 1.28
1364 */
1365 public function markAsSafeRequest() {
1366 $this->markedAsSafe = true;
1367 }
1368 }