Fixing comment so that method documentation isn't broken
[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 ) $limit = 0;
567 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
568 $limit = (int)$wgUser->getOption( $optionname );
569 }
570 if( $limit <= 0 ) $limit = $deflimit;
571 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
572
573 $offset = $this->getInt( 'offset', 0 );
574 if( $offset < 0 ) $offset = 0;
575
576 return array( $limit, $offset );
577 }
578
579 /**
580 * Return the path to the temporary file where PHP has stored the upload.
581 *
582 * @param $key String:
583 * @return string or NULL if no such file.
584 */
585 public function getFileTempname( $key ) {
586 $file = new WebRequestUpload( $this, $key );
587 return $file->getTempName();
588 }
589
590 /**
591 * Return the size of the upload, or 0.
592 *
593 * @deprecated
594 * @param $key String:
595 * @return integer
596 */
597 public function getFileSize( $key ) {
598 $file = new WebRequestUpload( $this, $key );
599 return $file->getSize();
600 }
601
602 /**
603 * Return the upload error or 0
604 *
605 * @param $key String:
606 * @return integer
607 */
608 public function getUploadError( $key ) {
609 $file = new WebRequestUpload( $this, $key );
610 return $file->getError();
611 }
612
613 /**
614 * Return the original filename of the uploaded file, as reported by
615 * the submitting user agent. HTML-style character entities are
616 * interpreted and normalized to Unicode normalization form C, in part
617 * to deal with weird input from Safari with non-ASCII filenames.
618 *
619 * Other than this the name is not verified for being a safe filename.
620 *
621 * @param $key String:
622 * @return string or NULL if no such file.
623 */
624 public function getFileName( $key ) {
625 $file = new WebRequestUpload( $this, $key );
626 return $file->getName();
627 }
628
629 /**
630 * Return a WebRequestUpload object corresponding to the key
631 *
632 * @param @key string
633 * @return WebRequestUpload
634 */
635 public function getUpload( $key ) {
636 return new WebRequestUpload( $this, $key );
637 }
638
639 /**
640 * Return a handle to WebResponse style object, for setting cookies,
641 * headers and other stuff, for Request being worked on.
642 */
643 public function response() {
644 /* Lazy initialization of response object for this request */
645 if ( !is_object( $this->_response ) ) {
646 $class = ( $this instanceof FauxRequest ) ? 'FauxResponse' : 'WebResponse';
647 $this->_response = new $class();
648 }
649 return $this->_response;
650 }
651
652 /**
653 * Get a request header, or false if it isn't set
654 * @param $name String: case-insensitive header name
655 */
656 public function getHeader( $name ) {
657 $name = strtoupper( $name );
658 if ( function_exists( 'apache_request_headers' ) ) {
659 if ( !$this->headers ) {
660 foreach ( apache_request_headers() as $tempName => $tempValue ) {
661 $this->headers[ strtoupper( $tempName ) ] = $tempValue;
662 }
663 }
664 if ( isset( $this->headers[$name] ) ) {
665 return $this->headers[$name];
666 } else {
667 return false;
668 }
669 } else {
670 $name = 'HTTP_' . str_replace( '-', '_', $name );
671 if ( $name === 'HTTP_CONTENT_LENGTH' && !isset( $_SERVER[$name] ) ) {
672 $name = 'CONTENT_LENGTH';
673 }
674 if ( isset( $_SERVER[$name] ) ) {
675 return $_SERVER[$name];
676 } else {
677 return false;
678 }
679 }
680 }
681
682 /**
683 * Get data from $_SESSION
684 *
685 * @param $key String: name of key in $_SESSION
686 * @return Mixed
687 */
688 public function getSessionData( $key ) {
689 if( !isset( $_SESSION[$key] ) )
690 return null;
691 return $_SESSION[$key];
692 }
693
694 /**
695 * Set session data
696 *
697 * @param $key String: name of key in $_SESSION
698 * @param $data Mixed
699 */
700 public function setSessionData( $key, $data ) {
701 $_SESSION[$key] = $data;
702 }
703
704 /**
705 * Returns true if the PATH_INFO ends with an extension other than a script
706 * extension. This could confuse IE for scripts that send arbitrary data which
707 * is not HTML but may be detected as such.
708 *
709 * Various past attempts to use the URL to make this check have generally
710 * run up against the fact that CGI does not provide a standard method to
711 * determine the URL. PATH_INFO may be mangled (e.g. if cgi.fix_pathinfo=0),
712 * but only by prefixing it with the script name and maybe some other stuff,
713 * the extension is not mangled. So this should be a reasonably portable
714 * way to perform this security check.
715 */
716 public function isPathInfoBad() {
717 global $wgScriptExtension;
718
719 if ( !isset( $_SERVER['PATH_INFO'] ) ) {
720 return false;
721 }
722 $pi = $_SERVER['PATH_INFO'];
723 $dotPos = strrpos( $pi, '.' );
724 if ( $dotPos === false ) {
725 return false;
726 }
727 $ext = substr( $pi, $dotPos );
728 return !in_array( $ext, array( $wgScriptExtension, '.php', '.php5' ) );
729 }
730
731 /**
732 * Parse the Accept-Language header sent by the client into an array
733 * @return array( languageCode => q-value ) sorted by q-value in descending order
734 * May contain the "language" '*', which applies to languages other than those explicitly listed.
735 * This is aligned with rfc2616 section 14.4
736 */
737 public function getAcceptLang() {
738 // Modified version of code found at http://www.thefutureoftheweb.com/blog/use-accept-language-header
739 $acceptLang = $this->getHeader( 'Accept-Language' );
740 if ( !$acceptLang ) {
741 return array();
742 }
743
744 // Return the language codes in lower case
745 $acceptLang = strtolower( $acceptLang );
746
747 // Break up string into pieces (languages and q factors)
748 $lang_parse = null;
749 preg_match_all( '/([a-z]{1,8}(-[a-z]{1,8})?|\*)\s*(;\s*q\s*=\s*(1|0(\.[0-9]+)?)?)?/',
750 $acceptLang, $lang_parse );
751
752 if ( !count( $lang_parse[1] ) ) {
753 return array();
754 }
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 } else if ( $val == 0 ) {
763 unset($langs[$lang]);
764 }
765 }
766
767 // Sort list
768 arsort( $langs, SORT_NUMERIC );
769 return $langs;
770 }
771 }
772
773 /**
774 * Object to access the $_FILES array
775 */
776 class WebRequestUpload {
777 protected $request;
778 protected $doesExist;
779 protected $fileInfo;
780
781 /**
782 * Constructor. Should only be called by WebRequest
783 *
784 * @param $request WebRequest The associated request
785 * @param $key string Key in $_FILES array (name of form field)
786 */
787 public function __construct( $request, $key ) {
788 $this->request = $request;
789 $this->doesExist = isset( $_FILES[$key] );
790 if ( $this->doesExist ) {
791 $this->fileInfo = $_FILES[$key];
792 }
793 }
794
795 /**
796 * Return whether a file with this name was uploaded.
797 *
798 * @return bool
799 */
800 public function exists() {
801 return $this->doesExist;
802 }
803
804 /**
805 * Return the original filename of the uploaded file
806 *
807 * @return mixed Filename or null if non-existent
808 */
809 public function getName() {
810 if ( !$this->exists() ) {
811 return null;
812 }
813
814 global $wgContLang;
815 $name = $this->fileInfo['name'];
816
817 # Safari sends filenames in HTML-encoded Unicode form D...
818 # Horrid and evil! Let's try to make some kind of sense of it.
819 $name = Sanitizer::decodeCharReferences( $name );
820 $name = $wgContLang->normalize( $name );
821 wfDebug( __METHOD__ . ": {$this->fileInfo['name']} normalized to '$name'\n" );
822 return $name;
823 }
824
825 /**
826 * Return the file size of the uploaded file
827 *
828 * @return int File size or zero if non-existent
829 */
830 public function getSize() {
831 if ( !$this->exists() ) {
832 return 0;
833 }
834
835 return $this->fileInfo['size'];
836 }
837
838 /**
839 * Return the path to the temporary file
840 *
841 * @return mixed Path or null if non-existent
842 */
843 public function getTempName() {
844 if ( !$this->exists() ) {
845 return null;
846 }
847
848 return $this->fileInfo['tmp_name'];
849 }
850
851 /**
852 * Return the upload error. See link for explanation
853 * http://www.php.net/manual/en/features.file-upload.errors.php
854 *
855 * @return int One of the UPLOAD_ constants, 0 if non-existent
856 */
857 public function getError() {
858 if ( !$this->exists() ) {
859 return 0; # UPLOAD_ERR_OK
860 }
861
862 return $this->fileInfo['error'];
863 }
864
865 /**
866 * Returns whether this upload failed because of overflow of a maximum set
867 * in php.ini
868 *
869 * @return bool
870 */
871 public function isIniSizeOverflow() {
872 if ( $this->getError() == UPLOAD_ERR_INI_SIZE ) {
873 # PHP indicated that upload_max_filesize is exceeded
874 return true;
875 }
876
877 $contentLength = $this->request->getHeader( 'CONTENT_LENGTH' );
878 if ( $contentLength > wfShorthandToInteger( ini_get( 'post_max_size' ) ) ) {
879 # post_max_size is exceeded
880 return true;
881 }
882
883 return false;
884 }
885 }
886
887 /**
888 * WebRequest clone which takes values from a provided array.
889 *
890 * @ingroup HTTP
891 */
892 class FauxRequest extends WebRequest {
893 private $wasPosted = false;
894 private $session = array();
895
896 /**
897 * @param $data Array of *non*-urlencoded key => value pairs, the
898 * fake GET/POST values
899 * @param $wasPosted Bool: whether to treat the data as POST
900 * @param $session Mixed: session array or null
901 */
902 public function __construct( $data, $wasPosted = false, $session = null ) {
903 if( is_array( $data ) ) {
904 $this->data = $data;
905 } else {
906 throw new MWException( "FauxRequest() got bogus data" );
907 }
908 $this->wasPosted = $wasPosted;
909 if( $session )
910 $this->session = $session;
911 }
912
913 private function notImplemented( $method ) {
914 throw new MWException( "{$method}() not implemented" );
915 }
916
917 public function getText( $name, $default = '' ) {
918 # Override; don't recode since we're using internal data
919 return (string)$this->getVal( $name, $default );
920 }
921
922 public function getValues() {
923 return $this->data;
924 }
925
926 public function wasPosted() {
927 return $this->wasPosted;
928 }
929
930 public function checkSessionCookie() {
931 return false;
932 }
933
934 public function getRequestURL() {
935 $this->notImplemented( __METHOD__ );
936 }
937
938 public function appendQuery( $query ) {
939 $this->notImplemented( __METHOD__ );
940 }
941
942 public function getHeader( $name ) {
943 return isset( $this->headers[$name] ) ? $this->headers[$name] : false;
944 }
945
946 public function setHeader( $name, $val ) {
947 $this->headers[$name] = $val;
948 }
949
950 public function getSessionData( $key ) {
951 if( isset( $this->session[$key] ) )
952 return $this->session[$key];
953 }
954
955 public function setSessionData( $key, $data ) {
956 $this->session[$key] = $data;
957 }
958
959 public function isPathInfoBad() {
960 return false;
961 }
962 }