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