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