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