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