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