Follow-up r70037: Move isIniSizeOverflow magic to WebRequestUpload
[lhc/web/wiklou.git] / includes / WebRequest.php
1 <?php
2 /**
3 * Deal with importing all those nasssty globals and things
4 */
5
6 # Copyright (C) 2003 Brion Vibber <brion@pobox.com>
7 # http://www.mediawiki.org/
8 #
9 # This program is free software; you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 2 of the License, or
12 # (at your option) any later version.
13 #
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License along
20 # with this program; if not, write to the Free Software Foundation, Inc.,
21 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 # http://www.gnu.org/copyleft/gpl.html
23
24
25 /**
26 * Some entry points may use this file without first enabling the
27 * autoloader.
28 */
29 if ( !function_exists( '__autoload' ) ) {
30 require_once( dirname(__FILE__) . '/normal/UtfNormal.php' );
31 }
32
33 /**
34 * The WebRequest class encapsulates getting at data passed in the
35 * URL or via a POSTed form, handling remove of "magic quotes" slashes,
36 * stripping illegal input characters and normalizing Unicode sequences.
37 *
38 * Usually this is used via a global singleton, $wgRequest. You should
39 * not create a second WebRequest object; make a FauxRequest object if
40 * you want to pass arbitrary data to some function in place of the web
41 * input.
42 *
43 * @ingroup HTTP
44 */
45 class WebRequest {
46 protected $data, $headers = array();
47 private $_response;
48
49 public function __construct() {
50 /// @todo Fixme: this preemptive de-quoting can interfere with other web libraries
51 /// and increases our memory footprint. It would be cleaner to do on
52 /// demand; but currently we have no wrapper for $_SERVER etc.
53 $this->checkMagicQuotes();
54
55 // POST overrides GET data
56 // We don't use $_REQUEST here to avoid interference from cookies...
57 $this->data = $_POST + $_GET;
58 }
59
60 /**
61 * Check for title, action, and/or variant data in the URL
62 * and interpolate it into the GET variables.
63 * This should only be run after $wgContLang is available,
64 * as we may need the list of language variants to determine
65 * available variant URLs.
66 */
67 public function interpolateTitle() {
68 global $wgUsePathInfo;
69
70 if ( $wgUsePathInfo ) {
71 // PATH_INFO is mangled due to http://bugs.php.net/bug.php?id=31892
72 // And also by Apache 2.x, double slashes are converted to single slashes.
73 // So we will use REQUEST_URI if possible.
74 $matches = array();
75
76 if ( !empty( $_SERVER['REQUEST_URI'] ) ) {
77 // Slurp out the path portion to examine...
78 $url = $_SERVER['REQUEST_URI'];
79 if ( !preg_match( '!^https?://!', $url ) ) {
80 $url = 'http://unused' . $url;
81 }
82 $a = parse_url( $url );
83 if( $a ) {
84 $path = isset( $a['path'] ) ? $a['path'] : '';
85
86 global $wgScript;
87 if( $path == $wgScript ) {
88 // Script inside a rewrite path?
89 // Abort to keep from breaking...
90 return;
91 }
92 // Raw PATH_INFO style
93 $matches = $this->extractTitle( $path, "$wgScript/$1" );
94
95 global $wgArticlePath;
96 if( !$matches && $wgArticlePath ) {
97 $matches = $this->extractTitle( $path, $wgArticlePath );
98 }
99
100 global $wgActionPaths;
101 if( !$matches && $wgActionPaths ) {
102 $matches = $this->extractTitle( $path, $wgActionPaths, 'action' );
103 }
104
105 global $wgVariantArticlePath, $wgContLang;
106 if( !$matches && $wgVariantArticlePath ) {
107 $variantPaths = array();
108 foreach( $wgContLang->getVariants() as $variant ) {
109 $variantPaths[$variant] =
110 str_replace( '$2', $variant, $wgVariantArticlePath );
111 }
112 $matches = $this->extractTitle( $path, $variantPaths, 'variant' );
113 }
114 }
115 } elseif ( isset( $_SERVER['ORIG_PATH_INFO'] ) && $_SERVER['ORIG_PATH_INFO'] != '' ) {
116 // Mangled PATH_INFO
117 // http://bugs.php.net/bug.php?id=31892
118 // Also reported when ini_get('cgi.fix_pathinfo')==false
119 $matches['title'] = substr( $_SERVER['ORIG_PATH_INFO'], 1 );
120
121 } elseif ( isset( $_SERVER['PATH_INFO'] ) && ($_SERVER['PATH_INFO'] != '') ) {
122 // Regular old PATH_INFO yay
123 $matches['title'] = substr( $_SERVER['PATH_INFO'], 1 );
124 }
125 foreach( $matches as $key => $val) {
126 $this->data[$key] = $_GET[$key] = $_REQUEST[$key] = $val;
127 }
128 }
129 }
130
131 /**
132 * Internal URL rewriting function; tries to extract page title and,
133 * optionally, one other fixed parameter value from a URL path.
134 *
135 * @param $path string: the URL path given from the client
136 * @param $bases array: one or more URLs, optionally with $1 at the end
137 * @param $key string: if provided, the matching key in $bases will be
138 * passed on as the value of this URL parameter
139 * @return array of URL variables to interpolate; empty if no match
140 */
141 private function extractTitle( $path, $bases, $key=false ) {
142 foreach( (array)$bases as $keyValue => $base ) {
143 // Find the part after $wgArticlePath
144 $base = str_replace( '$1', '', $base );
145 $baseLen = strlen( $base );
146 if( substr( $path, 0, $baseLen ) == $base ) {
147 $raw = substr( $path, $baseLen );
148 if( $raw !== '' ) {
149 $matches = array( 'title' => rawurldecode( $raw ) );
150 if( $key ) {
151 $matches[$key] = $keyValue;
152 }
153 return $matches;
154 }
155 }
156 }
157 return array();
158 }
159
160 /**
161 * Recursively strips slashes from the given array;
162 * used for undoing the evil that is magic_quotes_gpc.
163 *
164 * @param $arr array: will be modified
165 * @return array the original array
166 */
167 private function &fix_magic_quotes( &$arr ) {
168 foreach( $arr as $key => $val ) {
169 if( is_array( $val ) ) {
170 $this->fix_magic_quotes( $arr[$key] );
171 } else {
172 $arr[$key] = stripslashes( $val );
173 }
174 }
175 return $arr;
176 }
177
178 /**
179 * If magic_quotes_gpc option is on, run the global arrays
180 * through fix_magic_quotes to strip out the stupid slashes.
181 * WARNING: This should only be done once! Running a second
182 * time could damage the values.
183 */
184 private function checkMagicQuotes() {
185 $mustFixQuotes = function_exists( 'get_magic_quotes_gpc' )
186 && get_magic_quotes_gpc();
187 if( $mustFixQuotes ) {
188 $this->fix_magic_quotes( $_COOKIE );
189 $this->fix_magic_quotes( $_ENV );
190 $this->fix_magic_quotes( $_GET );
191 $this->fix_magic_quotes( $_POST );
192 $this->fix_magic_quotes( $_REQUEST );
193 $this->fix_magic_quotes( $_SERVER );
194 }
195 }
196
197 /**
198 * Recursively normalizes UTF-8 strings in the given array.
199 *
200 * @param $data string or array
201 * @return cleaned-up version of the given
202 * @private
203 */
204 function normalizeUnicode( $data ) {
205 if( is_array( $data ) ) {
206 foreach( $data as $key => $val ) {
207 $data[$key] = $this->normalizeUnicode( $val );
208 }
209 } else {
210 global $wgContLang;
211 $data = $wgContLang->normalize( $data );
212 }
213 return $data;
214 }
215
216 /**
217 * Fetch a value from the given array or return $default if it's not set.
218 *
219 * @param $arr Array
220 * @param $name String
221 * @param $default Mixed
222 * @return mixed
223 */
224 private function getGPCVal( $arr, $name, $default ) {
225 # PHP is so nice to not touch input data, except sometimes:
226 # http://us2.php.net/variables.external#language.variables.external.dot-in-names
227 # Work around PHP *feature* to avoid *bugs* elsewhere.
228 $name = strtr( $name, '.', '_' );
229 if( isset( $arr[$name] ) ) {
230 global $wgContLang;
231 $data = $arr[$name];
232 if( isset( $_GET[$name] ) && !is_array( $data ) ) {
233 # Check for alternate/legacy character encoding.
234 if( isset( $wgContLang ) ) {
235 $data = $wgContLang->checkTitleEncoding( $data );
236 }
237 }
238 $data = $this->normalizeUnicode( $data );
239 return $data;
240 } else {
241 taint( $default );
242 return $default;
243 }
244 }
245
246 /**
247 * Fetch a scalar from the input or return $default if it's not set.
248 * Returns a string. Arrays are discarded. Useful for
249 * non-freeform text inputs (e.g. predefined internal text keys
250 * selected by a drop-down menu). For freeform input, see getText().
251 *
252 * @param $name String
253 * @param $default String: optional default (or NULL)
254 * @return String
255 */
256 public function getVal( $name, $default = null ) {
257 $val = $this->getGPCVal( $this->data, $name, $default );
258 if( is_array( $val ) ) {
259 $val = $default;
260 }
261 if( is_null( $val ) ) {
262 return $val;
263 } else {
264 return (string)$val;
265 }
266 }
267
268 /**
269 * Set an aribtrary value into our get/post data.
270 *
271 * @param $key String: key name to use
272 * @param $value Mixed: value to set
273 * @return Mixed: old value if one was present, null otherwise
274 */
275 public function setVal( $key, $value ) {
276 $ret = isset( $this->data[$key] ) ? $this->data[$key] : null;
277 $this->data[$key] = $value;
278 return $ret;
279 }
280
281 /**
282 * Fetch an array from the input or return $default if it's not set.
283 * If source was scalar, will return an array with a single element.
284 * If no source and no default, returns NULL.
285 *
286 * @param $name String
287 * @param $default Array: optional default (or NULL)
288 * @return Array
289 */
290 public function getArray( $name, $default = null ) {
291 $val = $this->getGPCVal( $this->data, $name, $default );
292 if( is_null( $val ) ) {
293 return null;
294 } else {
295 return (array)$val;
296 }
297 }
298
299 /**
300 * Fetch an array of integers, or return $default if it's not set.
301 * If source was scalar, will return an array with a single element.
302 * If no source and no default, returns NULL.
303 * If an array is returned, contents are guaranteed to be integers.
304 *
305 * @param $name String
306 * @param $default Array: option default (or NULL)
307 * @return Array of ints
308 */
309 public function getIntArray( $name, $default = null ) {
310 $val = $this->getArray( $name, $default );
311 if( is_array( $val ) ) {
312 $val = array_map( 'intval', $val );
313 }
314 return $val;
315 }
316
317 /**
318 * Fetch an integer value from the input or return $default if not set.
319 * Guaranteed to return an integer; non-numeric input will typically
320 * return 0.
321 *
322 * @param $name String
323 * @param $default Integer
324 * @return Integer
325 */
326 public function getInt( $name, $default = 0 ) {
327 return intval( $this->getVal( $name, $default ) );
328 }
329
330 /**
331 * Fetch an integer value from the input or return null if empty.
332 * Guaranteed to return an integer or null; non-numeric input will
333 * typically return null.
334 *
335 * @param $name String
336 * @return Integer
337 */
338 public function getIntOrNull( $name ) {
339 $val = $this->getVal( $name );
340 return is_numeric( $val )
341 ? intval( $val )
342 : null;
343 }
344
345 /**
346 * Fetch a boolean value from the input or return $default if not set.
347 * Guaranteed to return true or false, with normal PHP semantics for
348 * boolean interpretation of strings.
349 *
350 * @param $name String
351 * @param $default Boolean
352 * @return Boolean
353 */
354 public function getBool( $name, $default = false ) {
355 return $this->getVal( $name, $default ) ? true : false;
356 }
357
358 /**
359 * Return true if the named value is set in the input, whatever that
360 * value is (even "0"). Return false if the named value is not set.
361 * Example use is checking for the presence of check boxes in forms.
362 *
363 * @param $name String
364 * @return Boolean
365 */
366 public function getCheck( $name ) {
367 # Checkboxes and buttons are only present when clicked
368 # Presence connotes truth, abscense false
369 $val = $this->getVal( $name, null );
370 return isset( $val );
371 }
372
373 /**
374 * Fetch a text string from the given array or return $default if it's not
375 * set. \r is stripped from the text, and with some language modules there
376 * is an input transliteration applied. This should generally be used for
377 * form <textarea> and <input> fields. Used for user-supplied freeform text
378 * input (for which input transformations may be required - e.g. Esperanto
379 * x-coding).
380 *
381 * @param $name String
382 * @param $default String: optional
383 * @return String
384 */
385 public function getText( $name, $default = '' ) {
386 global $wgContLang;
387 $val = $this->getVal( $name, $default );
388 return str_replace( "\r\n", "\n",
389 $wgContLang->recodeInput( $val ) );
390 }
391
392 /**
393 * Extracts the given named values into an array.
394 * If no arguments are given, returns all input values.
395 * No transformation is performed on the values.
396 */
397 public function getValues() {
398 $names = func_get_args();
399 if ( count( $names ) == 0 ) {
400 $names = array_keys( $this->data );
401 }
402
403 $retVal = array();
404 foreach ( $names as $name ) {
405 $value = $this->getVal( $name );
406 if ( !is_null( $value ) ) {
407 $retVal[$name] = $value;
408 }
409 }
410 return $retVal;
411 }
412
413 /**
414 * Returns true if the present request was reached by a POST operation,
415 * false otherwise (GET, HEAD, or command-line).
416 *
417 * Note that values retrieved by the object may come from the
418 * GET URL etc even on a POST request.
419 *
420 * @return Boolean
421 */
422 public function wasPosted() {
423 return $_SERVER['REQUEST_METHOD'] == 'POST';
424 }
425
426 /**
427 * Returns true if there is a session cookie set.
428 * This does not necessarily mean that the user is logged in!
429 *
430 * If you want to check for an open session, use session_id()
431 * instead; that will also tell you if the session was opened
432 * during the current request (in which case the cookie will
433 * be sent back to the client at the end of the script run).
434 *
435 * @return Boolean
436 */
437 public function checkSessionCookie() {
438 return isset( $_COOKIE[session_name()] );
439 }
440
441 /**
442 * Get a cookie from the $_COOKIE jar
443 *
444 * @param $key String: the name of the cookie
445 * @param $default Mixed: what to return if the value isn't found
446 * @param $prefix String: a prefix to use for the cookie name, if not $wgCookiePrefix
447 * @return Mixed: cookie value or $default if the cookie not set
448 */
449 public function getCookie( $key, $default = null, $prefix = '' ) {
450 if( !$prefix ) {
451 global $wgCookiePrefix;
452 $prefix = $wgCookiePrefix;
453 }
454 return $this->getGPCVal( $_COOKIE, $prefix . $key , $default );
455 }
456
457 /**
458 * Return the path portion of the request URI.
459 *
460 * @return String
461 */
462 public function getRequestURL() {
463 if( isset( $_SERVER['REQUEST_URI']) && strlen($_SERVER['REQUEST_URI']) ) {
464 $base = $_SERVER['REQUEST_URI'];
465 } elseif( isset( $_SERVER['SCRIPT_NAME'] ) ) {
466 // Probably IIS; doesn't set REQUEST_URI
467 $base = $_SERVER['SCRIPT_NAME'];
468 if( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
469 $base .= '?' . $_SERVER['QUERY_STRING'];
470 }
471 } else {
472 // This shouldn't happen!
473 throw new MWException( "Web server doesn't provide either " .
474 "REQUEST_URI or SCRIPT_NAME. Report details of your " .
475 "web server configuration to http://bugzilla.wikimedia.org/" );
476 }
477 // User-agents should not send a fragment with the URI, but
478 // if they do, and the web server passes it on to us, we
479 // need to strip it or we get false-positive redirect loops
480 // or weird output URLs
481 $hash = strpos( $base, '#' );
482 if( $hash !== false ) {
483 $base = substr( $base, 0, $hash );
484 }
485 if( $base{0} == '/' ) {
486 return $base;
487 } else {
488 // We may get paths with a host prepended; strip it.
489 return preg_replace( '!^[^:]+://[^/]+/!', '/', $base );
490 }
491 }
492
493 /**
494 * Return the request URI with the canonical service and hostname.
495 *
496 * @return String
497 */
498 public function getFullRequestURL() {
499 global $wgServer;
500 return $wgServer . $this->getRequestURL();
501 }
502
503 /**
504 * Take an arbitrary query and rewrite the present URL to include it
505 * @param $query String: query string fragment; do not include initial '?'
506 *
507 * @return String
508 */
509 public function appendQuery( $query ) {
510 global $wgTitle;
511 $basequery = '';
512 foreach( $_GET as $var => $val ) {
513 if ( $var == 'title' )
514 continue;
515 if ( is_array( $val ) )
516 /* This will happen given a request like
517 * http://en.wikipedia.org/w/index.php?title[]=Special:Userlogin&returnto[]=Main_Page
518 */
519 continue;
520 $basequery .= '&' . urlencode( $var ) . '=' . urlencode( $val );
521 }
522 $basequery .= '&' . $query;
523
524 # Trim the extra &
525 $basequery = substr( $basequery, 1 );
526 return $wgTitle->getLocalURL( $basequery );
527 }
528
529 /**
530 * HTML-safe version of appendQuery().
531 *
532 * @param $query String: query string fragment; do not include initial '?'
533 * @return String
534 */
535 public function escapeAppendQuery( $query ) {
536 return htmlspecialchars( $this->appendQuery( $query ) );
537 }
538
539 public function appendQueryValue( $key, $value, $onlyquery = false ) {
540 return $this->appendQueryArray( array( $key => $value ), $onlyquery );
541 }
542
543 /**
544 * Appends or replaces value of query variables.
545 *
546 * @param $array Array of values to replace/add to query
547 * @param $onlyquery Bool: whether to only return the query string and not
548 * the complete URL
549 * @return String
550 */
551 public function appendQueryArray( $array, $onlyquery = false ) {
552 global $wgTitle;
553 $newquery = $_GET;
554 unset( $newquery['title'] );
555 $newquery = array_merge( $newquery, $array );
556 $query = wfArrayToCGI( $newquery );
557 return $onlyquery ? $query : $wgTitle->getLocalURL( $query );
558 }
559
560 /**
561 * Check for limit and offset parameters on the input, and return sensible
562 * defaults if not given. The limit must be positive and is capped at 5000.
563 * Offset must be positive but is not capped.
564 *
565 * @param $deflimit Integer: limit to use if no input and the user hasn't set the option.
566 * @param $optionname String: to specify an option other than rclimit to pull from.
567 * @return array first element is limit, second is offset
568 */
569 public function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
570 global $wgUser;
571
572 $limit = $this->getInt( 'limit', 0 );
573 if( $limit < 0 ) $limit = 0;
574 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
575 $limit = (int)$wgUser->getOption( $optionname );
576 }
577 if( $limit <= 0 ) $limit = $deflimit;
578 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
579
580 $offset = $this->getInt( 'offset', 0 );
581 if( $offset < 0 ) $offset = 0;
582
583 return array( $limit, $offset );
584 }
585
586 /**
587 * Return the path to the temporary file where PHP has stored the upload.
588 *
589 * @param $key String:
590 * @return string or NULL if no such file.
591 */
592 public function getFileTempname( $key ) {
593 $file = new WebRequestUpload( $this, $key );
594 return $file->getTempName();
595 }
596
597 /**
598 * Return the size of the upload, or 0.
599 *
600 * @deprecated
601 * @param $key String:
602 * @return integer
603 */
604 public function getFileSize( $key ) {
605 $file = new WebRequestUpload( $this, $key );
606 return $file->getSize();
607 }
608
609 /**
610 * Return the upload error or 0
611 *
612 * @param $key String:
613 * @return integer
614 */
615 public function getUploadError( $key ) {
616 $file = new WebRequestUpload( $this, $key );
617 return $file->getError();
618 }
619
620 /**
621 * Return the original filename of the uploaded file, as reported by
622 * the submitting user agent. HTML-style character entities are
623 * interpreted and normalized to Unicode normalization form C, in part
624 * to deal with weird input from Safari with non-ASCII filenames.
625 *
626 * Other than this the name is not verified for being a safe filename.
627 *
628 * @param $key String:
629 * @return string or NULL if no such file.
630 */
631 public function getFileName( $key ) {
632 $file = new WebRequestUpload( $this, $key );
633 return $file->getName();
634 }
635
636 /**
637 * Return a WebRequestUpload object corresponding to the key
638 *
639 * @param @key string
640 * @return WebRequestUpload
641 */
642 public function getUpload( $key ) {
643 return new WebRequestUpload( $this, $key );
644 }
645
646 /**
647 * Return a handle to WebResponse style object, for setting cookies,
648 * headers and other stuff, for Request being worked on.
649 */
650 public function response() {
651 /* Lazy initialization of response object for this request */
652 if ( !is_object( $this->_response ) ) {
653 $class = ( $this instanceof FauxRequest ) ? 'FauxResponse' : 'WebResponse';
654 $this->_response = new $class();
655 }
656 return $this->_response;
657 }
658
659 /**
660 * Get a request header, or false if it isn't set
661 * @param $name String: case-insensitive header name
662 */
663 public function getHeader( $name ) {
664 $name = strtoupper( $name );
665 if ( function_exists( 'apache_request_headers' ) ) {
666 if ( !$this->headers ) {
667 foreach ( apache_request_headers() as $tempName => $tempValue ) {
668 $this->headers[ strtoupper( $tempName ) ] = $tempValue;
669 }
670 }
671 if ( isset( $this->headers[$name] ) ) {
672 return $this->headers[$name];
673 } else {
674 return false;
675 }
676 } else {
677 $name = 'HTTP_' . str_replace( '-', '_', $name );
678 if ( $name === 'HTTP_CONTENT_LENGTH' && !isset( $_SERVER[$name] ) ) {
679 $name = 'CONTENT_LENGTH';
680 }
681 if ( isset( $_SERVER[$name] ) ) {
682 return $_SERVER[$name];
683 } else {
684 return false;
685 }
686 }
687 }
688
689 /**
690 * Get data from $_SESSION
691 *
692 * @param $key String: name of key in $_SESSION
693 * @return Mixed
694 */
695 public function getSessionData( $key ) {
696 if( !isset( $_SESSION[$key] ) )
697 return null;
698 return $_SESSION[$key];
699 }
700
701 /**
702 * Set session data
703 *
704 * @param $key String: name of key in $_SESSION
705 * @param $data Mixed
706 */
707 public function setSessionData( $key, $data ) {
708 $_SESSION[$key] = $data;
709 }
710
711 /**
712 * Returns true if the PATH_INFO ends with an extension other than a script
713 * extension. This could confuse IE for scripts that send arbitrary data which
714 * is not HTML but may be detected as such.
715 *
716 * Various past attempts to use the URL to make this check have generally
717 * run up against the fact that CGI does not provide a standard method to
718 * determine the URL. PATH_INFO may be mangled (e.g. if cgi.fix_pathinfo=0),
719 * but only by prefixing it with the script name and maybe some other stuff,
720 * the extension is not mangled. So this should be a reasonably portable
721 * way to perform this security check.
722 */
723 public function isPathInfoBad() {
724 global $wgScriptExtension;
725
726 if ( !isset( $_SERVER['PATH_INFO'] ) ) {
727 return false;
728 }
729 $pi = $_SERVER['PATH_INFO'];
730 $dotPos = strrpos( $pi, '.' );
731 if ( $dotPos === false ) {
732 return false;
733 }
734 $ext = substr( $pi, $dotPos );
735 return !in_array( $ext, array( $wgScriptExtension, '.php', '.php5' ) );
736 }
737
738 /**
739 * Parse the Accept-Language header sent by the client into an array
740 * @return array( languageCode => q-value ) sorted by q-value in descending order
741 */
742 public function getAcceptLang() {
743 // Modified version of code found at http://www.thefutureoftheweb.com/blog/use-accept-language-header
744 if ( !isset( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ) ) {
745 return array();
746 }
747
748 // Break up string into pieces (languages and q factors)
749 $lang_parse = null;
750 preg_match_all( '/([a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0(\.[0-9]+))?)?/i',
751 $_SERVER['HTTP_ACCEPT_LANGUAGE'], $lang_parse );
752
753 if ( !count( $lang_parse[1] ) ) {
754 return array();
755 }
756 // Create a list like "en" => 0.8
757 $langs = array_combine( $lang_parse[1], $lang_parse[4] );
758 // Set default q factor to 1
759 foreach ( $langs as $lang => $val ) {
760 if ( $val === '' ) {
761 $langs[$lang] = 1;
762 }
763 }
764 // Sort list
765 arsort( $langs, SORT_NUMERIC );
766 return $langs;
767 }
768 }
769
770 /**
771 * Object to access the $_FILES array
772 */
773 class WebRequestUpload {
774 protected $request;
775 protected $doesExist;
776 protected $fileInfo;
777
778 /**
779 * Constructor. Should only be called by WebRequest
780 *
781 * @param $request WebRequest The associated request
782 * @param $key string Key in $_FILES array (name of form field)
783 */
784 public function __construct( $request, $key ) {
785 $this->request = $request;
786 $this->doesExist = isset( $_FILES[$key] );
787 if ( $this->doesExist ) {
788 $this->fileInfo = $_FILES[$key];
789 }
790 }
791
792 /**
793 * Return whether a file with this name was uploaded.
794 *
795 * @return bool
796 */
797 public function exists() {
798 return $this->doesExist;
799 }
800
801 /**
802 * Return the original filename of the uploaded file
803 *
804 * @return mixed Filename or null if non-existent
805 */
806 public function getName() {
807 if ( !$this->exists() ) {
808 return null;
809 }
810
811 global $wgContLang;
812 $name = $this->fileInfo['name'];
813
814 # Safari sends filenames in HTML-encoded Unicode form D...
815 # Horrid and evil! Let's try to make some kind of sense of it.
816 $name = Sanitizer::decodeCharReferences( $name );
817 $name = $wgContLang->normalize( $name );
818 wfDebug( __METHOD__ . ": {$this->fileInfo['name']} normalized to '$name'\n" );
819 return $name;
820 }
821
822 /**
823 * Return the file size of the uploaded file
824 *
825 * @return int File size or zero if non-existent
826 */
827 public function getSize() {
828 if ( !$this->exists() ) {
829 return 0;
830 }
831
832 return $this->fileInfo['size'];
833 }
834
835 /**
836 * Return the path to the temporary file
837 *
838 * @return mixed Path or null if non-existent
839 */
840 public function getTempName() {
841 if ( !$this->exists() ) {
842 return null;
843 }
844
845 return $this->fileInfo['tmp_name'];
846 }
847
848 /**
849 * Return the upload error. See link for explanation
850 * http://www.php.net/manual/en/features.file-upload.errors.php
851 *
852 * @return int One of the UPLOAD_ constants, 0 if non-existent
853 */
854 public function getError() {
855 if ( !$this->exists() ) {
856 return 0; # UPLOAD_ERR_OK
857 }
858
859 return $this->fileInfo['error'];
860 }
861
862 /**
863 * Returns whether this upload failed because of overflow of a maximum set
864 * in php.ini
865 *
866 * @return bool
867 */
868 public function isIniSizeOverflow() {
869 if ( $this->getError() == UPLOAD_ERR_INI_SIZE ) {
870 # PHP indicated that upload_max_filesize is exceeded
871 return true;
872 }
873
874 $contentLength = $this->request->getHeader( 'CONTENT_LENGTH' );
875 if ( $contentLength > wfShorthandToInteger( ini_get( 'post_max_size' ) ) ) {
876 # post_max_size is exceeded
877 return true;
878 }
879
880 return false;
881 }
882 }
883
884 /**
885 * WebRequest clone which takes values from a provided array.
886 *
887 * @ingroup HTTP
888 */
889 class FauxRequest extends WebRequest {
890 private $wasPosted = false;
891 private $session = array();
892
893 /**
894 * @param $data Array of *non*-urlencoded key => value pairs, the
895 * fake GET/POST values
896 * @param $wasPosted Bool: whether to treat the data as POST
897 * @param $session Mixed: session array or null
898 */
899 public function __construct( $data, $wasPosted = false, $session = null ) {
900 if( is_array( $data ) ) {
901 $this->data = $data;
902 } else {
903 throw new MWException( "FauxRequest() got bogus data" );
904 }
905 $this->wasPosted = $wasPosted;
906 if( $session )
907 $this->session = $session;
908 }
909
910 private function notImplemented( $method ) {
911 throw new MWException( "{$method}() not implemented" );
912 }
913
914 public function getText( $name, $default = '' ) {
915 # Override; don't recode since we're using internal data
916 return (string)$this->getVal( $name, $default );
917 }
918
919 public function getValues() {
920 return $this->data;
921 }
922
923 public function wasPosted() {
924 return $this->wasPosted;
925 }
926
927 public function checkSessionCookie() {
928 return false;
929 }
930
931 public function getRequestURL() {
932 $this->notImplemented( __METHOD__ );
933 }
934
935 public function appendQuery( $query ) {
936 $this->notImplemented( __METHOD__ );
937 }
938
939 public function getHeader( $name ) {
940 return isset( $this->headers[$name] ) ? $this->headers[$name] : false;
941 }
942
943 public function setHeader( $name, $val ) {
944 $this->headers[$name] = $val;
945 }
946
947 public function getSessionData( $key ) {
948 if( isset( $this->session[$key] ) )
949 return $this->session[$key];
950 }
951
952 public function setSessionData( $key, $data ) {
953 $this->session[$key] = $data;
954 }
955
956 public function isPathInfoBad() {
957 return false;
958 }
959 }