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