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