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