Merge "Display an error message when the validataion of a radio input fails because...
[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->getVal( $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->getVal( $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->getVal( $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->getVal( $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 ) && strcasecmp( $this->getVal( $name ), 'false' ) !== 0;
579 }
580
581 /**
582 * Return true if the named value is set in the input, whatever that
583 * value is (even "0"). Return false if the named value is not set.
584 * Example use is checking for the presence of check boxes in forms.
585 *
586 * @param string $name
587 * @return bool
588 */
589 public function getCheck( $name ) {
590 # Checkboxes and buttons are only present when clicked
591 # Presence connotes truth, absence false
592 return $this->getVal( $name, null ) !== null;
593 }
594
595 /**
596 * Fetch a text string from the given array or return $default if it's not
597 * set. Carriage returns are stripped from the text. This should generally
598 * be used for form "<textarea>" and "<input>" fields, and for
599 * user-supplied freeform text input.
600 *
601 * @param string $name
602 * @param string $default Optional
603 * @return string
604 */
605 public function getText( $name, $default = '' ) {
606 $val = $this->getVal( $name, $default );
607 return str_replace( "\r\n", "\n", $val );
608 }
609
610 /**
611 * Extracts the given named values into an array.
612 * If no arguments are given, returns all input values.
613 * No transformation is performed on the values.
614 *
615 * @return array
616 */
617 public function getValues() {
618 $names = func_get_args();
619 if ( count( $names ) == 0 ) {
620 $names = array_keys( $this->data );
621 }
622
623 $retVal = [];
624 foreach ( $names as $name ) {
625 $value = $this->getGPCVal( $this->data, $name, null );
626 if ( !is_null( $value ) ) {
627 $retVal[$name] = $value;
628 }
629 }
630 return $retVal;
631 }
632
633 /**
634 * Returns the names of all input values excluding those in $exclude.
635 *
636 * @param array $exclude
637 * @return array
638 */
639 public function getValueNames( $exclude = [] ) {
640 return array_diff( array_keys( $this->getValues() ), $exclude );
641 }
642
643 /**
644 * Get the values passed in the query string.
645 * No transformation is performed on the values.
646 *
647 * @codeCoverageIgnore
648 * @return array
649 */
650 public function getQueryValues() {
651 return $_GET;
652 }
653
654 /**
655 * Return the contents of the Query with no decoding. Use when you need to
656 * know exactly what was sent, e.g. for an OAuth signature over the elements.
657 *
658 * @codeCoverageIgnore
659 * @return string
660 */
661 public function getRawQueryString() {
662 return $_SERVER['QUERY_STRING'];
663 }
664
665 /**
666 * Return the contents of the POST with no decoding. Use when you need to
667 * know exactly what was sent, e.g. for an OAuth signature over the elements.
668 *
669 * @return string
670 */
671 public function getRawPostString() {
672 if ( !$this->wasPosted() ) {
673 return '';
674 }
675 return $this->getRawInput();
676 }
677
678 /**
679 * Return the raw request body, with no processing. Cached since some methods
680 * disallow reading the stream more than once. As stated in the php docs, this
681 * does not work with enctype="multipart/form-data".
682 *
683 * @return string
684 */
685 public function getRawInput() {
686 static $input = null;
687 if ( $input === null ) {
688 $input = file_get_contents( 'php://input' );
689 }
690 return $input;
691 }
692
693 /**
694 * Get the HTTP method used for this request.
695 *
696 * @return string
697 */
698 public function getMethod() {
699 return isset( $_SERVER['REQUEST_METHOD'] ) ? $_SERVER['REQUEST_METHOD'] : 'GET';
700 }
701
702 /**
703 * Returns true if the present request was reached by a POST operation,
704 * false otherwise (GET, HEAD, or command-line).
705 *
706 * Note that values retrieved by the object may come from the
707 * GET URL etc even on a POST request.
708 *
709 * @return bool
710 */
711 public function wasPosted() {
712 return $this->getMethod() == 'POST';
713 }
714
715 /**
716 * Return the session for this request
717 *
718 * This might unpersist an existing session if it was invalid.
719 *
720 * @since 1.27
721 * @note For performance, keep the session locally if you will be making
722 * much use of it instead of calling this method repeatedly.
723 * @return Session
724 */
725 public function getSession() {
726 if ( $this->sessionId !== null ) {
727 $session = SessionManager::singleton()->getSessionById( (string)$this->sessionId, true, $this );
728 if ( $session ) {
729 return $session;
730 }
731 }
732
733 $session = SessionManager::singleton()->getSessionForRequest( $this );
734 $this->sessionId = $session->getSessionId();
735 return $session;
736 }
737
738 /**
739 * Set the session for this request
740 * @since 1.27
741 * @private For use by MediaWiki\Session classes only
742 * @param SessionId $sessionId
743 */
744 public function setSessionId( SessionId $sessionId ) {
745 $this->sessionId = $sessionId;
746 }
747
748 /**
749 * Get the session id for this request, if any
750 * @since 1.27
751 * @private For use by MediaWiki\Session classes only
752 * @return SessionId|null
753 */
754 public function getSessionId() {
755 return $this->sessionId;
756 }
757
758 /**
759 * Returns true if the request has a persistent session.
760 * This does not necessarily mean that the user is logged in!
761 *
762 * @deprecated since 1.27, use
763 * \MediaWiki\Session\SessionManager::singleton()->getPersistedSessionId()
764 * instead.
765 * @return bool
766 */
767 public function checkSessionCookie() {
768 global $wgInitialSessionId;
769 wfDeprecated( __METHOD__, '1.27' );
770 return $wgInitialSessionId !== null &&
771 $this->getSession()->getId() === (string)$wgInitialSessionId;
772 }
773
774 /**
775 * Get a cookie from the $_COOKIE jar
776 *
777 * @param string $key The name of the cookie
778 * @param string $prefix A prefix to use for the cookie name, if not $wgCookiePrefix
779 * @param mixed $default What to return if the value isn't found
780 * @return mixed Cookie value or $default if the cookie not set
781 */
782 public function getCookie( $key, $prefix = null, $default = null ) {
783 if ( $prefix === null ) {
784 global $wgCookiePrefix;
785 $prefix = $wgCookiePrefix;
786 }
787 return $this->getGPCVal( $_COOKIE, $prefix . $key, $default );
788 }
789
790 /**
791 * Return the path and query string portion of the main request URI.
792 * This will be suitable for use as a relative link in HTML output.
793 *
794 * @throws MWException
795 * @return string
796 */
797 public static function getGlobalRequestURL() {
798 if ( isset( $_SERVER['REQUEST_URI'] ) && strlen( $_SERVER['REQUEST_URI'] ) ) {
799 $base = $_SERVER['REQUEST_URI'];
800 } elseif ( isset( $_SERVER['HTTP_X_ORIGINAL_URL'] )
801 && strlen( $_SERVER['HTTP_X_ORIGINAL_URL'] )
802 ) {
803 // Probably IIS; doesn't set REQUEST_URI
804 $base = $_SERVER['HTTP_X_ORIGINAL_URL'];
805 } elseif ( isset( $_SERVER['SCRIPT_NAME'] ) ) {
806 $base = $_SERVER['SCRIPT_NAME'];
807 if ( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
808 $base .= '?' . $_SERVER['QUERY_STRING'];
809 }
810 } else {
811 // This shouldn't happen!
812 throw new MWException( "Web server doesn't provide either " .
813 "REQUEST_URI, HTTP_X_ORIGINAL_URL or SCRIPT_NAME. Report details " .
814 "of your web server configuration to https://phabricator.wikimedia.org/" );
815 }
816 // User-agents should not send a fragment with the URI, but
817 // if they do, and the web server passes it on to us, we
818 // need to strip it or we get false-positive redirect loops
819 // or weird output URLs
820 $hash = strpos( $base, '#' );
821 if ( $hash !== false ) {
822 $base = substr( $base, 0, $hash );
823 }
824
825 if ( $base[0] == '/' ) {
826 // More than one slash will look like it is protocol relative
827 return preg_replace( '!^/+!', '/', $base );
828 } else {
829 // We may get paths with a host prepended; strip it.
830 return preg_replace( '!^[^:]+://[^/]+/+!', '/', $base );
831 }
832 }
833
834 /**
835 * Return the path and query string portion of the request URI.
836 * This will be suitable for use as a relative link in HTML output.
837 *
838 * @throws MWException
839 * @return string
840 */
841 public function getRequestURL() {
842 return self::getGlobalRequestURL();
843 }
844
845 /**
846 * Return the request URI with the canonical service and hostname, path,
847 * and query string. This will be suitable for use as an absolute link
848 * in HTML or other output.
849 *
850 * If $wgServer is protocol-relative, this will return a fully
851 * qualified URL with the protocol that was used for this request.
852 *
853 * @return string
854 */
855 public function getFullRequestURL() {
856 return wfExpandUrl( $this->getRequestURL(), PROTO_CURRENT );
857 }
858
859 /**
860 * @param string $key
861 * @param string $value
862 * @return string
863 */
864 public function appendQueryValue( $key, $value ) {
865 return $this->appendQueryArray( [ $key => $value ] );
866 }
867
868 /**
869 * Appends or replaces value of query variables.
870 *
871 * @param array $array Array of values to replace/add to query
872 * @return string
873 */
874 public function appendQueryArray( $array ) {
875 $newquery = $this->getQueryValues();
876 unset( $newquery['title'] );
877 $newquery = array_merge( $newquery, $array );
878
879 return wfArrayToCgi( $newquery );
880 }
881
882 /**
883 * Check for limit and offset parameters on the input, and return sensible
884 * defaults if not given. The limit must be positive and is capped at 5000.
885 * Offset must be positive but is not capped.
886 *
887 * @param int $deflimit Limit to use if no input and the user hasn't set the option.
888 * @param string $optionname To specify an option other than rclimit to pull from.
889 * @return int[] First element is limit, second is offset
890 */
891 public function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
892 global $wgUser;
893
894 $limit = $this->getInt( 'limit', 0 );
895 if ( $limit < 0 ) {
896 $limit = 0;
897 }
898 if ( ( $limit == 0 ) && ( $optionname != '' ) ) {
899 $limit = $wgUser->getIntOption( $optionname );
900 }
901 if ( $limit <= 0 ) {
902 $limit = $deflimit;
903 }
904 if ( $limit > 5000 ) {
905 $limit = 5000; # We have *some* limits...
906 }
907
908 $offset = $this->getInt( 'offset', 0 );
909 if ( $offset < 0 ) {
910 $offset = 0;
911 }
912
913 return [ $limit, $offset ];
914 }
915
916 /**
917 * Return the path to the temporary file where PHP has stored the upload.
918 *
919 * @param string $key
920 * @return string|null String or null if no such file.
921 */
922 public function getFileTempname( $key ) {
923 $file = new WebRequestUpload( $this, $key );
924 return $file->getTempName();
925 }
926
927 /**
928 * Return the upload error or 0
929 *
930 * @param string $key
931 * @return int
932 */
933 public function getUploadError( $key ) {
934 $file = new WebRequestUpload( $this, $key );
935 return $file->getError();
936 }
937
938 /**
939 * Return the original filename of the uploaded file, as reported by
940 * the submitting user agent. HTML-style character entities are
941 * interpreted and normalized to Unicode normalization form C, in part
942 * to deal with weird input from Safari with non-ASCII filenames.
943 *
944 * Other than this the name is not verified for being a safe filename.
945 *
946 * @param string $key
947 * @return string|null String or null if no such file.
948 */
949 public function getFileName( $key ) {
950 $file = new WebRequestUpload( $this, $key );
951 return $file->getName();
952 }
953
954 /**
955 * Return a WebRequestUpload object corresponding to the key
956 *
957 * @param string $key
958 * @return WebRequestUpload
959 */
960 public function getUpload( $key ) {
961 return new WebRequestUpload( $this, $key );
962 }
963
964 /**
965 * Return a handle to WebResponse style object, for setting cookies,
966 * headers and other stuff, for Request being worked on.
967 *
968 * @return WebResponse
969 */
970 public function response() {
971 /* Lazy initialization of response object for this request */
972 if ( !is_object( $this->response ) ) {
973 $class = ( $this instanceof FauxRequest ) ? 'FauxResponse' : 'WebResponse';
974 $this->response = new $class();
975 }
976 return $this->response;
977 }
978
979 /**
980 * Initialise the header list
981 */
982 protected function initHeaders() {
983 if ( count( $this->headers ) ) {
984 return;
985 }
986
987 $apacheHeaders = function_exists( 'apache_request_headers' ) ? apache_request_headers() : false;
988 if ( $apacheHeaders ) {
989 foreach ( $apacheHeaders as $tempName => $tempValue ) {
990 $this->headers[strtoupper( $tempName )] = $tempValue;
991 }
992 } else {
993 foreach ( $_SERVER as $name => $value ) {
994 if ( substr( $name, 0, 5 ) === 'HTTP_' ) {
995 $name = str_replace( '_', '-', substr( $name, 5 ) );
996 $this->headers[$name] = $value;
997 } elseif ( $name === 'CONTENT_LENGTH' ) {
998 $this->headers['CONTENT-LENGTH'] = $value;
999 }
1000 }
1001 }
1002 }
1003
1004 /**
1005 * Get an array containing all request headers
1006 *
1007 * @return array Mapping header name to its value
1008 */
1009 public function getAllHeaders() {
1010 $this->initHeaders();
1011 return $this->headers;
1012 }
1013
1014 /**
1015 * Get a request header, or false if it isn't set.
1016 *
1017 * @param string $name Case-insensitive header name
1018 * @param int $flags Bitwise combination of:
1019 * WebRequest::GETHEADER_LIST Treat the header as a comma-separated list
1020 * of values, as described in RFC 2616 § 4.2.
1021 * (since 1.26).
1022 * @return string|array|bool False if header is unset; otherwise the
1023 * header value(s) as either a string (the default) or an array, if
1024 * WebRequest::GETHEADER_LIST flag was set.
1025 */
1026 public function getHeader( $name, $flags = 0 ) {
1027 $this->initHeaders();
1028 $name = strtoupper( $name );
1029 if ( !isset( $this->headers[$name] ) ) {
1030 return false;
1031 }
1032 $value = $this->headers[$name];
1033 if ( $flags & self::GETHEADER_LIST ) {
1034 $value = array_map( 'trim', explode( ',', $value ) );
1035 }
1036 return $value;
1037 }
1038
1039 /**
1040 * Get data from the session
1041 *
1042 * @note Prefer $this->getSession() instead if making multiple calls.
1043 * @param string $key Name of key in the session
1044 * @return mixed
1045 */
1046 public function getSessionData( $key ) {
1047 return $this->getSession()->get( $key );
1048 }
1049
1050 /**
1051 * Set session data
1052 *
1053 * @note Prefer $this->getSession() instead if making multiple calls.
1054 * @param string $key Name of key in the session
1055 * @param mixed $data
1056 */
1057 public function setSessionData( $key, $data ) {
1058 $this->getSession()->set( $key, $data );
1059 }
1060
1061 /**
1062 * Check if Internet Explorer will detect an incorrect cache extension in
1063 * PATH_INFO or QUERY_STRING. If the request can't be allowed, show an error
1064 * message or redirect to a safer URL. Returns true if the URL is OK, and
1065 * false if an error message has been shown and the request should be aborted.
1066 *
1067 * @param array $extWhitelist
1068 * @throws HttpError
1069 * @return bool
1070 */
1071 public function checkUrlExtension( $extWhitelist = [] ) {
1072 $extWhitelist[] = 'php';
1073 if ( IEUrlExtension::areServerVarsBad( $_SERVER, $extWhitelist ) ) {
1074 if ( !$this->wasPosted() ) {
1075 $newUrl = IEUrlExtension::fixUrlForIE6(
1076 $this->getFullRequestURL(), $extWhitelist );
1077 if ( $newUrl !== false ) {
1078 $this->doSecurityRedirect( $newUrl );
1079 return false;
1080 }
1081 }
1082 throw new HttpError( 403,
1083 'Invalid file extension found in the path info or query string.' );
1084 }
1085 return true;
1086 }
1087
1088 /**
1089 * Attempt to redirect to a URL with a QUERY_STRING that's not dangerous in
1090 * IE 6. Returns true if it was successful, false otherwise.
1091 *
1092 * @param string $url
1093 * @return bool
1094 */
1095 protected function doSecurityRedirect( $url ) {
1096 header( 'Location: ' . $url );
1097 header( 'Content-Type: text/html' );
1098 $encUrl = htmlspecialchars( $url );
1099 echo <<<HTML
1100 <html>
1101 <head>
1102 <title>Security redirect</title>
1103 </head>
1104 <body>
1105 <h1>Security redirect</h1>
1106 <p>
1107 We can't serve non-HTML content from the URL you have requested, because
1108 Internet Explorer would interpret it as an incorrect and potentially dangerous
1109 content type.</p>
1110 <p>Instead, please use <a href="$encUrl">this URL</a>, which is the same as the
1111 URL you have requested, except that "&amp;*" is appended. This prevents Internet
1112 Explorer from seeing a bogus file extension.
1113 </p>
1114 </body>
1115 </html>
1116 HTML;
1117 echo "\n";
1118 return true;
1119 }
1120
1121 /**
1122 * Parse the Accept-Language header sent by the client into an array
1123 *
1124 * @return array Array( languageCode => q-value ) sorted by q-value in
1125 * descending order then appearing time in the header in ascending order.
1126 * May contain the "language" '*', which applies to languages other than those explicitly listed.
1127 * This is aligned with rfc2616 section 14.4
1128 * Preference for earlier languages appears in rfc3282 as an extension to HTTP/1.1.
1129 */
1130 public function getAcceptLang() {
1131 // Modified version of code found at
1132 // http://www.thefutureoftheweb.com/blog/use-accept-language-header
1133 $acceptLang = $this->getHeader( 'Accept-Language' );
1134 if ( !$acceptLang ) {
1135 return [];
1136 }
1137
1138 // Return the language codes in lower case
1139 $acceptLang = strtolower( $acceptLang );
1140
1141 // Break up string into pieces (languages and q factors)
1142 $lang_parse = null;
1143 preg_match_all(
1144 '/([a-z]{1,8}(-[a-z]{1,8})*|\*)\s*(;\s*q\s*=\s*(1(\.0{0,3})?|0(\.[0-9]{0,3})?)?)?/',
1145 $acceptLang,
1146 $lang_parse
1147 );
1148
1149 if ( !count( $lang_parse[1] ) ) {
1150 return [];
1151 }
1152
1153 $langcodes = $lang_parse[1];
1154 $qvalues = $lang_parse[4];
1155 $indices = range( 0, count( $lang_parse[1] ) - 1 );
1156
1157 // Set default q factor to 1
1158 foreach ( $indices as $index ) {
1159 if ( $qvalues[$index] === '' ) {
1160 $qvalues[$index] = 1;
1161 } elseif ( $qvalues[$index] == 0 ) {
1162 unset( $langcodes[$index], $qvalues[$index], $indices[$index] );
1163 }
1164 }
1165
1166 // Sort list. First by $qvalues, then by order. Reorder $langcodes the same way
1167 array_multisort( $qvalues, SORT_DESC, SORT_NUMERIC, $indices, $langcodes );
1168
1169 // Create a list like "en" => 0.8
1170 $langs = array_combine( $langcodes, $qvalues );
1171
1172 return $langs;
1173 }
1174
1175 /**
1176 * Fetch the raw IP from the request
1177 *
1178 * @since 1.19
1179 *
1180 * @throws MWException
1181 * @return string
1182 */
1183 protected function getRawIP() {
1184 if ( !isset( $_SERVER['REMOTE_ADDR'] ) ) {
1185 return null;
1186 }
1187
1188 if ( is_array( $_SERVER['REMOTE_ADDR'] ) || strpos( $_SERVER['REMOTE_ADDR'], ',' ) !== false ) {
1189 throw new MWException( __METHOD__
1190 . " : Could not determine the remote IP address due to multiple values." );
1191 } else {
1192 $ipchain = $_SERVER['REMOTE_ADDR'];
1193 }
1194
1195 return IP::canonicalize( $ipchain );
1196 }
1197
1198 /**
1199 * Work out the IP address based on various globals
1200 * For trusted proxies, use the XFF client IP (first of the chain)
1201 *
1202 * @since 1.19
1203 *
1204 * @throws MWException
1205 * @return string
1206 */
1207 public function getIP() {
1208 global $wgUsePrivateIPs;
1209
1210 # Return cached result
1211 if ( $this->ip !== null ) {
1212 return $this->ip;
1213 }
1214
1215 # collect the originating ips
1216 $ip = $this->getRawIP();
1217 if ( !$ip ) {
1218 throw new MWException( 'Unable to determine IP.' );
1219 }
1220
1221 # Append XFF
1222 $forwardedFor = $this->getHeader( 'X-Forwarded-For' );
1223 if ( $forwardedFor !== false ) {
1224 $isConfigured = IP::isConfiguredProxy( $ip );
1225 $ipchain = array_map( 'trim', explode( ',', $forwardedFor ) );
1226 $ipchain = array_reverse( $ipchain );
1227 array_unshift( $ipchain, $ip );
1228
1229 # Step through XFF list and find the last address in the list which is a
1230 # trusted server. Set $ip to the IP address given by that trusted server,
1231 # unless the address is not sensible (e.g. private). However, prefer private
1232 # IP addresses over proxy servers controlled by this site (more sensible).
1233 # Note that some XFF values might be "unknown" with Squid/Varnish.
1234 foreach ( $ipchain as $i => $curIP ) {
1235 $curIP = IP::sanitizeIP( IP::canonicalize( $curIP ) );
1236 if ( !$curIP || !isset( $ipchain[$i + 1] ) || $ipchain[$i + 1] === 'unknown'
1237 || !IP::isTrustedProxy( $curIP )
1238 ) {
1239 break; // IP is not valid/trusted or does not point to anything
1240 }
1241 if (
1242 IP::isPublic( $ipchain[$i + 1] ) ||
1243 $wgUsePrivateIPs ||
1244 IP::isConfiguredProxy( $curIP ) // bug 48919; treat IP as sane
1245 ) {
1246 // Follow the next IP according to the proxy
1247 $nextIP = IP::canonicalize( $ipchain[$i + 1] );
1248 if ( !$nextIP && $isConfigured ) {
1249 // We have not yet made it past CDN/proxy servers of this site,
1250 // so either they are misconfigured or there is some IP spoofing.
1251 throw new MWException( "Invalid IP given in XFF '$forwardedFor'." );
1252 }
1253 $ip = $nextIP;
1254 // keep traversing the chain
1255 continue;
1256 }
1257 break;
1258 }
1259 }
1260
1261 # Allow extensions to improve our guess
1262 Hooks::run( 'GetIP', [ &$ip ] );
1263
1264 if ( !$ip ) {
1265 throw new MWException( "Unable to determine IP." );
1266 }
1267
1268 wfDebug( "IP: $ip\n" );
1269 $this->ip = $ip;
1270 return $ip;
1271 }
1272
1273 /**
1274 * @param string $ip
1275 * @return void
1276 * @since 1.21
1277 */
1278 public function setIP( $ip ) {
1279 $this->ip = $ip;
1280 }
1281
1282 /**
1283 * Check if this request uses a "safe" HTTP method
1284 *
1285 * Safe methods are verbs (e.g. GET/HEAD/OPTIONS) used for obtaining content. Such requests
1286 * are not expected to mutate content, especially in ways attributable to the client. Verbs
1287 * like POST and PUT are typical of non-safe requests which often change content.
1288 *
1289 * @return bool
1290 * @see https://tools.ietf.org/html/rfc7231#section-4.2.1
1291 * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
1292 * @since 1.28
1293 */
1294 public function hasSafeMethod() {
1295 if ( !isset( $_SERVER['REQUEST_METHOD'] ) ) {
1296 return false; // CLI mode
1297 }
1298
1299 return in_array( $_SERVER['REQUEST_METHOD'], [ 'GET', 'HEAD', 'OPTIONS', 'TRACE' ] );
1300 }
1301
1302 /**
1303 * Whether this request should be identified as being "safe"
1304 *
1305 * This means that the client is not requesting any state changes and that database writes
1306 * are not inherently required. Ideally, no visible updates would happen at all. If they
1307 * must, then they should not be publically attributed to the end user.
1308 *
1309 * In more detail:
1310 * - Cache populations and refreshes MAY occur.
1311 * - Private user session updates and private server logging MAY occur.
1312 * - Updates to private viewing activity data MAY occur via DeferredUpdates.
1313 * - Other updates SHOULD NOT occur (e.g. modifying content assets).
1314 *
1315 * @return bool
1316 * @see https://tools.ietf.org/html/rfc7231#section-4.2.1
1317 * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
1318 * @since 1.28
1319 */
1320 public function isSafeRequest() {
1321 if ( $this->markedAsSafe && $this->wasPosted() ) {
1322 return true; // marked as a "safe" POST
1323 }
1324
1325 return $this->hasSafeMethod();
1326 }
1327
1328 /**
1329 * Mark this request as identified as being nullipotent even if it is a POST request
1330 *
1331 * POST requests are often used due to the need for a client payload, even if the request
1332 * is otherwise equivalent to a "safe method" request.
1333 *
1334 * @see https://tools.ietf.org/html/rfc7231#section-4.2.1
1335 * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
1336 * @since 1.28
1337 */
1338 public function markAsSafeRequest() {
1339 $this->markedAsSafe = true;
1340 }
1341 }