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