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