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