WebRequest::appendQuery*() functions no longer take $onlyquery
[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 * @param string $key
731 * @param string $value
732 * @return string
733 */
734 public function appendQueryValue( $key, $value ) {
735 return $this->appendQueryArray( array( $key => $value ) );
736 }
737
738 /**
739 * Appends or replaces value of query variables.
740 *
741 * @param array $array Array of values to replace/add to query
742 * @return string
743 */
744 public function appendQueryArray( $array ) {
745 $newquery = $this->getQueryValues();
746 unset( $newquery['title'] );
747 $newquery = array_merge( $newquery, $array );
748
749 return wfArrayToCgi( $newquery );
750 }
751
752 /**
753 * Check for limit and offset parameters on the input, and return sensible
754 * defaults if not given. The limit must be positive and is capped at 5000.
755 * Offset must be positive but is not capped.
756 *
757 * @param int $deflimit Limit to use if no input and the user hasn't set the option.
758 * @param string $optionname To specify an option other than rclimit to pull from.
759 * @return int[] First element is limit, second is offset
760 */
761 public function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
762 global $wgUser;
763
764 $limit = $this->getInt( 'limit', 0 );
765 if ( $limit < 0 ) {
766 $limit = 0;
767 }
768 if ( ( $limit == 0 ) && ( $optionname != '' ) ) {
769 $limit = $wgUser->getIntOption( $optionname );
770 }
771 if ( $limit <= 0 ) {
772 $limit = $deflimit;
773 }
774 if ( $limit > 5000 ) {
775 $limit = 5000; # We have *some* limits...
776 }
777
778 $offset = $this->getInt( 'offset', 0 );
779 if ( $offset < 0 ) {
780 $offset = 0;
781 }
782
783 return array( $limit, $offset );
784 }
785
786 /**
787 * Return the path to the temporary file where PHP has stored the upload.
788 *
789 * @param string $key
790 * @return string|null String or null if no such file.
791 */
792 public function getFileTempname( $key ) {
793 $file = new WebRequestUpload( $this, $key );
794 return $file->getTempName();
795 }
796
797 /**
798 * Return the upload error or 0
799 *
800 * @param string $key
801 * @return int
802 */
803 public function getUploadError( $key ) {
804 $file = new WebRequestUpload( $this, $key );
805 return $file->getError();
806 }
807
808 /**
809 * Return the original filename of the uploaded file, as reported by
810 * the submitting user agent. HTML-style character entities are
811 * interpreted and normalized to Unicode normalization form C, in part
812 * to deal with weird input from Safari with non-ASCII filenames.
813 *
814 * Other than this the name is not verified for being a safe filename.
815 *
816 * @param string $key
817 * @return string|null String or null if no such file.
818 */
819 public function getFileName( $key ) {
820 $file = new WebRequestUpload( $this, $key );
821 return $file->getName();
822 }
823
824 /**
825 * Return a WebRequestUpload object corresponding to the key
826 *
827 * @param string $key
828 * @return WebRequestUpload
829 */
830 public function getUpload( $key ) {
831 return new WebRequestUpload( $this, $key );
832 }
833
834 /**
835 * Return a handle to WebResponse style object, for setting cookies,
836 * headers and other stuff, for Request being worked on.
837 *
838 * @return WebResponse
839 */
840 public function response() {
841 /* Lazy initialization of response object for this request */
842 if ( !is_object( $this->response ) ) {
843 $class = ( $this instanceof FauxRequest ) ? 'FauxResponse' : 'WebResponse';
844 $this->response = new $class();
845 }
846 return $this->response;
847 }
848
849 /**
850 * Initialise the header list
851 */
852 protected function initHeaders() {
853 if ( count( $this->headers ) ) {
854 return;
855 }
856
857 $apacheHeaders = function_exists( 'apache_request_headers' ) ? apache_request_headers() : false;
858 if ( $apacheHeaders ) {
859 foreach ( $apacheHeaders as $tempName => $tempValue ) {
860 $this->headers[strtoupper( $tempName )] = $tempValue;
861 }
862 } else {
863 foreach ( $_SERVER as $name => $value ) {
864 if ( substr( $name, 0, 5 ) === 'HTTP_' ) {
865 $name = str_replace( '_', '-', substr( $name, 5 ) );
866 $this->headers[$name] = $value;
867 } elseif ( $name === 'CONTENT_LENGTH' ) {
868 $this->headers['CONTENT-LENGTH'] = $value;
869 }
870 }
871 }
872 }
873
874 /**
875 * Get an array containing all request headers
876 *
877 * @return array Mapping header name to its value
878 */
879 public function getAllHeaders() {
880 $this->initHeaders();
881 return $this->headers;
882 }
883
884 /**
885 * Get a request header, or false if it isn't set.
886 *
887 * @param string $name Case-insensitive header name
888 * @param int $flags Bitwise combination of:
889 * WebRequest::GETHEADER_LIST Treat the header as a comma-separated list
890 * of values, as described in RFC 2616 § 4.2.
891 * (since 1.26).
892 * @return string|array|bool False if header is unset; otherwise the
893 * header value(s) as either a string (the default) or an array, if
894 * WebRequest::GETHEADER_LIST flag was set.
895 */
896 public function getHeader( $name, $flags = 0 ) {
897 $this->initHeaders();
898 $name = strtoupper( $name );
899 if ( !isset( $this->headers[$name] ) ) {
900 return false;
901 }
902 $value = $this->headers[$name];
903 if ( $flags & self::GETHEADER_LIST ) {
904 $value = array_map( 'trim', explode( ',', $value ) );
905 }
906 return $value;
907 }
908
909 /**
910 * Get data from $_SESSION
911 *
912 * @param string $key Name of key in $_SESSION
913 * @return mixed
914 */
915 public function getSessionData( $key ) {
916 if ( !isset( $_SESSION[$key] ) ) {
917 return null;
918 }
919 return $_SESSION[$key];
920 }
921
922 /**
923 * Set session data
924 *
925 * @param string $key Name of key in $_SESSION
926 * @param mixed $data
927 */
928 public function setSessionData( $key, $data ) {
929 $_SESSION[$key] = $data;
930 }
931
932 /**
933 * Check if Internet Explorer will detect an incorrect cache extension in
934 * PATH_INFO or QUERY_STRING. If the request can't be allowed, show an error
935 * message or redirect to a safer URL. Returns true if the URL is OK, and
936 * false if an error message has been shown and the request should be aborted.
937 *
938 * @param array $extWhitelist
939 * @throws HttpError
940 * @return bool
941 */
942 public function checkUrlExtension( $extWhitelist = array() ) {
943 $extWhitelist[] = 'php';
944 if ( IEUrlExtension::areServerVarsBad( $_SERVER, $extWhitelist ) ) {
945 if ( !$this->wasPosted() ) {
946 $newUrl = IEUrlExtension::fixUrlForIE6(
947 $this->getFullRequestURL(), $extWhitelist );
948 if ( $newUrl !== false ) {
949 $this->doSecurityRedirect( $newUrl );
950 return false;
951 }
952 }
953 throw new HttpError( 403,
954 'Invalid file extension found in the path info or query string.' );
955 }
956 return true;
957 }
958
959 /**
960 * Attempt to redirect to a URL with a QUERY_STRING that's not dangerous in
961 * IE 6. Returns true if it was successful, false otherwise.
962 *
963 * @param string $url
964 * @return bool
965 */
966 protected function doSecurityRedirect( $url ) {
967 header( 'Location: ' . $url );
968 header( 'Content-Type: text/html' );
969 $encUrl = htmlspecialchars( $url );
970 echo <<<HTML
971 <html>
972 <head>
973 <title>Security redirect</title>
974 </head>
975 <body>
976 <h1>Security redirect</h1>
977 <p>
978 We can't serve non-HTML content from the URL you have requested, because
979 Internet Explorer would interpret it as an incorrect and potentially dangerous
980 content type.</p>
981 <p>Instead, please use <a href="$encUrl">this URL</a>, which is the same as the
982 URL you have requested, except that "&amp;*" is appended. This prevents Internet
983 Explorer from seeing a bogus file extension.
984 </p>
985 </body>
986 </html>
987 HTML;
988 echo "\n";
989 return true;
990 }
991
992 /**
993 * Parse the Accept-Language header sent by the client into an array
994 *
995 * @return array Array( languageCode => q-value ) sorted by q-value in
996 * descending order then appearing time in the header in ascending order.
997 * May contain the "language" '*', which applies to languages other than those explicitly listed.
998 * This is aligned with rfc2616 section 14.4
999 * Preference for earlier languages appears in rfc3282 as an extension to HTTP/1.1.
1000 */
1001 public function getAcceptLang() {
1002 // Modified version of code found at
1003 // http://www.thefutureoftheweb.com/blog/use-accept-language-header
1004 $acceptLang = $this->getHeader( 'Accept-Language' );
1005 if ( !$acceptLang ) {
1006 return array();
1007 }
1008
1009 // Return the language codes in lower case
1010 $acceptLang = strtolower( $acceptLang );
1011
1012 // Break up string into pieces (languages and q factors)
1013 $lang_parse = null;
1014 preg_match_all(
1015 '/([a-z]{1,8}(-[a-z]{1,8})*|\*)\s*(;\s*q\s*=\s*(1(\.0{0,3})?|0(\.[0-9]{0,3})?)?)?/',
1016 $acceptLang,
1017 $lang_parse
1018 );
1019
1020 if ( !count( $lang_parse[1] ) ) {
1021 return array();
1022 }
1023
1024 $langcodes = $lang_parse[1];
1025 $qvalues = $lang_parse[4];
1026 $indices = range( 0, count( $lang_parse[1] ) - 1 );
1027
1028 // Set default q factor to 1
1029 foreach ( $indices as $index ) {
1030 if ( $qvalues[$index] === '' ) {
1031 $qvalues[$index] = 1;
1032 } elseif ( $qvalues[$index] == 0 ) {
1033 unset( $langcodes[$index], $qvalues[$index], $indices[$index] );
1034 }
1035 }
1036
1037 // Sort list. First by $qvalues, then by order. Reorder $langcodes the same way
1038 array_multisort( $qvalues, SORT_DESC, SORT_NUMERIC, $indices, $langcodes );
1039
1040 // Create a list like "en" => 0.8
1041 $langs = array_combine( $langcodes, $qvalues );
1042
1043 return $langs;
1044 }
1045
1046 /**
1047 * Fetch the raw IP from the request
1048 *
1049 * @since 1.19
1050 *
1051 * @throws MWException
1052 * @return string
1053 */
1054 protected function getRawIP() {
1055 if ( !isset( $_SERVER['REMOTE_ADDR'] ) ) {
1056 return null;
1057 }
1058
1059 if ( is_array( $_SERVER['REMOTE_ADDR'] ) || strpos( $_SERVER['REMOTE_ADDR'], ',' ) !== false ) {
1060 throw new MWException( __METHOD__
1061 . " : Could not determine the remote IP address due to multiple values." );
1062 } else {
1063 $ipchain = $_SERVER['REMOTE_ADDR'];
1064 }
1065
1066 return IP::canonicalize( $ipchain );
1067 }
1068
1069 /**
1070 * Work out the IP address based on various globals
1071 * For trusted proxies, use the XFF client IP (first of the chain)
1072 *
1073 * @since 1.19
1074 *
1075 * @throws MWException
1076 * @return string
1077 */
1078 public function getIP() {
1079 global $wgUsePrivateIPs;
1080
1081 # Return cached result
1082 if ( $this->ip !== null ) {
1083 return $this->ip;
1084 }
1085
1086 # collect the originating ips
1087 $ip = $this->getRawIP();
1088 if ( !$ip ) {
1089 throw new MWException( 'Unable to determine IP.' );
1090 }
1091
1092 # Append XFF
1093 $forwardedFor = $this->getHeader( 'X-Forwarded-For' );
1094 if ( $forwardedFor !== false ) {
1095 $isConfigured = IP::isConfiguredProxy( $ip );
1096 $ipchain = array_map( 'trim', explode( ',', $forwardedFor ) );
1097 $ipchain = array_reverse( $ipchain );
1098 array_unshift( $ipchain, $ip );
1099
1100 # Step through XFF list and find the last address in the list which is a
1101 # trusted server. Set $ip to the IP address given by that trusted server,
1102 # unless the address is not sensible (e.g. private). However, prefer private
1103 # IP addresses over proxy servers controlled by this site (more sensible).
1104 # Note that some XFF values might be "unknown" with Squid/Varnish.
1105 foreach ( $ipchain as $i => $curIP ) {
1106 $curIP = IP::sanitizeIP( IP::canonicalize( $curIP ) );
1107 if ( !$curIP || !isset( $ipchain[$i + 1] ) || $ipchain[$i + 1] === 'unknown'
1108 || !IP::isTrustedProxy( $curIP )
1109 ) {
1110 break; // IP is not valid/trusted or does not point to anything
1111 }
1112 if (
1113 IP::isPublic( $ipchain[$i + 1] ) ||
1114 $wgUsePrivateIPs ||
1115 IP::isConfiguredProxy( $curIP ) // bug 48919; treat IP as sane
1116 ) {
1117 // Follow the next IP according to the proxy
1118 $nextIP = IP::canonicalize( $ipchain[$i + 1] );
1119 if ( !$nextIP && $isConfigured ) {
1120 // We have not yet made it past CDN/proxy servers of this site,
1121 // so either they are misconfigured or there is some IP spoofing.
1122 throw new MWException( "Invalid IP given in XFF '$forwardedFor'." );
1123 }
1124 $ip = $nextIP;
1125 // keep traversing the chain
1126 continue;
1127 }
1128 break;
1129 }
1130 }
1131
1132 # Allow extensions to improve our guess
1133 Hooks::run( 'GetIP', array( &$ip ) );
1134
1135 if ( !$ip ) {
1136 throw new MWException( "Unable to determine IP." );
1137 }
1138
1139 wfDebug( "IP: $ip\n" );
1140 $this->ip = $ip;
1141 return $ip;
1142 }
1143
1144 /**
1145 * @param string $ip
1146 * @return void
1147 * @since 1.21
1148 */
1149 public function setIP( $ip ) {
1150 $this->ip = $ip;
1151 }
1152 }