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