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