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