Merge "Remove .mw-help-field-hint and -data CSS classes from mw.legacy/shared"
[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\Session\Session;
27 use MediaWiki\Session\SessionId;
28 use MediaWiki\Session\SessionManager;
29
30 /**
31 * The WebRequest class encapsulates getting at data passed in the
32 * URL or via a POSTed form stripping illegal input characters and
33 * normalizing Unicode sequences.
34 *
35 * @ingroup HTTP
36 */
37 class WebRequest {
38 protected $data, $headers = [];
39
40 /**
41 * Flag to make WebRequest::getHeader return an array of values.
42 * @since 1.26
43 */
44 const GETHEADER_LIST = 1;
45
46 /**
47 * The unique request ID.
48 * @var string
49 */
50 private static $reqId;
51
52 /**
53 * Lazy-init response object
54 * @var WebResponse
55 */
56 private $response;
57
58 /**
59 * Cached client IP address
60 * @var string
61 */
62 private $ip;
63
64 /**
65 * The timestamp of the start of the request, with microsecond precision.
66 * @var float
67 */
68 protected $requestTime;
69
70 /**
71 * Cached URL protocol
72 * @var string
73 */
74 protected $protocol;
75
76 /**
77 * @var SessionId|null Session ID to use for this
78 * request. We can't save the session directly due to reference cycles not
79 * working too well (slow GC in Zend and never collected in HHVM).
80 */
81 protected $sessionId = null;
82
83 /** @var bool Whether this HTTP request is "safe" (even if it is an HTTP post) */
84 protected $markedAsSafe = false;
85
86 /**
87 * @codeCoverageIgnore
88 */
89 public function __construct() {
90 $this->requestTime = isset( $_SERVER['REQUEST_TIME_FLOAT'] )
91 ? $_SERVER['REQUEST_TIME_FLOAT'] : microtime( true );
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 http://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 MediaWiki\suppressWarnings();
126 $a = parse_url( $url );
127 MediaWiki\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 // http://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 // Bug 70021: 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 array
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 // bug 16019: 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 # http://us2.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 Optional default
410 * @return string
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
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
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 * Returns true if the request has a persistent session.
761 * This does not necessarily mean that the user is logged in!
762 *
763 * @deprecated since 1.27, use
764 * \MediaWiki\Session\SessionManager::singleton()->getPersistedSessionId()
765 * instead.
766 * @return bool
767 */
768 public function checkSessionCookie() {
769 global $wgInitialSessionId;
770 wfDeprecated( __METHOD__, '1.27' );
771 return $wgInitialSessionId !== null &&
772 $this->getSession()->getId() === (string)$wgInitialSessionId;
773 }
774
775 /**
776 * Get a cookie from the $_COOKIE jar
777 *
778 * @param string $key The name of the cookie
779 * @param string $prefix A prefix to use for the cookie name, if not $wgCookiePrefix
780 * @param mixed $default What to return if the value isn't found
781 * @return mixed Cookie value or $default if the cookie not set
782 */
783 public function getCookie( $key, $prefix = null, $default = null ) {
784 if ( $prefix === null ) {
785 global $wgCookiePrefix;
786 $prefix = $wgCookiePrefix;
787 }
788 return $this->getGPCVal( $_COOKIE, $prefix . $key, $default );
789 }
790
791 /**
792 * Return the path and query string portion of the main request URI.
793 * This will be suitable for use as a relative link in HTML output.
794 *
795 * @throws MWException
796 * @return string
797 */
798 public static function getGlobalRequestURL() {
799 if ( isset( $_SERVER['REQUEST_URI'] ) && strlen( $_SERVER['REQUEST_URI'] ) ) {
800 $base = $_SERVER['REQUEST_URI'];
801 } elseif ( isset( $_SERVER['HTTP_X_ORIGINAL_URL'] )
802 && strlen( $_SERVER['HTTP_X_ORIGINAL_URL'] )
803 ) {
804 // Probably IIS; doesn't set REQUEST_URI
805 $base = $_SERVER['HTTP_X_ORIGINAL_URL'];
806 } elseif ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
807 $base = $_SERVER['SCRIPT_NAME'];
808 if ( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
809 $base .= '?' . $_SERVER['QUERY_STRING'];
810 }
811 } else {
812 // This shouldn't happen!
813 throw new MWException( "Web server doesn't provide either " .
814 "REQUEST_URI, HTTP_X_ORIGINAL_URL or SCRIPT_NAME. Report details " .
815 "of your web server configuration to https://phabricator.wikimedia.org/" );
816 }
817 // User-agents should not send a fragment with the URI, but
818 // if they do, and the web server passes it on to us, we
819 // need to strip it or we get false-positive redirect loops
820 // or weird output URLs
821 $hash = strpos( $base, '#' );
822 if ( $hash !== false ) {
823 $base = substr( $base, 0, $hash );
824 }
825
826 if ( $base[0] == '/' ) {
827 // More than one slash will look like it is protocol relative
828 return preg_replace( '!^/+!', '/', $base );
829 } else {
830 // We may get paths with a host prepended; strip it.
831 return preg_replace( '!^[^:]+://[^/]+/+!', '/', $base );
832 }
833 }
834
835 /**
836 * Return the path and query string portion of the request URI.
837 * This will be suitable for use as a relative link in HTML output.
838 *
839 * @throws MWException
840 * @return string
841 */
842 public function getRequestURL() {
843 return self::getGlobalRequestURL();
844 }
845
846 /**
847 * Return the request URI with the canonical service and hostname, path,
848 * and query string. This will be suitable for use as an absolute link
849 * in HTML or other output.
850 *
851 * If $wgServer is protocol-relative, this will return a fully
852 * qualified URL with the protocol that was used for this request.
853 *
854 * @return string
855 */
856 public function getFullRequestURL() {
857 return wfExpandUrl( $this->getRequestURL(), PROTO_CURRENT );
858 }
859
860 /**
861 * @param string $key
862 * @param string $value
863 * @return string
864 */
865 public function appendQueryValue( $key, $value ) {
866 return $this->appendQueryArray( [ $key => $value ] );
867 }
868
869 /**
870 * Appends or replaces value of query variables.
871 *
872 * @param array $array Array of values to replace/add to query
873 * @return string
874 */
875 public function appendQueryArray( $array ) {
876 $newquery = $this->getQueryValues();
877 unset( $newquery['title'] );
878 $newquery = array_merge( $newquery, $array );
879
880 return wfArrayToCgi( $newquery );
881 }
882
883 /**
884 * Check for limit and offset parameters on the input, and return sensible
885 * defaults if not given. The limit must be positive and is capped at 5000.
886 * Offset must be positive but is not capped.
887 *
888 * @param int $deflimit Limit to use if no input and the user hasn't set the option.
889 * @param string $optionname To specify an option other than rclimit to pull from.
890 * @return int[] First element is limit, second is offset
891 */
892 public function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
893 global $wgUser;
894
895 $limit = $this->getInt( 'limit', 0 );
896 if ( $limit < 0 ) {
897 $limit = 0;
898 }
899 if ( ( $limit == 0 ) && ( $optionname != '' ) ) {
900 $limit = $wgUser->getIntOption( $optionname );
901 }
902 if ( $limit <= 0 ) {
903 $limit = $deflimit;
904 }
905 if ( $limit > 5000 ) {
906 $limit = 5000; # We have *some* limits...
907 }
908
909 $offset = $this->getInt( 'offset', 0 );
910 if ( $offset < 0 ) {
911 $offset = 0;
912 }
913
914 return [ $limit, $offset ];
915 }
916
917 /**
918 * Return the path to the temporary file where PHP has stored the upload.
919 *
920 * @param string $key
921 * @return string|null String or null if no such file.
922 */
923 public function getFileTempname( $key ) {
924 $file = new WebRequestUpload( $this, $key );
925 return $file->getTempName();
926 }
927
928 /**
929 * Return the upload error or 0
930 *
931 * @param string $key
932 * @return int
933 */
934 public function getUploadError( $key ) {
935 $file = new WebRequestUpload( $this, $key );
936 return $file->getError();
937 }
938
939 /**
940 * Return the original filename of the uploaded file, as reported by
941 * the submitting user agent. HTML-style character entities are
942 * interpreted and normalized to Unicode normalization form C, in part
943 * to deal with weird input from Safari with non-ASCII filenames.
944 *
945 * Other than this the name is not verified for being a safe filename.
946 *
947 * @param string $key
948 * @return string|null String or null if no such file.
949 */
950 public function getFileName( $key ) {
951 $file = new WebRequestUpload( $this, $key );
952 return $file->getName();
953 }
954
955 /**
956 * Return a WebRequestUpload object corresponding to the key
957 *
958 * @param string $key
959 * @return WebRequestUpload
960 */
961 public function getUpload( $key ) {
962 return new WebRequestUpload( $this, $key );
963 }
964
965 /**
966 * Return a handle to WebResponse style object, for setting cookies,
967 * headers and other stuff, for Request being worked on.
968 *
969 * @return WebResponse
970 */
971 public function response() {
972 /* Lazy initialization of response object for this request */
973 if ( !is_object( $this->response ) ) {
974 $class = ( $this instanceof FauxRequest ) ? 'FauxResponse' : 'WebResponse';
975 $this->response = new $class();
976 }
977 return $this->response;
978 }
979
980 /**
981 * Initialise the header list
982 */
983 protected function initHeaders() {
984 if ( count( $this->headers ) ) {
985 return;
986 }
987
988 $apacheHeaders = function_exists( 'apache_request_headers' ) ? apache_request_headers() : false;
989 if ( $apacheHeaders ) {
990 foreach ( $apacheHeaders as $tempName => $tempValue ) {
991 $this->headers[strtoupper( $tempName )] = $tempValue;
992 }
993 } else {
994 foreach ( $_SERVER as $name => $value ) {
995 if ( substr( $name, 0, 5 ) === 'HTTP_' ) {
996 $name = str_replace( '_', '-', substr( $name, 5 ) );
997 $this->headers[$name] = $value;
998 } elseif ( $name === 'CONTENT_LENGTH' ) {
999 $this->headers['CONTENT-LENGTH'] = $value;
1000 }
1001 }
1002 }
1003 }
1004
1005 /**
1006 * Get an array containing all request headers
1007 *
1008 * @return array Mapping header name to its value
1009 */
1010 public function getAllHeaders() {
1011 $this->initHeaders();
1012 return $this->headers;
1013 }
1014
1015 /**
1016 * Get a request header, or false if it isn't set.
1017 *
1018 * @param string $name Case-insensitive header name
1019 * @param int $flags Bitwise combination of:
1020 * WebRequest::GETHEADER_LIST Treat the header as a comma-separated list
1021 * of values, as described in RFC 2616 § 4.2.
1022 * (since 1.26).
1023 * @return string|array|bool False if header is unset; otherwise the
1024 * header value(s) as either a string (the default) or an array, if
1025 * WebRequest::GETHEADER_LIST flag was set.
1026 */
1027 public function getHeader( $name, $flags = 0 ) {
1028 $this->initHeaders();
1029 $name = strtoupper( $name );
1030 if ( !isset( $this->headers[$name] ) ) {
1031 return false;
1032 }
1033 $value = $this->headers[$name];
1034 if ( $flags & self::GETHEADER_LIST ) {
1035 $value = array_map( 'trim', explode( ',', $value ) );
1036 }
1037 return $value;
1038 }
1039
1040 /**
1041 * Get data from the session
1042 *
1043 * @note Prefer $this->getSession() instead if making multiple calls.
1044 * @param string $key Name of key in the session
1045 * @return mixed
1046 */
1047 public function getSessionData( $key ) {
1048 return $this->getSession()->get( $key );
1049 }
1050
1051 /**
1052 * Set session data
1053 *
1054 * @note Prefer $this->getSession() instead if making multiple calls.
1055 * @param string $key Name of key in the session
1056 * @param mixed $data
1057 */
1058 public function setSessionData( $key, $data ) {
1059 $this->getSession()->set( $key, $data );
1060 }
1061
1062 /**
1063 * Check if Internet Explorer will detect an incorrect cache extension in
1064 * PATH_INFO or QUERY_STRING. If the request can't be allowed, show an error
1065 * message or redirect to a safer URL. Returns true if the URL is OK, and
1066 * false if an error message has been shown and the request should be aborted.
1067 *
1068 * @param array $extWhitelist
1069 * @throws HttpError
1070 * @return bool
1071 */
1072 public function checkUrlExtension( $extWhitelist = [] ) {
1073 $extWhitelist[] = 'php';
1074 if ( IEUrlExtension::areServerVarsBad( $_SERVER, $extWhitelist ) ) {
1075 if ( !$this->wasPosted() ) {
1076 $newUrl = IEUrlExtension::fixUrlForIE6(
1077 $this->getFullRequestURL(), $extWhitelist );
1078 if ( $newUrl !== false ) {
1079 $this->doSecurityRedirect( $newUrl );
1080 return false;
1081 }
1082 }
1083 throw new HttpError( 403,
1084 'Invalid file extension found in the path info or query string.' );
1085 }
1086 return true;
1087 }
1088
1089 /**
1090 * Attempt to redirect to a URL with a QUERY_STRING that's not dangerous in
1091 * IE 6. Returns true if it was successful, false otherwise.
1092 *
1093 * @param string $url
1094 * @return bool
1095 */
1096 protected function doSecurityRedirect( $url ) {
1097 header( 'Location: ' . $url );
1098 header( 'Content-Type: text/html' );
1099 $encUrl = htmlspecialchars( $url );
1100 echo <<<HTML
1101 <html>
1102 <head>
1103 <title>Security redirect</title>
1104 </head>
1105 <body>
1106 <h1>Security redirect</h1>
1107 <p>
1108 We can't serve non-HTML content from the URL you have requested, because
1109 Internet Explorer would interpret it as an incorrect and potentially dangerous
1110 content type.</p>
1111 <p>Instead, please use <a href="$encUrl">this URL</a>, which is the same as the
1112 URL you have requested, except that "&amp;*" is appended. This prevents Internet
1113 Explorer from seeing a bogus file extension.
1114 </p>
1115 </body>
1116 </html>
1117 HTML;
1118 echo "\n";
1119 return true;
1120 }
1121
1122 /**
1123 * Parse the Accept-Language header sent by the client into an array
1124 *
1125 * @return array Array( languageCode => q-value ) sorted by q-value in
1126 * descending order then appearing time in the header in ascending order.
1127 * May contain the "language" '*', which applies to languages other than those explicitly listed.
1128 * This is aligned with rfc2616 section 14.4
1129 * Preference for earlier languages appears in rfc3282 as an extension to HTTP/1.1.
1130 */
1131 public function getAcceptLang() {
1132 // Modified version of code found at
1133 // http://www.thefutureoftheweb.com/blog/use-accept-language-header
1134 $acceptLang = $this->getHeader( 'Accept-Language' );
1135 if ( !$acceptLang ) {
1136 return [];
1137 }
1138
1139 // Return the language codes in lower case
1140 $acceptLang = strtolower( $acceptLang );
1141
1142 // Break up string into pieces (languages and q factors)
1143 $lang_parse = null;
1144 preg_match_all(
1145 '/([a-z]{1,8}(-[a-z]{1,8})*|\*)\s*(;\s*q\s*=\s*(1(\.0{0,3})?|0(\.[0-9]{0,3})?)?)?/',
1146 $acceptLang,
1147 $lang_parse
1148 );
1149
1150 if ( !count( $lang_parse[1] ) ) {
1151 return [];
1152 }
1153
1154 $langcodes = $lang_parse[1];
1155 $qvalues = $lang_parse[4];
1156 $indices = range( 0, count( $lang_parse[1] ) - 1 );
1157
1158 // Set default q factor to 1
1159 foreach ( $indices as $index ) {
1160 if ( $qvalues[$index] === '' ) {
1161 $qvalues[$index] = 1;
1162 } elseif ( $qvalues[$index] == 0 ) {
1163 unset( $langcodes[$index], $qvalues[$index], $indices[$index] );
1164 }
1165 }
1166
1167 // Sort list. First by $qvalues, then by order. Reorder $langcodes the same way
1168 array_multisort( $qvalues, SORT_DESC, SORT_NUMERIC, $indices, $langcodes );
1169
1170 // Create a list like "en" => 0.8
1171 $langs = array_combine( $langcodes, $qvalues );
1172
1173 return $langs;
1174 }
1175
1176 /**
1177 * Fetch the raw IP from the request
1178 *
1179 * @since 1.19
1180 *
1181 * @throws MWException
1182 * @return string
1183 */
1184 protected function getRawIP() {
1185 if ( !isset( $_SERVER['REMOTE_ADDR'] ) ) {
1186 return null;
1187 }
1188
1189 if ( is_array( $_SERVER['REMOTE_ADDR'] ) || strpos( $_SERVER['REMOTE_ADDR'], ',' ) !== false ) {
1190 throw new MWException( __METHOD__
1191 . " : Could not determine the remote IP address due to multiple values." );
1192 } else {
1193 $ipchain = $_SERVER['REMOTE_ADDR'];
1194 }
1195
1196 return IP::canonicalize( $ipchain );
1197 }
1198
1199 /**
1200 * Work out the IP address based on various globals
1201 * For trusted proxies, use the XFF client IP (first of the chain)
1202 *
1203 * @since 1.19
1204 *
1205 * @throws MWException
1206 * @return string
1207 */
1208 public function getIP() {
1209 global $wgUsePrivateIPs;
1210
1211 # Return cached result
1212 if ( $this->ip !== null ) {
1213 return $this->ip;
1214 }
1215
1216 # collect the originating ips
1217 $ip = $this->getRawIP();
1218 if ( !$ip ) {
1219 throw new MWException( 'Unable to determine IP.' );
1220 }
1221
1222 # Append XFF
1223 $forwardedFor = $this->getHeader( 'X-Forwarded-For' );
1224 if ( $forwardedFor !== false ) {
1225 $isConfigured = IP::isConfiguredProxy( $ip );
1226 $ipchain = array_map( 'trim', explode( ',', $forwardedFor ) );
1227 $ipchain = array_reverse( $ipchain );
1228 array_unshift( $ipchain, $ip );
1229
1230 # Step through XFF list and find the last address in the list which is a
1231 # trusted server. Set $ip to the IP address given by that trusted server,
1232 # unless the address is not sensible (e.g. private). However, prefer private
1233 # IP addresses over proxy servers controlled by this site (more sensible).
1234 # Note that some XFF values might be "unknown" with Squid/Varnish.
1235 foreach ( $ipchain as $i => $curIP ) {
1236 $curIP = IP::sanitizeIP( IP::canonicalize( $curIP ) );
1237 if ( !$curIP || !isset( $ipchain[$i + 1] ) || $ipchain[$i + 1] === 'unknown'
1238 || !IP::isTrustedProxy( $curIP )
1239 ) {
1240 break; // IP is not valid/trusted or does not point to anything
1241 }
1242 if (
1243 IP::isPublic( $ipchain[$i + 1] ) ||
1244 $wgUsePrivateIPs ||
1245 IP::isConfiguredProxy( $curIP ) // bug 48919; treat IP as sane
1246 ) {
1247 // Follow the next IP according to the proxy
1248 $nextIP = IP::canonicalize( $ipchain[$i + 1] );
1249 if ( !$nextIP && $isConfigured ) {
1250 // We have not yet made it past CDN/proxy servers of this site,
1251 // so either they are misconfigured or there is some IP spoofing.
1252 throw new MWException( "Invalid IP given in XFF '$forwardedFor'." );
1253 }
1254 $ip = $nextIP;
1255 // keep traversing the chain
1256 continue;
1257 }
1258 break;
1259 }
1260 }
1261
1262 # Allow extensions to improve our guess
1263 Hooks::run( 'GetIP', [ &$ip ] );
1264
1265 if ( !$ip ) {
1266 throw new MWException( "Unable to determine IP." );
1267 }
1268
1269 wfDebug( "IP: $ip\n" );
1270 $this->ip = $ip;
1271 return $ip;
1272 }
1273
1274 /**
1275 * @param string $ip
1276 * @return void
1277 * @since 1.21
1278 */
1279 public function setIP( $ip ) {
1280 $this->ip = $ip;
1281 }
1282
1283 /**
1284 * Check if this request uses a "safe" HTTP method
1285 *
1286 * Safe methods are verbs (e.g. GET/HEAD/OPTIONS) used for obtaining content. Such requests
1287 * are not expected to mutate content, especially in ways attributable to the client. Verbs
1288 * like POST and PUT are typical of non-safe requests which often change content.
1289 *
1290 * @return bool
1291 * @see https://tools.ietf.org/html/rfc7231#section-4.2.1
1292 * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
1293 * @since 1.28
1294 */
1295 public function hasSafeMethod() {
1296 if ( !isset( $_SERVER['REQUEST_METHOD'] ) ) {
1297 return false; // CLI mode
1298 }
1299
1300 return in_array( $_SERVER['REQUEST_METHOD'], [ 'GET', 'HEAD', 'OPTIONS', 'TRACE' ] );
1301 }
1302
1303 /**
1304 * Whether this request should be identified as being "safe"
1305 *
1306 * This means that the client is not requesting any state changes and that database writes
1307 * are not inherently required. Ideally, no visible updates would happen at all. If they
1308 * must, then they should not be publically attributed to the end user.
1309 *
1310 * In more detail:
1311 * - Cache populations and refreshes MAY occur.
1312 * - Private user session updates and private server logging MAY occur.
1313 * - Updates to private viewing activity data MAY occur via DeferredUpdates.
1314 * - Other updates SHOULD NOT occur (e.g. modifying content assets).
1315 *
1316 * @return bool
1317 * @see https://tools.ietf.org/html/rfc7231#section-4.2.1
1318 * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
1319 * @since 1.28
1320 */
1321 public function isSafeRequest() {
1322 if ( $this->markedAsSafe && $this->wasPosted() ) {
1323 return true; // marked as a "safe" POST
1324 }
1325
1326 return $this->hasSafeMethod();
1327 }
1328
1329 /**
1330 * Mark this request as identified as being nullipotent even if it is a POST request
1331 *
1332 * POST requests are often used due to the need for a client payload, even if the request
1333 * is otherwise equivalent to a "safe method" request.
1334 *
1335 * @see https://tools.ietf.org/html/rfc7231#section-4.2.1
1336 * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
1337 * @since 1.28
1338 */
1339 public function markAsSafeRequest() {
1340 $this->markedAsSafe = true;
1341 }
1342 }