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