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