(bug 19195) Make user IDs more readily available with the API
[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 *
675 * @param $query String: query string fragment; do not include initial '?'
676 * @return String
677 */
678 public function escapeAppendQuery( $query ) {
679 return htmlspecialchars( $this->appendQuery( $query ) );
680 }
681
682 /**
683 * @param $key
684 * @param $value
685 * @param $onlyquery bool
686 * @return String
687 */
688 public function appendQueryValue( $key, $value, $onlyquery = false ) {
689 return $this->appendQueryArray( array( $key => $value ), $onlyquery );
690 }
691
692 /**
693 * Appends or replaces value of query variables.
694 *
695 * @param $array Array of values to replace/add to query
696 * @param $onlyquery Bool: whether to only return the query string and not
697 * the complete URL
698 * @return String
699 */
700 public function appendQueryArray( $array, $onlyquery = false ) {
701 global $wgTitle;
702 $newquery = $this->getQueryValues();
703 unset( $newquery['title'] );
704 $newquery = array_merge( $newquery, $array );
705 $query = wfArrayToCGI( $newquery );
706 return $onlyquery ? $query : $wgTitle->getLocalURL( $query );
707 }
708
709 /**
710 * Check for limit and offset parameters on the input, and return sensible
711 * defaults if not given. The limit must be positive and is capped at 5000.
712 * Offset must be positive but is not capped.
713 *
714 * @param $deflimit Integer: limit to use if no input and the user hasn't set the option.
715 * @param $optionname String: to specify an option other than rclimit to pull from.
716 * @return array first element is limit, second is offset
717 */
718 public function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
719 global $wgUser;
720
721 $limit = $this->getInt( 'limit', 0 );
722 if( $limit < 0 ) {
723 $limit = 0;
724 }
725 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
726 $limit = (int)$wgUser->getOption( $optionname );
727 }
728 if( $limit <= 0 ) {
729 $limit = $deflimit;
730 }
731 if( $limit > 5000 ) {
732 $limit = 5000; # We have *some* limits...
733 }
734
735 $offset = $this->getInt( 'offset', 0 );
736 if( $offset < 0 ) {
737 $offset = 0;
738 }
739
740 return array( $limit, $offset );
741 }
742
743 /**
744 * Return the path to the temporary file where PHP has stored the upload.
745 *
746 * @param $key String:
747 * @return string or NULL if no such file.
748 */
749 public function getFileTempname( $key ) {
750 $file = new WebRequestUpload( $this, $key );
751 return $file->getTempName();
752 }
753
754 /**
755 * Return the size of the upload, or 0.
756 *
757 * @deprecated since 1.17
758 * @param $key String:
759 * @return integer
760 */
761 public function getFileSize( $key ) {
762 wfDeprecated( __METHOD__, '1.17' );
763 $file = new WebRequestUpload( $this, $key );
764 return $file->getSize();
765 }
766
767 /**
768 * Return the upload error or 0
769 *
770 * @param $key String:
771 * @return integer
772 */
773 public function getUploadError( $key ) {
774 $file = new WebRequestUpload( $this, $key );
775 return $file->getError();
776 }
777
778 /**
779 * Return the original filename of the uploaded file, as reported by
780 * the submitting user agent. HTML-style character entities are
781 * interpreted and normalized to Unicode normalization form C, in part
782 * to deal with weird input from Safari with non-ASCII filenames.
783 *
784 * Other than this the name is not verified for being a safe filename.
785 *
786 * @param $key String:
787 * @return string or NULL if no such file.
788 */
789 public function getFileName( $key ) {
790 $file = new WebRequestUpload( $this, $key );
791 return $file->getName();
792 }
793
794 /**
795 * Return a WebRequestUpload object corresponding to the key
796 *
797 * @param $key string
798 * @return WebRequestUpload
799 */
800 public function getUpload( $key ) {
801 return new WebRequestUpload( $this, $key );
802 }
803
804 /**
805 * Return a handle to WebResponse style object, for setting cookies,
806 * headers and other stuff, for Request being worked on.
807 *
808 * @return WebResponse
809 */
810 public function response() {
811 /* Lazy initialization of response object for this request */
812 if ( !is_object( $this->response ) ) {
813 $class = ( $this instanceof FauxRequest ) ? 'FauxResponse' : 'WebResponse';
814 $this->response = new $class();
815 }
816 return $this->response;
817 }
818
819 /**
820 * Initialise the header list
821 */
822 private function initHeaders() {
823 if ( count( $this->headers ) ) {
824 return;
825 }
826
827 if ( function_exists( 'apache_request_headers' ) ) {
828 foreach ( apache_request_headers() as $tempName => $tempValue ) {
829 $this->headers[ strtoupper( $tempName ) ] = $tempValue;
830 }
831 } else {
832 foreach ( $_SERVER as $name => $value ) {
833 if ( substr( $name, 0, 5 ) === 'HTTP_' ) {
834 $name = str_replace( '_', '-', substr( $name, 5 ) );
835 $this->headers[$name] = $value;
836 } elseif ( $name === 'CONTENT_LENGTH' ) {
837 $this->headers['CONTENT-LENGTH'] = $value;
838 }
839 }
840 }
841 }
842
843 /**
844 * Get an array containing all request headers
845 *
846 * @return Array mapping header name to its value
847 */
848 public function getAllHeaders() {
849 $this->initHeaders();
850 return $this->headers;
851 }
852
853 /**
854 * Get a request header, or false if it isn't set
855 * @param $name String: case-insensitive header name
856 *
857 * @return string|bool False on failure
858 */
859 public function getHeader( $name ) {
860 $this->initHeaders();
861 $name = strtoupper( $name );
862 if ( isset( $this->headers[$name] ) ) {
863 return $this->headers[$name];
864 } else {
865 return false;
866 }
867 }
868
869 /**
870 * Get data from $_SESSION
871 *
872 * @param $key String: name of key in $_SESSION
873 * @return Mixed
874 */
875 public function getSessionData( $key ) {
876 if( !isset( $_SESSION[$key] ) ) {
877 return null;
878 }
879 return $_SESSION[$key];
880 }
881
882 /**
883 * Set session data
884 *
885 * @param $key String: name of key in $_SESSION
886 * @param $data Mixed
887 */
888 public function setSessionData( $key, $data ) {
889 $_SESSION[$key] = $data;
890 }
891
892 /**
893 * Check if Internet Explorer will detect an incorrect cache extension in
894 * PATH_INFO or QUERY_STRING. If the request can't be allowed, show an error
895 * message or redirect to a safer URL. Returns true if the URL is OK, and
896 * false if an error message has been shown and the request should be aborted.
897 *
898 * @param $extWhitelist array
899 * @return bool
900 */
901 public function checkUrlExtension( $extWhitelist = array() ) {
902 global $wgScriptExtension;
903 $extWhitelist[] = ltrim( $wgScriptExtension, '.' );
904 if ( IEUrlExtension::areServerVarsBad( $_SERVER, $extWhitelist ) ) {
905 if ( !$this->wasPosted() ) {
906 $newUrl = IEUrlExtension::fixUrlForIE6(
907 $this->getFullRequestURL(), $extWhitelist );
908 if ( $newUrl !== false ) {
909 $this->doSecurityRedirect( $newUrl );
910 return false;
911 }
912 }
913 throw new HttpError( 403,
914 'Invalid file extension found in the path info or query string.' );
915 }
916 return true;
917 }
918
919 /**
920 * Attempt to redirect to a URL with a QUERY_STRING that's not dangerous in
921 * IE 6. Returns true if it was successful, false otherwise.
922 *
923 * @param $url string
924 * @return bool
925 */
926 protected function doSecurityRedirect( $url ) {
927 header( 'Location: ' . $url );
928 header( 'Content-Type: text/html' );
929 $encUrl = htmlspecialchars( $url );
930 echo <<<HTML
931 <html>
932 <head>
933 <title>Security redirect</title>
934 </head>
935 <body>
936 <h1>Security redirect</h1>
937 <p>
938 We can't serve non-HTML content from the URL you have requested, because
939 Internet Explorer would interpret it as an incorrect and potentially dangerous
940 content type.</p>
941 <p>Instead, please use <a href="$encUrl">this URL</a>, which is the same as the URL you have requested, except that
942 "&amp;*" is appended. This prevents Internet Explorer from seeing a bogus file
943 extension.
944 </p>
945 </body>
946 </html>
947 HTML;
948 echo "\n";
949 return true;
950 }
951
952 /**
953 * Returns true if the PATH_INFO ends with an extension other than a script
954 * extension. This could confuse IE for scripts that send arbitrary data which
955 * is not HTML but may be detected as such.
956 *
957 * Various past attempts to use the URL to make this check have generally
958 * run up against the fact that CGI does not provide a standard method to
959 * determine the URL. PATH_INFO may be mangled (e.g. if cgi.fix_pathinfo=0),
960 * but only by prefixing it with the script name and maybe some other stuff,
961 * the extension is not mangled. So this should be a reasonably portable
962 * way to perform this security check.
963 *
964 * Also checks for anything that looks like a file extension at the end of
965 * QUERY_STRING, since IE 6 and earlier will use this to get the file type
966 * if there was no dot before the question mark (bug 28235).
967 *
968 * @deprecated Use checkUrlExtension().
969 *
970 * @param $extWhitelist array
971 *
972 * @return bool
973 */
974 public function isPathInfoBad( $extWhitelist = array() ) {
975 wfDeprecated( __METHOD__, '1.17' );
976 global $wgScriptExtension;
977 $extWhitelist[] = ltrim( $wgScriptExtension, '.' );
978 return IEUrlExtension::areServerVarsBad( $_SERVER, $extWhitelist );
979 }
980
981 /**
982 * Parse the Accept-Language header sent by the client into an array
983 * @return array array( languageCode => q-value ) sorted by q-value in descending order
984 * May contain the "language" '*', which applies to languages other than those explicitly listed.
985 * This is aligned with rfc2616 section 14.4
986 */
987 public function getAcceptLang() {
988 // Modified version of code found at http://www.thefutureoftheweb.com/blog/use-accept-language-header
989 $acceptLang = $this->getHeader( 'Accept-Language' );
990 if ( !$acceptLang ) {
991 return array();
992 }
993
994 // Return the language codes in lower case
995 $acceptLang = strtolower( $acceptLang );
996
997 // Break up string into pieces (languages and q factors)
998 $lang_parse = null;
999 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})?)?)?/',
1000 $acceptLang, $lang_parse );
1001
1002 if ( !count( $lang_parse[1] ) ) {
1003 return array();
1004 }
1005
1006 // Create a list like "en" => 0.8
1007 $langs = array_combine( $lang_parse[1], $lang_parse[4] );
1008 // Set default q factor to 1
1009 foreach ( $langs as $lang => $val ) {
1010 if ( $val === '' ) {
1011 $langs[$lang] = 1;
1012 } elseif ( $val == 0 ) {
1013 unset($langs[$lang]);
1014 }
1015 }
1016
1017 // Sort list
1018 arsort( $langs, SORT_NUMERIC );
1019 return $langs;
1020 }
1021
1022 /**
1023 * Fetch the raw IP from the request
1024 *
1025 * @since 1.19
1026 *
1027 * @return String
1028 */
1029 protected function getRawIP() {
1030 if ( isset( $_SERVER['REMOTE_ADDR'] ) ) {
1031 return IP::canonicalize( $_SERVER['REMOTE_ADDR'] );
1032 } else {
1033 return null;
1034 }
1035 }
1036
1037 /**
1038 * Work out the IP address based on various globals
1039 * For trusted proxies, use the XFF client IP (first of the chain)
1040 *
1041 * @since 1.19
1042 *
1043 * @return string
1044 */
1045 public function getIP() {
1046 global $wgUsePrivateIPs;
1047
1048 # Return cached result
1049 if ( $this->ip !== null ) {
1050 return $this->ip;
1051 }
1052
1053 # collect the originating ips
1054 $ip = $this->getRawIP();
1055
1056 # Append XFF
1057 $forwardedFor = $this->getHeader( 'X-Forwarded-For' );
1058 if ( $forwardedFor !== false ) {
1059 $ipchain = array_map( 'trim', explode( ',', $forwardedFor ) );
1060 $ipchain = array_reverse( $ipchain );
1061 if ( $ip ) {
1062 array_unshift( $ipchain, $ip );
1063 }
1064
1065 # Step through XFF list and find the last address in the list which is a trusted server
1066 # Set $ip to the IP address given by that trusted server, unless the address is not sensible (e.g. private)
1067 foreach ( $ipchain as $i => $curIP ) {
1068 $curIP = IP::canonicalize( $curIP );
1069 if ( wfIsTrustedProxy( $curIP ) ) {
1070 if ( isset( $ipchain[$i + 1] ) ) {
1071 if ( $wgUsePrivateIPs || IP::isPublic( $ipchain[$i + 1 ] ) ) {
1072 $ip = $ipchain[$i + 1];
1073 }
1074 }
1075 } else {
1076 break;
1077 }
1078 }
1079 }
1080
1081 # Allow extensions to improve our guess
1082 wfRunHooks( 'GetIP', array( &$ip ) );
1083
1084 if ( !$ip ) {
1085 throw new MWException( "Unable to determine IP" );
1086 }
1087
1088 wfDebug( "IP: $ip\n" );
1089 $this->ip = $ip;
1090 return $ip;
1091 }
1092 }
1093
1094 /**
1095 * Object to access the $_FILES array
1096 */
1097 class WebRequestUpload {
1098 protected $request;
1099 protected $doesExist;
1100 protected $fileInfo;
1101
1102 /**
1103 * Constructor. Should only be called by WebRequest
1104 *
1105 * @param $request WebRequest The associated request
1106 * @param $key string Key in $_FILES array (name of form field)
1107 */
1108 public function __construct( $request, $key ) {
1109 $this->request = $request;
1110 $this->doesExist = isset( $_FILES[$key] );
1111 if ( $this->doesExist ) {
1112 $this->fileInfo = $_FILES[$key];
1113 }
1114 }
1115
1116 /**
1117 * Return whether a file with this name was uploaded.
1118 *
1119 * @return bool
1120 */
1121 public function exists() {
1122 return $this->doesExist;
1123 }
1124
1125 /**
1126 * Return the original filename of the uploaded file
1127 *
1128 * @return mixed Filename or null if non-existent
1129 */
1130 public function getName() {
1131 if ( !$this->exists() ) {
1132 return null;
1133 }
1134
1135 global $wgContLang;
1136 $name = $this->fileInfo['name'];
1137
1138 # Safari sends filenames in HTML-encoded Unicode form D...
1139 # Horrid and evil! Let's try to make some kind of sense of it.
1140 $name = Sanitizer::decodeCharReferences( $name );
1141 $name = $wgContLang->normalize( $name );
1142 wfDebug( __METHOD__ . ": {$this->fileInfo['name']} normalized to '$name'\n" );
1143 return $name;
1144 }
1145
1146 /**
1147 * Return the file size of the uploaded file
1148 *
1149 * @return int File size or zero if non-existent
1150 */
1151 public function getSize() {
1152 if ( !$this->exists() ) {
1153 return 0;
1154 }
1155
1156 return $this->fileInfo['size'];
1157 }
1158
1159 /**
1160 * Return the path to the temporary file
1161 *
1162 * @return mixed Path or null if non-existent
1163 */
1164 public function getTempName() {
1165 if ( !$this->exists() ) {
1166 return null;
1167 }
1168
1169 return $this->fileInfo['tmp_name'];
1170 }
1171
1172 /**
1173 * Return the upload error. See link for explanation
1174 * http://www.php.net/manual/en/features.file-upload.errors.php
1175 *
1176 * @return int One of the UPLOAD_ constants, 0 if non-existent
1177 */
1178 public function getError() {
1179 if ( !$this->exists() ) {
1180 return 0; # UPLOAD_ERR_OK
1181 }
1182
1183 return $this->fileInfo['error'];
1184 }
1185
1186 /**
1187 * Returns whether this upload failed because of overflow of a maximum set
1188 * in php.ini
1189 *
1190 * @return bool
1191 */
1192 public function isIniSizeOverflow() {
1193 if ( $this->getError() == UPLOAD_ERR_INI_SIZE ) {
1194 # PHP indicated that upload_max_filesize is exceeded
1195 return true;
1196 }
1197
1198 $contentLength = $this->request->getHeader( 'CONTENT_LENGTH' );
1199 if ( $contentLength > wfShorthandToInteger( ini_get( 'post_max_size' ) ) ) {
1200 # post_max_size is exceeded
1201 return true;
1202 }
1203
1204 return false;
1205 }
1206 }
1207
1208 /**
1209 * WebRequest clone which takes values from a provided array.
1210 *
1211 * @ingroup HTTP
1212 */
1213 class FauxRequest extends WebRequest {
1214 private $wasPosted = false;
1215 private $session = array();
1216
1217 /**
1218 * @param $data Array of *non*-urlencoded key => value pairs, the
1219 * fake GET/POST values
1220 * @param $wasPosted Bool: whether to treat the data as POST
1221 * @param $session Mixed: session array or null
1222 */
1223 public function __construct( $data = array(), $wasPosted = false, $session = null ) {
1224 if( is_array( $data ) ) {
1225 $this->data = $data;
1226 } else {
1227 throw new MWException( "FauxRequest() got bogus data" );
1228 }
1229 $this->wasPosted = $wasPosted;
1230 if( $session )
1231 $this->session = $session;
1232 }
1233
1234 /**
1235 * @param $method string
1236 * @throws MWException
1237 */
1238 private function notImplemented( $method ) {
1239 throw new MWException( "{$method}() not implemented" );
1240 }
1241
1242 /**
1243 * @param $name string
1244 * @param $default string
1245 * @return string
1246 */
1247 public function getText( $name, $default = '' ) {
1248 # Override; don't recode since we're using internal data
1249 return (string)$this->getVal( $name, $default );
1250 }
1251
1252 /**
1253 * @return Array
1254 */
1255 public function getValues() {
1256 return $this->data;
1257 }
1258
1259 /**
1260 * @return array
1261 */
1262 public function getQueryValues() {
1263 if ( $this->wasPosted ) {
1264 return array();
1265 } else {
1266 return $this->data;
1267 }
1268 }
1269
1270 /**
1271 * @return bool
1272 */
1273 public function wasPosted() {
1274 return $this->wasPosted;
1275 }
1276
1277 public function checkSessionCookie() {
1278 return false;
1279 }
1280
1281 public function getRequestURL() {
1282 $this->notImplemented( __METHOD__ );
1283 }
1284
1285 /**
1286 * @param $name
1287 * @return bool|string
1288 */
1289 public function getHeader( $name ) {
1290 return isset( $this->headers[$name] ) ? $this->headers[$name] : false;
1291 }
1292
1293 /**
1294 * @param $name string
1295 * @param $val string
1296 */
1297 public function setHeader( $name, $val ) {
1298 $this->headers[$name] = $val;
1299 }
1300
1301 /**
1302 * @param $key
1303 * @return mixed
1304 */
1305 public function getSessionData( $key ) {
1306 if( isset( $this->session[$key] ) )
1307 return $this->session[$key];
1308 }
1309
1310 /**
1311 * @param $key
1312 * @param $data
1313 */
1314 public function setSessionData( $key, $data ) {
1315 $this->session[$key] = $data;
1316 }
1317
1318 /**
1319 * @return array|Mixed|null
1320 */
1321 public function getSessionArray() {
1322 return $this->session;
1323 }
1324
1325 /**
1326 * @param array $extWhitelist
1327 * @return bool
1328 */
1329 public function isPathInfoBad( $extWhitelist = array() ) {
1330 return false;
1331 }
1332
1333 /**
1334 * @param array $extWhitelist
1335 * @return bool
1336 */
1337 public function checkUrlExtension( $extWhitelist = array() ) {
1338 return true;
1339 }
1340
1341 /**
1342 * @return string
1343 */
1344 protected function getRawIP() {
1345 return '127.0.0.1';
1346 }
1347 }
1348
1349 /**
1350 * Similar to FauxRequest, but only fakes URL parameters and method
1351 * (POST or GET) and use the base request for the remaining stuff
1352 * (cookies, session and headers).
1353 *
1354 * @ingroup HTTP
1355 * @since 1.19
1356 */
1357 class DerivativeRequest extends FauxRequest {
1358 private $base;
1359
1360 public function __construct( WebRequest $base, $data, $wasPosted = false ) {
1361 $this->base = $base;
1362 parent::__construct( $data, $wasPosted );
1363 }
1364
1365 public function getCookie( $key, $prefix = null, $default = null ) {
1366 return $this->base->getCookie( $key, $prefix, $default );
1367 }
1368
1369 public function checkSessionCookie() {
1370 return $this->base->checkSessionCookie();
1371 }
1372
1373 public function getHeader( $name ) {
1374 return $this->base->getHeader( $name );
1375 }
1376
1377 public function getAllHeaders() {
1378 return $this->base->getAllHeaders();
1379 }
1380
1381 public function getSessionData( $key ) {
1382 return $this->base->getSessionData( $key );
1383 }
1384
1385 public function setSessionData( $key, $data ) {
1386 $this->base->setSessionData( $key, $data );
1387 }
1388
1389 public function getAcceptLang() {
1390 return $this->base->getAcceptLang();
1391 }
1392
1393 public function getIP() {
1394 return $this->base->getIP();
1395 }
1396 }