(bug 37755) Set robot meta tags for 'view source' pages
[lhc/web/wiklou.git] / includes / WebRequest.php
1 <?php
2 /**
3 * Deal with importing all those nasssty 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 $want string: 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 static public 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 return ( isset( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] == 'on' ) ? array( 'https', 443 ) : array( 'http', 80 );
196 }
197
198 /**
199 * @return string
200 */
201 public static function detectProtocol() {
202 list( $proto, $stdPort ) = self::detectProtocolAndStdPort();
203 return $proto;
204 }
205
206 /**
207 * Check for title, action, and/or variant data in the URL
208 * and interpolate it into the GET variables.
209 * This should only be run after $wgContLang is available,
210 * as we may need the list of language variants to determine
211 * available variant URLs.
212 */
213 public function interpolateTitle() {
214 // bug 16019: title interpolation on API queries is useless and sometimes harmful
215 if ( defined( 'MW_API' ) ) {
216 return;
217 }
218
219 $matches = self::getPathInfo( 'title' );
220 foreach( $matches as $key => $val) {
221 $this->data[$key] = $_GET[$key] = $_REQUEST[$key] = $val;
222 }
223 }
224
225 /**
226 * URL rewriting function; tries to extract page title and,
227 * optionally, one other fixed parameter value from a URL path.
228 *
229 * @param $path string: the URL path given from the client
230 * @param $bases array: one or more URLs, optionally with $1 at the end
231 * @param $key string: if provided, the matching key in $bases will be
232 * passed on as the value of this URL parameter
233 * @return array of URL variables to interpolate; empty if no match
234 */
235 static function extractTitle( $path, $bases, $key = false ) {
236 foreach( (array)$bases as $keyValue => $base ) {
237 // Find the part after $wgArticlePath
238 $base = str_replace( '$1', '', $base );
239 $baseLen = strlen( $base );
240 if( substr( $path, 0, $baseLen ) == $base ) {
241 $raw = substr( $path, $baseLen );
242 if( $raw !== '' ) {
243 $matches = array( 'title' => rawurldecode( $raw ) );
244 if( $key ) {
245 $matches[$key] = $keyValue;
246 }
247 return $matches;
248 }
249 }
250 }
251 return array();
252 }
253
254 /**
255 * Recursively strips slashes from the given array;
256 * used for undoing the evil that is magic_quotes_gpc.
257 *
258 * @param $arr array: will be modified
259 * @param $topLevel bool Specifies if the array passed is from the top
260 * level of the source. In PHP5 magic_quotes only escapes the first level
261 * of keys that belong to an array.
262 * @return array the original array
263 * @see http://www.php.net/manual/en/function.get-magic-quotes-gpc.php#49612
264 */
265 private function &fix_magic_quotes( &$arr, $topLevel = true ) {
266 $clean = array();
267 foreach( $arr as $key => $val ) {
268 if( is_array( $val ) ) {
269 $cleanKey = $topLevel ? stripslashes( $key ) : $key;
270 $clean[$cleanKey] = $this->fix_magic_quotes( $arr[$key], false );
271 } else {
272 $cleanKey = stripslashes( $key );
273 $clean[$cleanKey] = stripslashes( $val );
274 }
275 }
276 $arr = $clean;
277 return $arr;
278 }
279
280 /**
281 * If magic_quotes_gpc option is on, run the global arrays
282 * through fix_magic_quotes to strip out the stupid slashes.
283 * WARNING: This should only be done once! Running a second
284 * time could damage the values.
285 */
286 private function checkMagicQuotes() {
287 $mustFixQuotes = function_exists( 'get_magic_quotes_gpc' )
288 && get_magic_quotes_gpc();
289 if( $mustFixQuotes ) {
290 $this->fix_magic_quotes( $_COOKIE );
291 $this->fix_magic_quotes( $_ENV );
292 $this->fix_magic_quotes( $_GET );
293 $this->fix_magic_quotes( $_POST );
294 $this->fix_magic_quotes( $_REQUEST );
295 $this->fix_magic_quotes( $_SERVER );
296 }
297 }
298
299 /**
300 * Recursively normalizes UTF-8 strings in the given array.
301 *
302 * @param $data string|array
303 * @return array|string cleaned-up version of the given
304 * @private
305 */
306 function normalizeUnicode( $data ) {
307 if( is_array( $data ) ) {
308 foreach( $data as $key => $val ) {
309 $data[$key] = $this->normalizeUnicode( $val );
310 }
311 } else {
312 global $wgContLang;
313 $data = isset( $wgContLang ) ? $wgContLang->normalize( $data ) : UtfNormal::cleanUp( $data );
314 }
315 return $data;
316 }
317
318 /**
319 * Fetch a value from the given array or return $default if it's not set.
320 *
321 * @param $arr Array
322 * @param $name String
323 * @param $default Mixed
324 * @return mixed
325 */
326 private function getGPCVal( $arr, $name, $default ) {
327 # PHP is so nice to not touch input data, except sometimes:
328 # http://us2.php.net/variables.external#language.variables.external.dot-in-names
329 # Work around PHP *feature* to avoid *bugs* elsewhere.
330 $name = strtr( $name, '.', '_' );
331 if( isset( $arr[$name] ) ) {
332 global $wgContLang;
333 $data = $arr[$name];
334 if( isset( $_GET[$name] ) && !is_array( $data ) ) {
335 # Check for alternate/legacy character encoding.
336 if( isset( $wgContLang ) ) {
337 $data = $wgContLang->checkTitleEncoding( $data );
338 }
339 }
340 $data = $this->normalizeUnicode( $data );
341 return $data;
342 } else {
343 taint( $default );
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 $name String
355 * @param $default String: 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 $key String: key name to use
374 * @param $value Mixed: 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 $key String: 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 $name String
405 * @param $default Array: 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 $name String
424 * @param $default Array: option default (or NULL)
425 * @return 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 $name String
441 * @param $default Integer
442 * @return Integer
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 $name String
454 * @return Integer
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 boolean value from the input or return $default if not set.
465 * Guaranteed to return true or false, with normal PHP semantics for
466 * boolean interpretation of strings.
467 *
468 * @param $name String
469 * @param $default Boolean
470 * @return Boolean
471 */
472 public function getBool( $name, $default = false ) {
473 return (bool)$this->getVal( $name, $default );
474 }
475
476 /**
477 * Fetch a boolean value from the input or return $default if not set.
478 * Unlike getBool, the string "false" will result in boolean false, which is
479 * useful when interpreting information sent from JavaScript.
480 *
481 * @param $name String
482 * @param $default Boolean
483 * @return Boolean
484 */
485 public function getFuzzyBool( $name, $default = false ) {
486 return $this->getBool( $name, $default ) && strcasecmp( $this->getVal( $name ), 'false' ) !== 0;
487 }
488
489 /**
490 * Return true if the named value is set in the input, whatever that
491 * value is (even "0"). Return false if the named value is not set.
492 * Example use is checking for the presence of check boxes in forms.
493 *
494 * @param $name String
495 * @return Boolean
496 */
497 public function getCheck( $name ) {
498 # Checkboxes and buttons are only present when clicked
499 # Presence connotes truth, abscense false
500 return $this->getVal( $name, null ) !== null;
501 }
502
503 /**
504 * Fetch a text string from the given array or return $default if it's not
505 * set. Carriage returns are stripped from the text, and with some language
506 * modules there is an input transliteration applied. This should generally
507 * be used for form "<textarea>" and "<input>" fields. Used for
508 * user-supplied freeform text input (for which input transformations may
509 * be required - e.g. Esperanto x-coding).
510 *
511 * @param $name String
512 * @param $default String: optional
513 * @return String
514 */
515 public function getText( $name, $default = '' ) {
516 global $wgContLang;
517 $val = $this->getVal( $name, $default );
518 return str_replace( "\r\n", "\n",
519 $wgContLang->recodeInput( $val ) );
520 }
521
522 /**
523 * Extracts the given named values into an array.
524 * If no arguments are given, returns all input values.
525 * No transformation is performed on the values.
526 *
527 * @return array
528 */
529 public function getValues() {
530 $names = func_get_args();
531 if ( count( $names ) == 0 ) {
532 $names = array_keys( $this->data );
533 }
534
535 $retVal = array();
536 foreach ( $names as $name ) {
537 $value = $this->getGPCVal( $this->data, $name, null );
538 if ( !is_null( $value ) ) {
539 $retVal[$name] = $value;
540 }
541 }
542 return $retVal;
543 }
544
545 /**
546 * Returns the names of all input values excluding those in $exclude.
547 *
548 * @param $exclude Array
549 * @return array
550 */
551 public function getValueNames( $exclude = array() ) {
552 return array_diff( array_keys( $this->getValues() ), $exclude );
553 }
554
555 /**
556 * Get the values passed in the query string.
557 * No transformation is performed on the values.
558 *
559 * @return Array
560 */
561 public function getQueryValues() {
562 return $_GET;
563 }
564
565 /**
566 * Get the HTTP method used for this request.
567 *
568 * @return String
569 */
570 public function getMethod() {
571 return isset( $_SERVER['REQUEST_METHOD'] ) ? $_SERVER['REQUEST_METHOD'] : 'GET';
572 }
573
574 /**
575 * Returns true if the present request was reached by a POST operation,
576 * false otherwise (GET, HEAD, or command-line).
577 *
578 * Note that values retrieved by the object may come from the
579 * GET URL etc even on a POST request.
580 *
581 * @return Boolean
582 */
583 public function wasPosted() {
584 return $this->getMethod() == 'POST';
585 }
586
587 /**
588 * Returns true if there is a session cookie set.
589 * This does not necessarily mean that the user is logged in!
590 *
591 * If you want to check for an open session, use session_id()
592 * instead; that will also tell you if the session was opened
593 * during the current request (in which case the cookie will
594 * be sent back to the client at the end of the script run).
595 *
596 * @return Boolean
597 */
598 public function checkSessionCookie() {
599 return isset( $_COOKIE[ session_name() ] );
600 }
601
602 /**
603 * Get a cookie from the $_COOKIE jar
604 *
605 * @param $key String: the name of the cookie
606 * @param $prefix String: a prefix to use for the cookie name, if not $wgCookiePrefix
607 * @param $default Mixed: what to return if the value isn't found
608 * @return Mixed: cookie value or $default if the cookie not set
609 */
610 public function getCookie( $key, $prefix = null, $default = null ) {
611 if( $prefix === null ) {
612 global $wgCookiePrefix;
613 $prefix = $wgCookiePrefix;
614 }
615 return $this->getGPCVal( $_COOKIE, $prefix . $key , $default );
616 }
617
618 /**
619 * Return the path and query string portion of the request URI.
620 * This will be suitable for use as a relative link in HTML output.
621 *
622 * @throws MWException
623 * @return String
624 */
625 public function getRequestURL() {
626 if( isset( $_SERVER['REQUEST_URI'] ) && strlen( $_SERVER['REQUEST_URI'] ) ) {
627 $base = $_SERVER['REQUEST_URI'];
628 } elseif ( isset( $_SERVER['HTTP_X_ORIGINAL_URL'] ) && strlen( $_SERVER['HTTP_X_ORIGINAL_URL'] ) ) {
629 // Probably IIS; doesn't set REQUEST_URI
630 $base = $_SERVER['HTTP_X_ORIGINAL_URL'];
631 } elseif( isset( $_SERVER['SCRIPT_NAME'] ) ) {
632 $base = $_SERVER['SCRIPT_NAME'];
633 if( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
634 $base .= '?' . $_SERVER['QUERY_STRING'];
635 }
636 } else {
637 // This shouldn't happen!
638 throw new MWException( "Web server doesn't provide either " .
639 "REQUEST_URI, HTTP_X_ORIGINAL_URL or SCRIPT_NAME. Report details " .
640 "of your web server configuration to http://bugzilla.wikimedia.org/" );
641 }
642 // User-agents should not send a fragment with the URI, but
643 // if they do, and the web server passes it on to us, we
644 // need to strip it or we get false-positive redirect loops
645 // or weird output URLs
646 $hash = strpos( $base, '#' );
647 if( $hash !== false ) {
648 $base = substr( $base, 0, $hash );
649 }
650 if( $base[0] == '/' ) {
651 return $base;
652 } else {
653 // We may get paths with a host prepended; strip it.
654 return preg_replace( '!^[^:]+://[^/]+/!', '/', $base );
655 }
656 }
657
658 /**
659 * Return the request URI with the canonical service and hostname, path,
660 * and query string. This will be suitable for use as an absolute link
661 * in HTML or other output.
662 *
663 * If $wgServer is protocol-relative, this will return a fully
664 * qualified URL with the protocol that was used for this request.
665 *
666 * @return String
667 */
668 public function getFullRequestURL() {
669 return wfExpandUrl( $this->getRequestURL(), PROTO_CURRENT );
670 }
671
672 /**
673 * Take an arbitrary query and rewrite the present URL to include it
674 * @param $query String: query string fragment; do not include initial '?'
675 *
676 * @return String
677 */
678 public function appendQuery( $query ) {
679 return $this->appendQueryArray( wfCgiToArray( $query ) );
680 }
681
682 /**
683 * HTML-safe version of appendQuery().
684 * @deprecated: Deprecated in 1.20, warnings in 1.21, remove in 1.22.
685 *
686 * @param $query String: query string fragment; do not include initial '?'
687 * @return String
688 */
689 public function escapeAppendQuery( $query ) {
690 return htmlspecialchars( $this->appendQuery( $query ) );
691 }
692
693 /**
694 * @param $key
695 * @param $value
696 * @param $onlyquery bool
697 * @return String
698 */
699 public function appendQueryValue( $key, $value, $onlyquery = false ) {
700 return $this->appendQueryArray( array( $key => $value ), $onlyquery );
701 }
702
703 /**
704 * Appends or replaces value of query variables.
705 *
706 * @param $array Array of values to replace/add to query
707 * @param $onlyquery Bool: whether to only return the query string and not
708 * the complete URL
709 * @return String
710 */
711 public function appendQueryArray( $array, $onlyquery = false ) {
712 global $wgTitle;
713 $newquery = $this->getQueryValues();
714 unset( $newquery['title'] );
715 $newquery = array_merge( $newquery, $array );
716 $query = wfArrayToCGI( $newquery );
717 return $onlyquery ? $query : $wgTitle->getLocalURL( $query );
718 }
719
720 /**
721 * Check for limit and offset parameters on the input, and return sensible
722 * defaults if not given. The limit must be positive and is capped at 5000.
723 * Offset must be positive but is not capped.
724 *
725 * @param $deflimit Integer: limit to use if no input and the user hasn't set the option.
726 * @param $optionname String: to specify an option other than rclimit to pull from.
727 * @return array first element is limit, second is offset
728 */
729 public function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
730 global $wgUser;
731
732 $limit = $this->getInt( 'limit', 0 );
733 if( $limit < 0 ) {
734 $limit = 0;
735 }
736 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
737 $limit = (int)$wgUser->getOption( $optionname );
738 }
739 if( $limit <= 0 ) {
740 $limit = $deflimit;
741 }
742 if( $limit > 5000 ) {
743 $limit = 5000; # We have *some* limits...
744 }
745
746 $offset = $this->getInt( 'offset', 0 );
747 if( $offset < 0 ) {
748 $offset = 0;
749 }
750
751 return array( $limit, $offset );
752 }
753
754 /**
755 * Return the path to the temporary file where PHP has stored the upload.
756 *
757 * @param $key String:
758 * @return string or NULL if no such file.
759 */
760 public function getFileTempname( $key ) {
761 $file = new WebRequestUpload( $this, $key );
762 return $file->getTempName();
763 }
764
765 /**
766 * Return the size of the upload, or 0.
767 *
768 * @deprecated since 1.17
769 * @param $key String:
770 * @return integer
771 */
772 public function getFileSize( $key ) {
773 wfDeprecated( __METHOD__, '1.17' );
774 $file = new WebRequestUpload( $this, $key );
775 return $file->getSize();
776 }
777
778 /**
779 * Return the upload error or 0
780 *
781 * @param $key String:
782 * @return integer
783 */
784 public function getUploadError( $key ) {
785 $file = new WebRequestUpload( $this, $key );
786 return $file->getError();
787 }
788
789 /**
790 * Return the original filename of the uploaded file, as reported by
791 * the submitting user agent. HTML-style character entities are
792 * interpreted and normalized to Unicode normalization form C, in part
793 * to deal with weird input from Safari with non-ASCII filenames.
794 *
795 * Other than this the name is not verified for being a safe filename.
796 *
797 * @param $key String:
798 * @return string or NULL if no such file.
799 */
800 public function getFileName( $key ) {
801 $file = new WebRequestUpload( $this, $key );
802 return $file->getName();
803 }
804
805 /**
806 * Return a WebRequestUpload object corresponding to the key
807 *
808 * @param $key string
809 * @return WebRequestUpload
810 */
811 public function getUpload( $key ) {
812 return new WebRequestUpload( $this, $key );
813 }
814
815 /**
816 * Return a handle to WebResponse style object, for setting cookies,
817 * headers and other stuff, for Request being worked on.
818 *
819 * @return WebResponse
820 */
821 public function response() {
822 /* Lazy initialization of response object for this request */
823 if ( !is_object( $this->response ) ) {
824 $class = ( $this instanceof FauxRequest ) ? 'FauxResponse' : 'WebResponse';
825 $this->response = new $class();
826 }
827 return $this->response;
828 }
829
830 /**
831 * Initialise the header list
832 */
833 private function initHeaders() {
834 if ( count( $this->headers ) ) {
835 return;
836 }
837
838 if ( function_exists( 'apache_request_headers' ) ) {
839 foreach ( apache_request_headers() as $tempName => $tempValue ) {
840 $this->headers[ strtoupper( $tempName ) ] = $tempValue;
841 }
842 } else {
843 foreach ( $_SERVER as $name => $value ) {
844 if ( substr( $name, 0, 5 ) === 'HTTP_' ) {
845 $name = str_replace( '_', '-', substr( $name, 5 ) );
846 $this->headers[$name] = $value;
847 } elseif ( $name === 'CONTENT_LENGTH' ) {
848 $this->headers['CONTENT-LENGTH'] = $value;
849 }
850 }
851 }
852 }
853
854 /**
855 * Get an array containing all request headers
856 *
857 * @return Array mapping header name to its value
858 */
859 public function getAllHeaders() {
860 $this->initHeaders();
861 return $this->headers;
862 }
863
864 /**
865 * Get a request header, or false if it isn't set
866 * @param $name String: case-insensitive header name
867 *
868 * @return string|bool False on failure
869 */
870 public function getHeader( $name ) {
871 $this->initHeaders();
872 $name = strtoupper( $name );
873 if ( isset( $this->headers[$name] ) ) {
874 return $this->headers[$name];
875 } else {
876 return false;
877 }
878 }
879
880 /**
881 * Get data from $_SESSION
882 *
883 * @param $key String: name of key in $_SESSION
884 * @return Mixed
885 */
886 public function getSessionData( $key ) {
887 if( !isset( $_SESSION[$key] ) ) {
888 return null;
889 }
890 return $_SESSION[$key];
891 }
892
893 /**
894 * Set session data
895 *
896 * @param $key String: name of key in $_SESSION
897 * @param $data Mixed
898 */
899 public function setSessionData( $key, $data ) {
900 $_SESSION[$key] = $data;
901 }
902
903 /**
904 * Check if Internet Explorer will detect an incorrect cache extension in
905 * PATH_INFO or QUERY_STRING. If the request can't be allowed, show an error
906 * message or redirect to a safer URL. Returns true if the URL is OK, and
907 * false if an error message has been shown and the request should be aborted.
908 *
909 * @param $extWhitelist array
910 * @throws HttpError
911 * @return bool
912 */
913 public function checkUrlExtension( $extWhitelist = array() ) {
914 global $wgScriptExtension;
915 $extWhitelist[] = ltrim( $wgScriptExtension, '.' );
916 if ( IEUrlExtension::areServerVarsBad( $_SERVER, $extWhitelist ) ) {
917 if ( !$this->wasPosted() ) {
918 $newUrl = IEUrlExtension::fixUrlForIE6(
919 $this->getFullRequestURL(), $extWhitelist );
920 if ( $newUrl !== false ) {
921 $this->doSecurityRedirect( $newUrl );
922 return false;
923 }
924 }
925 throw new HttpError( 403,
926 'Invalid file extension found in the path info or query string.' );
927 }
928 return true;
929 }
930
931 /**
932 * Attempt to redirect to a URL with a QUERY_STRING that's not dangerous in
933 * IE 6. Returns true if it was successful, false otherwise.
934 *
935 * @param $url string
936 * @return bool
937 */
938 protected function doSecurityRedirect( $url ) {
939 header( 'Location: ' . $url );
940 header( 'Content-Type: text/html' );
941 $encUrl = htmlspecialchars( $url );
942 echo <<<HTML
943 <html>
944 <head>
945 <title>Security redirect</title>
946 </head>
947 <body>
948 <h1>Security redirect</h1>
949 <p>
950 We can't serve non-HTML content from the URL you have requested, because
951 Internet Explorer would interpret it as an incorrect and potentially dangerous
952 content type.</p>
953 <p>Instead, please use <a href="$encUrl">this URL</a>, which is the same as the URL you have requested, except that
954 "&amp;*" is appended. This prevents Internet Explorer from seeing a bogus file
955 extension.
956 </p>
957 </body>
958 </html>
959 HTML;
960 echo "\n";
961 return true;
962 }
963
964 /**
965 * Returns true if the PATH_INFO ends with an extension other than a script
966 * extension. This could confuse IE for scripts that send arbitrary data which
967 * is not HTML but may be detected as such.
968 *
969 * Various past attempts to use the URL to make this check have generally
970 * run up against the fact that CGI does not provide a standard method to
971 * determine the URL. PATH_INFO may be mangled (e.g. if cgi.fix_pathinfo=0),
972 * but only by prefixing it with the script name and maybe some other stuff,
973 * the extension is not mangled. So this should be a reasonably portable
974 * way to perform this security check.
975 *
976 * Also checks for anything that looks like a file extension at the end of
977 * QUERY_STRING, since IE 6 and earlier will use this to get the file type
978 * if there was no dot before the question mark (bug 28235).
979 *
980 * @deprecated Use checkUrlExtension().
981 *
982 * @param $extWhitelist array
983 *
984 * @return bool
985 */
986 public function isPathInfoBad( $extWhitelist = array() ) {
987 wfDeprecated( __METHOD__, '1.17' );
988 global $wgScriptExtension;
989 $extWhitelist[] = ltrim( $wgScriptExtension, '.' );
990 return IEUrlExtension::areServerVarsBad( $_SERVER, $extWhitelist );
991 }
992
993 /**
994 * Parse the Accept-Language header sent by the client into an array
995 * @return array array( languageCode => q-value ) sorted by q-value in descending order then
996 * appearing time in the header in ascending order.
997 * May contain the "language" '*', which applies to languages other than those explicitly listed.
998 * This is aligned with rfc2616 section 14.4
999 * Preference for earlier languages appears in rfc3282 as an extension to HTTP/1.1.
1000 */
1001 public function getAcceptLang() {
1002 // Modified version of code found at http://www.thefutureoftheweb.com/blog/use-accept-language-header
1003 $acceptLang = $this->getHeader( 'Accept-Language' );
1004 if ( !$acceptLang ) {
1005 return array();
1006 }
1007
1008 // Return the language codes in lower case
1009 $acceptLang = strtolower( $acceptLang );
1010
1011 // Break up string into pieces (languages and q factors)
1012 $lang_parse = null;
1013 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})?)?)?/',
1014 $acceptLang, $lang_parse );
1015
1016 if ( !count( $lang_parse[1] ) ) {
1017 return array();
1018 }
1019
1020 $langcodes = $lang_parse[1];
1021 $qvalues = $lang_parse[4];
1022 $indices = range( 0, count( $lang_parse[1] ) - 1 );
1023
1024 // Set default q factor to 1
1025 foreach ( $indices as $index ) {
1026 if ( $qvalues[$index] === '' ) {
1027 $qvalues[$index] = 1;
1028 } elseif ( $qvalues[$index] == 0 ) {
1029 unset( $langcodes[$index], $qvalues[$index], $indices[$index] );
1030 }
1031 }
1032
1033 // Sort list. First by $qvalues, then by order. Reorder $langcodes the same way
1034 array_multisort( $qvalues, SORT_DESC, SORT_NUMERIC, $indices, $langcodes );
1035
1036 // Create a list like "en" => 0.8
1037 $langs = array_combine( $langcodes, $qvalues );
1038
1039 return $langs;
1040 }
1041
1042 /**
1043 * Fetch the raw IP from the request
1044 *
1045 * @since 1.19
1046 *
1047 * @return String
1048 */
1049 protected function getRawIP() {
1050 if ( isset( $_SERVER['REMOTE_ADDR'] ) ) {
1051 return IP::canonicalize( $_SERVER['REMOTE_ADDR'] );
1052 } else {
1053 return null;
1054 }
1055 }
1056
1057 /**
1058 * Work out the IP address based on various globals
1059 * For trusted proxies, use the XFF client IP (first of the chain)
1060 *
1061 * @since 1.19
1062 *
1063 * @throws MWException
1064 * @return string
1065 */
1066 public function getIP() {
1067 global $wgUsePrivateIPs;
1068
1069 # Return cached result
1070 if ( $this->ip !== null ) {
1071 return $this->ip;
1072 }
1073
1074 # collect the originating ips
1075 $ip = $this->getRawIP();
1076
1077 # Append XFF
1078 $forwardedFor = $this->getHeader( 'X-Forwarded-For' );
1079 if ( $forwardedFor !== false ) {
1080 $ipchain = array_map( 'trim', explode( ',', $forwardedFor ) );
1081 $ipchain = array_reverse( $ipchain );
1082 if ( $ip ) {
1083 array_unshift( $ipchain, $ip );
1084 }
1085
1086 # Step through XFF list and find the last address in the list which is a trusted server
1087 # Set $ip to the IP address given by that trusted server, unless the address is not sensible (e.g. private)
1088 foreach ( $ipchain as $i => $curIP ) {
1089 $curIP = IP::canonicalize( $curIP );
1090 if ( wfIsTrustedProxy( $curIP ) ) {
1091 if ( isset( $ipchain[$i + 1] ) ) {
1092 if ( $wgUsePrivateIPs || IP::isPublic( $ipchain[$i + 1 ] ) ) {
1093 $ip = $ipchain[$i + 1];
1094 }
1095 }
1096 } else {
1097 break;
1098 }
1099 }
1100 }
1101
1102 # Allow extensions to improve our guess
1103 wfRunHooks( 'GetIP', array( &$ip ) );
1104
1105 if ( !$ip ) {
1106 throw new MWException( "Unable to determine IP" );
1107 }
1108
1109 wfDebug( "IP: $ip\n" );
1110 $this->ip = $ip;
1111 return $ip;
1112 }
1113 }
1114
1115 /**
1116 * Object to access the $_FILES array
1117 */
1118 class WebRequestUpload {
1119 protected $request;
1120 protected $doesExist;
1121 protected $fileInfo;
1122
1123 /**
1124 * Constructor. Should only be called by WebRequest
1125 *
1126 * @param $request WebRequest The associated request
1127 * @param $key string Key in $_FILES array (name of form field)
1128 */
1129 public function __construct( $request, $key ) {
1130 $this->request = $request;
1131 $this->doesExist = isset( $_FILES[$key] );
1132 if ( $this->doesExist ) {
1133 $this->fileInfo = $_FILES[$key];
1134 }
1135 }
1136
1137 /**
1138 * Return whether a file with this name was uploaded.
1139 *
1140 * @return bool
1141 */
1142 public function exists() {
1143 return $this->doesExist;
1144 }
1145
1146 /**
1147 * Return the original filename of the uploaded file
1148 *
1149 * @return mixed Filename or null if non-existent
1150 */
1151 public function getName() {
1152 if ( !$this->exists() ) {
1153 return null;
1154 }
1155
1156 global $wgContLang;
1157 $name = $this->fileInfo['name'];
1158
1159 # Safari sends filenames in HTML-encoded Unicode form D...
1160 # Horrid and evil! Let's try to make some kind of sense of it.
1161 $name = Sanitizer::decodeCharReferences( $name );
1162 $name = $wgContLang->normalize( $name );
1163 wfDebug( __METHOD__ . ": {$this->fileInfo['name']} normalized to '$name'\n" );
1164 return $name;
1165 }
1166
1167 /**
1168 * Return the file size of the uploaded file
1169 *
1170 * @return int File size or zero if non-existent
1171 */
1172 public function getSize() {
1173 if ( !$this->exists() ) {
1174 return 0;
1175 }
1176
1177 return $this->fileInfo['size'];
1178 }
1179
1180 /**
1181 * Return the path to the temporary file
1182 *
1183 * @return mixed Path or null if non-existent
1184 */
1185 public function getTempName() {
1186 if ( !$this->exists() ) {
1187 return null;
1188 }
1189
1190 return $this->fileInfo['tmp_name'];
1191 }
1192
1193 /**
1194 * Return the upload error. See link for explanation
1195 * http://www.php.net/manual/en/features.file-upload.errors.php
1196 *
1197 * @return int One of the UPLOAD_ constants, 0 if non-existent
1198 */
1199 public function getError() {
1200 if ( !$this->exists() ) {
1201 return 0; # UPLOAD_ERR_OK
1202 }
1203
1204 return $this->fileInfo['error'];
1205 }
1206
1207 /**
1208 * Returns whether this upload failed because of overflow of a maximum set
1209 * in php.ini
1210 *
1211 * @return bool
1212 */
1213 public function isIniSizeOverflow() {
1214 if ( $this->getError() == UPLOAD_ERR_INI_SIZE ) {
1215 # PHP indicated that upload_max_filesize is exceeded
1216 return true;
1217 }
1218
1219 $contentLength = $this->request->getHeader( 'CONTENT_LENGTH' );
1220 if ( $contentLength > wfShorthandToInteger( ini_get( 'post_max_size' ) ) ) {
1221 # post_max_size is exceeded
1222 return true;
1223 }
1224
1225 return false;
1226 }
1227 }
1228
1229 /**
1230 * WebRequest clone which takes values from a provided array.
1231 *
1232 * @ingroup HTTP
1233 */
1234 class FauxRequest extends WebRequest {
1235 private $wasPosted = false;
1236 private $session = array();
1237
1238 /**
1239 * @param $data Array of *non*-urlencoded key => value pairs, the
1240 * fake GET/POST values
1241 * @param $wasPosted Bool: whether to treat the data as POST
1242 * @param $session Mixed: session array or null
1243 * @throws MWException
1244 */
1245 public function __construct( $data = array(), $wasPosted = false, $session = null ) {
1246 if( is_array( $data ) ) {
1247 $this->data = $data;
1248 } else {
1249 throw new MWException( "FauxRequest() got bogus data" );
1250 }
1251 $this->wasPosted = $wasPosted;
1252 if( $session )
1253 $this->session = $session;
1254 }
1255
1256 /**
1257 * @param $method string
1258 * @throws MWException
1259 */
1260 private function notImplemented( $method ) {
1261 throw new MWException( "{$method}() not implemented" );
1262 }
1263
1264 /**
1265 * @param $name string
1266 * @param $default string
1267 * @return string
1268 */
1269 public function getText( $name, $default = '' ) {
1270 # Override; don't recode since we're using internal data
1271 return (string)$this->getVal( $name, $default );
1272 }
1273
1274 /**
1275 * @return Array
1276 */
1277 public function getValues() {
1278 return $this->data;
1279 }
1280
1281 /**
1282 * @return array
1283 */
1284 public function getQueryValues() {
1285 if ( $this->wasPosted ) {
1286 return array();
1287 } else {
1288 return $this->data;
1289 }
1290 }
1291
1292 public function getMethod() {
1293 return $this->wasPosted ? 'POST' : 'GET';
1294 }
1295
1296 /**
1297 * @return bool
1298 */
1299 public function wasPosted() {
1300 return $this->wasPosted;
1301 }
1302
1303 public function checkSessionCookie() {
1304 return false;
1305 }
1306
1307 public function getRequestURL() {
1308 $this->notImplemented( __METHOD__ );
1309 }
1310
1311 /**
1312 * @param $name
1313 * @return bool|string
1314 */
1315 public function getHeader( $name ) {
1316 return isset( $this->headers[$name] ) ? $this->headers[$name] : false;
1317 }
1318
1319 /**
1320 * @param $name string
1321 * @param $val string
1322 */
1323 public function setHeader( $name, $val ) {
1324 $this->headers[$name] = $val;
1325 }
1326
1327 /**
1328 * @param $key
1329 * @return mixed
1330 */
1331 public function getSessionData( $key ) {
1332 if( isset( $this->session[$key] ) )
1333 return $this->session[$key];
1334 }
1335
1336 /**
1337 * @param $key
1338 * @param $data
1339 */
1340 public function setSessionData( $key, $data ) {
1341 $this->session[$key] = $data;
1342 }
1343
1344 /**
1345 * @return array|Mixed|null
1346 */
1347 public function getSessionArray() {
1348 return $this->session;
1349 }
1350
1351 /**
1352 * @param array $extWhitelist
1353 * @return bool
1354 */
1355 public function isPathInfoBad( $extWhitelist = array() ) {
1356 return false;
1357 }
1358
1359 /**
1360 * @param array $extWhitelist
1361 * @return bool
1362 */
1363 public function checkUrlExtension( $extWhitelist = array() ) {
1364 return true;
1365 }
1366
1367 /**
1368 * @return string
1369 */
1370 protected function getRawIP() {
1371 return '127.0.0.1';
1372 }
1373 }
1374
1375 /**
1376 * Similar to FauxRequest, but only fakes URL parameters and method
1377 * (POST or GET) and use the base request for the remaining stuff
1378 * (cookies, session and headers).
1379 *
1380 * @ingroup HTTP
1381 * @since 1.19
1382 */
1383 class DerivativeRequest extends FauxRequest {
1384 private $base;
1385
1386 public function __construct( WebRequest $base, $data, $wasPosted = false ) {
1387 $this->base = $base;
1388 parent::__construct( $data, $wasPosted );
1389 }
1390
1391 public function getCookie( $key, $prefix = null, $default = null ) {
1392 return $this->base->getCookie( $key, $prefix, $default );
1393 }
1394
1395 public function checkSessionCookie() {
1396 return $this->base->checkSessionCookie();
1397 }
1398
1399 public function getHeader( $name ) {
1400 return $this->base->getHeader( $name );
1401 }
1402
1403 public function getAllHeaders() {
1404 return $this->base->getAllHeaders();
1405 }
1406
1407 public function getSessionData( $key ) {
1408 return $this->base->getSessionData( $key );
1409 }
1410
1411 public function setSessionData( $key, $data ) {
1412 $this->base->setSessionData( $key, $data );
1413 }
1414
1415 public function getAcceptLang() {
1416 return $this->base->getAcceptLang();
1417 }
1418
1419 public function getIP() {
1420 return $this->base->getIP();
1421 }
1422 }