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