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