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