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