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