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