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