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