Fix a bunch of '? true : false' instances
[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 (bool)$this->getVal( $name, $default );
349 }
350
351 /**
352 * Fetch a boolean value from the input or return $default if not set.
353 * Unlike getBool, the string "false" will result in boolean false, which is
354 * useful when interpreting information sent from JavaScript.
355 *
356 * @param $name String
357 * @param $default Boolean
358 * @return Boolean
359 */
360 public function getFuzzyBool( $name, $default = false ) {
361 return $this->getBool( $name, $default ) && $this->getVal( $name ) !== 'false';
362 }
363
364 /**
365 * Return true if the named value is set in the input, whatever that
366 * value is (even "0"). Return false if the named value is not set.
367 * Example use is checking for the presence of check boxes in forms.
368 *
369 * @param $name String
370 * @return Boolean
371 */
372 public function getCheck( $name ) {
373 # Checkboxes and buttons are only present when clicked
374 # Presence connotes truth, abscense false
375 $val = $this->getVal( $name, null );
376 return isset( $val );
377 }
378
379 /**
380 * Fetch a text string from the given array or return $default if it's not
381 * set. Carriage returns are stripped from the text, and with some language
382 * modules there is an input transliteration applied. This should generally
383 * be used for form <textarea> and <input> fields. Used for user-supplied
384 * freeform text input (for which input transformations may be required - e.g.
385 * Esperanto x-coding).
386 *
387 * @param $name String
388 * @param $default String: optional
389 * @return String
390 */
391 public function getText( $name, $default = '' ) {
392 global $wgContLang;
393 $val = $this->getVal( $name, $default );
394 return str_replace( "\r\n", "\n",
395 $wgContLang->recodeInput( $val ) );
396 }
397
398 /**
399 * Extracts the given named values into an array.
400 * If no arguments are given, returns all input values.
401 * No transformation is performed on the values.
402 */
403 public function getValues() {
404 $names = func_get_args();
405 if ( count( $names ) == 0 ) {
406 $names = array_keys( $this->data );
407 }
408
409 $retVal = array();
410 foreach ( $names as $name ) {
411 $value = $this->getVal( $name );
412 if ( !is_null( $value ) ) {
413 $retVal[$name] = $value;
414 }
415 }
416 return $retVal;
417 }
418
419 /**
420 * Returns true if the present request was reached by a POST operation,
421 * false otherwise (GET, HEAD, or command-line).
422 *
423 * Note that values retrieved by the object may come from the
424 * GET URL etc even on a POST request.
425 *
426 * @return Boolean
427 */
428 public function wasPosted() {
429 return $_SERVER['REQUEST_METHOD'] == 'POST';
430 }
431
432 /**
433 * Returns true if there is a session cookie set.
434 * This does not necessarily mean that the user is logged in!
435 *
436 * If you want to check for an open session, use session_id()
437 * instead; that will also tell you if the session was opened
438 * during the current request (in which case the cookie will
439 * be sent back to the client at the end of the script run).
440 *
441 * @return Boolean
442 */
443 public function checkSessionCookie() {
444 return isset( $_COOKIE[ session_name() ] );
445 }
446
447 /**
448 * Get a cookie from the $_COOKIE jar
449 *
450 * @param $key String: the name of the cookie
451 * @param $prefix String: a prefix to use for the cookie name, if not $wgCookiePrefix
452 * @param $default Mixed: what to return if the value isn't found
453 * @return Mixed: cookie value or $default if the cookie not set
454 */
455 public function getCookie( $key, $prefix = null, $default = null ) {
456 if( $prefix === null ) {
457 global $wgCookiePrefix;
458 $prefix = $wgCookiePrefix;
459 }
460 return $this->getGPCVal( $_COOKIE, $prefix . $key , $default );
461 }
462
463 /**
464 * Return the path portion of the request URI.
465 *
466 * @return String
467 */
468 public function getRequestURL() {
469 if( isset( $_SERVER['REQUEST_URI']) && strlen($_SERVER['REQUEST_URI']) ) {
470 $base = $_SERVER['REQUEST_URI'];
471 } elseif( isset( $_SERVER['SCRIPT_NAME'] ) ) {
472 // Probably IIS; doesn't set REQUEST_URI
473 $base = $_SERVER['SCRIPT_NAME'];
474 if( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
475 $base .= '?' . $_SERVER['QUERY_STRING'];
476 }
477 } else {
478 // This shouldn't happen!
479 throw new MWException( "Web server doesn't provide either " .
480 "REQUEST_URI or SCRIPT_NAME. Report details of your " .
481 "web server configuration to http://bugzilla.wikimedia.org/" );
482 }
483 // User-agents should not send a fragment with the URI, but
484 // if they do, and the web server passes it on to us, we
485 // need to strip it or we get false-positive redirect loops
486 // or weird output URLs
487 $hash = strpos( $base, '#' );
488 if( $hash !== false ) {
489 $base = substr( $base, 0, $hash );
490 }
491 if( $base{0} == '/' ) {
492 return $base;
493 } else {
494 // We may get paths with a host prepended; strip it.
495 return preg_replace( '!^[^:]+://[^/]+/!', '/', $base );
496 }
497 }
498
499 /**
500 * Return the request URI with the canonical service and hostname.
501 *
502 * @return String
503 */
504 public function getFullRequestURL() {
505 global $wgServer;
506 return $wgServer . $this->getRequestURL();
507 }
508
509 /**
510 * Take an arbitrary query and rewrite the present URL to include it
511 * @param $query String: query string fragment; do not include initial '?'
512 *
513 * @return String
514 */
515 public function appendQuery( $query ) {
516 global $wgTitle;
517 $basequery = '';
518 foreach( $_GET as $var => $val ) {
519 if ( $var == 'title' )
520 continue;
521 if ( is_array( $val ) )
522 /* This will happen given a request like
523 * http://en.wikipedia.org/w/index.php?title[]=Special:Userlogin&returnto[]=Main_Page
524 */
525 continue;
526 $basequery .= '&' . urlencode( $var ) . '=' . urlencode( $val );
527 }
528 $basequery .= '&' . $query;
529
530 # Trim the extra &
531 $basequery = substr( $basequery, 1 );
532 return $wgTitle->getLocalURL( $basequery );
533 }
534
535 /**
536 * HTML-safe version of appendQuery().
537 *
538 * @param $query String: query string fragment; do not include initial '?'
539 * @return String
540 */
541 public function escapeAppendQuery( $query ) {
542 return htmlspecialchars( $this->appendQuery( $query ) );
543 }
544
545 public function appendQueryValue( $key, $value, $onlyquery = false ) {
546 return $this->appendQueryArray( array( $key => $value ), $onlyquery );
547 }
548
549 /**
550 * Appends or replaces value of query variables.
551 *
552 * @param $array Array of values to replace/add to query
553 * @param $onlyquery Bool: whether to only return the query string and not
554 * the complete URL
555 * @return String
556 */
557 public function appendQueryArray( $array, $onlyquery = false ) {
558 global $wgTitle;
559 $newquery = $_GET;
560 unset( $newquery['title'] );
561 $newquery = array_merge( $newquery, $array );
562 $query = wfArrayToCGI( $newquery );
563 return $onlyquery ? $query : $wgTitle->getLocalURL( $query );
564 }
565
566 /**
567 * Check for limit and offset parameters on the input, and return sensible
568 * defaults if not given. The limit must be positive and is capped at 5000.
569 * Offset must be positive but is not capped.
570 *
571 * @param $deflimit Integer: limit to use if no input and the user hasn't set the option.
572 * @param $optionname String: to specify an option other than rclimit to pull from.
573 * @return array first element is limit, second is offset
574 */
575 public function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
576 global $wgUser;
577
578 $limit = $this->getInt( 'limit', 0 );
579 if( $limit < 0 ) {
580 $limit = 0;
581 }
582 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
583 $limit = (int)$wgUser->getOption( $optionname );
584 }
585 if( $limit <= 0 ) {
586 $limit = $deflimit;
587 }
588 if( $limit > 5000 ) {
589 $limit = 5000; # We have *some* limits...
590 }
591
592 $offset = $this->getInt( 'offset', 0 );
593 if( $offset < 0 ) {
594 $offset = 0;
595 }
596
597 return array( $limit, $offset );
598 }
599
600 /**
601 * Return the path to the temporary file where PHP has stored the upload.
602 *
603 * @param $key String:
604 * @return string or NULL if no such file.
605 */
606 public function getFileTempname( $key ) {
607 $file = new WebRequestUpload( $this, $key );
608 return $file->getTempName();
609 }
610
611 /**
612 * Return the size of the upload, or 0.
613 *
614 * @deprecated
615 * @param $key String:
616 * @return integer
617 */
618 public function getFileSize( $key ) {
619 $file = new WebRequestUpload( $this, $key );
620 return $file->getSize();
621 }
622
623 /**
624 * Return the upload error or 0
625 *
626 * @param $key String:
627 * @return integer
628 */
629 public function getUploadError( $key ) {
630 $file = new WebRequestUpload( $this, $key );
631 return $file->getError();
632 }
633
634 /**
635 * Return the original filename of the uploaded file, as reported by
636 * the submitting user agent. HTML-style character entities are
637 * interpreted and normalized to Unicode normalization form C, in part
638 * to deal with weird input from Safari with non-ASCII filenames.
639 *
640 * Other than this the name is not verified for being a safe filename.
641 *
642 * @param $key String:
643 * @return string or NULL if no such file.
644 */
645 public function getFileName( $key ) {
646 $file = new WebRequestUpload( $this, $key );
647 return $file->getName();
648 }
649
650 /**
651 * Return a WebRequestUpload object corresponding to the key
652 *
653 * @param @key string
654 * @return WebRequestUpload
655 */
656 public function getUpload( $key ) {
657 return new WebRequestUpload( $this, $key );
658 }
659
660 /**
661 * Return a handle to WebResponse style object, for setting cookies,
662 * headers and other stuff, for Request being worked on.
663 */
664 public function response() {
665 /* Lazy initialization of response object for this request */
666 if ( !is_object( $this->_response ) ) {
667 $class = ( $this instanceof FauxRequest ) ? 'FauxResponse' : 'WebResponse';
668 $this->_response = new $class();
669 }
670 return $this->_response;
671 }
672
673 /**
674 * Get a request header, or false if it isn't set
675 * @param $name String: case-insensitive header name
676 */
677 public function getHeader( $name ) {
678 $name = strtoupper( $name );
679 if ( function_exists( 'apache_request_headers' ) ) {
680 if ( !$this->headers ) {
681 foreach ( apache_request_headers() as $tempName => $tempValue ) {
682 $this->headers[ strtoupper( $tempName ) ] = $tempValue;
683 }
684 }
685 if ( isset( $this->headers[$name] ) ) {
686 return $this->headers[$name];
687 } else {
688 return false;
689 }
690 } else {
691 $name = 'HTTP_' . str_replace( '-', '_', $name );
692 if ( $name === 'HTTP_CONTENT_LENGTH' && !isset( $_SERVER[$name] ) ) {
693 $name = 'CONTENT_LENGTH';
694 }
695 if ( isset( $_SERVER[$name] ) ) {
696 return $_SERVER[$name];
697 } else {
698 return false;
699 }
700 }
701 }
702
703 /**
704 * Get data from $_SESSION
705 *
706 * @param $key String: name of key in $_SESSION
707 * @return Mixed
708 */
709 public function getSessionData( $key ) {
710 if( !isset( $_SESSION[$key] ) ) {
711 return null;
712 }
713 return $_SESSION[$key];
714 }
715
716 /**
717 * Set session data
718 *
719 * @param $key String: name of key in $_SESSION
720 * @param $data Mixed
721 */
722 public function setSessionData( $key, $data ) {
723 $_SESSION[$key] = $data;
724 }
725
726 /**
727 * Returns true if the PATH_INFO ends with an extension other than a script
728 * extension. This could confuse IE for scripts that send arbitrary data which
729 * is not HTML but may be detected as such.
730 *
731 * Various past attempts to use the URL to make this check have generally
732 * run up against the fact that CGI does not provide a standard method to
733 * determine the URL. PATH_INFO may be mangled (e.g. if cgi.fix_pathinfo=0),
734 * but only by prefixing it with the script name and maybe some other stuff,
735 * the extension is not mangled. So this should be a reasonably portable
736 * way to perform this security check.
737 */
738 public function isPathInfoBad() {
739 global $wgScriptExtension;
740
741 if ( !isset( $_SERVER['PATH_INFO'] ) ) {
742 return false;
743 }
744 $pi = $_SERVER['PATH_INFO'];
745 $dotPos = strrpos( $pi, '.' );
746 if ( $dotPos === false ) {
747 return false;
748 }
749 $ext = substr( $pi, $dotPos );
750 return !in_array( $ext, array( $wgScriptExtension, '.php', '.php5' ) );
751 }
752
753 /**
754 * Parse the Accept-Language header sent by the client into an array
755 * @return array( languageCode => q-value ) sorted by q-value in descending order
756 * May contain the "language" '*', which applies to languages other than those explicitly listed.
757 * This is aligned with rfc2616 section 14.4
758 */
759 public function getAcceptLang() {
760 // Modified version of code found at http://www.thefutureoftheweb.com/blog/use-accept-language-header
761 $acceptLang = $this->getHeader( 'Accept-Language' );
762 if ( !$acceptLang ) {
763 return array();
764 }
765
766 // Return the language codes in lower case
767 $acceptLang = strtolower( $acceptLang );
768
769 // Break up string into pieces (languages and q factors)
770 $lang_parse = null;
771 preg_match_all( '/([a-z]{1,8}(-[a-z]{1,8})?|\*)\s*(;\s*q\s*=\s*(1|0(\.[0-9]+)?)?)?/',
772 $acceptLang, $lang_parse );
773
774 if ( !count( $lang_parse[1] ) ) {
775 return array();
776 }
777
778 // Create a list like "en" => 0.8
779 $langs = array_combine( $lang_parse[1], $lang_parse[4] );
780 // Set default q factor to 1
781 foreach ( $langs as $lang => $val ) {
782 if ( $val === '' ) {
783 $langs[$lang] = 1;
784 } else if ( $val == 0 ) {
785 unset($langs[$lang]);
786 }
787 }
788
789 // Sort list
790 arsort( $langs, SORT_NUMERIC );
791 return $langs;
792 }
793 }
794
795 /**
796 * Object to access the $_FILES array
797 */
798 class WebRequestUpload {
799 protected $request;
800 protected $doesExist;
801 protected $fileInfo;
802
803 /**
804 * Constructor. Should only be called by WebRequest
805 *
806 * @param $request WebRequest The associated request
807 * @param $key string Key in $_FILES array (name of form field)
808 */
809 public function __construct( $request, $key ) {
810 $this->request = $request;
811 $this->doesExist = isset( $_FILES[$key] );
812 if ( $this->doesExist ) {
813 $this->fileInfo = $_FILES[$key];
814 }
815 }
816
817 /**
818 * Return whether a file with this name was uploaded.
819 *
820 * @return bool
821 */
822 public function exists() {
823 return $this->doesExist;
824 }
825
826 /**
827 * Return the original filename of the uploaded file
828 *
829 * @return mixed Filename or null if non-existent
830 */
831 public function getName() {
832 if ( !$this->exists() ) {
833 return null;
834 }
835
836 global $wgContLang;
837 $name = $this->fileInfo['name'];
838
839 # Safari sends filenames in HTML-encoded Unicode form D...
840 # Horrid and evil! Let's try to make some kind of sense of it.
841 $name = Sanitizer::decodeCharReferences( $name );
842 $name = $wgContLang->normalize( $name );
843 wfDebug( __METHOD__ . ": {$this->fileInfo['name']} normalized to '$name'\n" );
844 return $name;
845 }
846
847 /**
848 * Return the file size of the uploaded file
849 *
850 * @return int File size or zero if non-existent
851 */
852 public function getSize() {
853 if ( !$this->exists() ) {
854 return 0;
855 }
856
857 return $this->fileInfo['size'];
858 }
859
860 /**
861 * Return the path to the temporary file
862 *
863 * @return mixed Path or null if non-existent
864 */
865 public function getTempName() {
866 if ( !$this->exists() ) {
867 return null;
868 }
869
870 return $this->fileInfo['tmp_name'];
871 }
872
873 /**
874 * Return the upload error. See link for explanation
875 * http://www.php.net/manual/en/features.file-upload.errors.php
876 *
877 * @return int One of the UPLOAD_ constants, 0 if non-existent
878 */
879 public function getError() {
880 if ( !$this->exists() ) {
881 return 0; # UPLOAD_ERR_OK
882 }
883
884 return $this->fileInfo['error'];
885 }
886
887 /**
888 * Returns whether this upload failed because of overflow of a maximum set
889 * in php.ini
890 *
891 * @return bool
892 */
893 public function isIniSizeOverflow() {
894 if ( $this->getError() == UPLOAD_ERR_INI_SIZE ) {
895 # PHP indicated that upload_max_filesize is exceeded
896 return true;
897 }
898
899 $contentLength = $this->request->getHeader( 'CONTENT_LENGTH' );
900 if ( $contentLength > wfShorthandToInteger( ini_get( 'post_max_size' ) ) ) {
901 # post_max_size is exceeded
902 return true;
903 }
904
905 return false;
906 }
907 }
908
909 /**
910 * WebRequest clone which takes values from a provided array.
911 *
912 * @ingroup HTTP
913 */
914 class FauxRequest extends WebRequest {
915 private $wasPosted = false;
916 private $session = array();
917
918 /**
919 * @param $data Array of *non*-urlencoded key => value pairs, the
920 * fake GET/POST values
921 * @param $wasPosted Bool: whether to treat the data as POST
922 * @param $session Mixed: session array or null
923 */
924 public function __construct( $data, $wasPosted = false, $session = null ) {
925 if( is_array( $data ) ) {
926 $this->data = $data;
927 } else {
928 throw new MWException( "FauxRequest() got bogus data" );
929 }
930 $this->wasPosted = $wasPosted;
931 if( $session )
932 $this->session = $session;
933 }
934
935 private function notImplemented( $method ) {
936 throw new MWException( "{$method}() not implemented" );
937 }
938
939 public function getText( $name, $default = '' ) {
940 # Override; don't recode since we're using internal data
941 return (string)$this->getVal( $name, $default );
942 }
943
944 public function getValues() {
945 return $this->data;
946 }
947
948 public function wasPosted() {
949 return $this->wasPosted;
950 }
951
952 public function checkSessionCookie() {
953 return false;
954 }
955
956 public function getRequestURL() {
957 $this->notImplemented( __METHOD__ );
958 }
959
960 public function appendQuery( $query ) {
961 global $wgTitle;
962 $basequery = '';
963 foreach( $this->data as $var => $val ) {
964 if ( $var == 'title' ) {
965 continue;
966 }
967 if ( is_array( $val ) ) {
968 /* This will happen given a request like
969 * http://en.wikipedia.org/w/index.php?title[]=Special:Userlogin&returnto[]=Main_Page
970 */
971 continue;
972 }
973 $basequery .= '&' . urlencode( $var ) . '=' . urlencode( $val );
974 }
975 $basequery .= '&' . $query;
976
977 # Trim the extra &
978 $basequery = substr( $basequery, 1 );
979 return $wgTitle->getLocalURL( $basequery );
980 }
981
982 public function getHeader( $name ) {
983 return isset( $this->headers[$name] ) ? $this->headers[$name] : false;
984 }
985
986 public function setHeader( $name, $val ) {
987 $this->headers[$name] = $val;
988 }
989
990 public function getSessionData( $key ) {
991 if( isset( $this->session[$key] ) )
992 return $this->session[$key];
993 }
994
995 public function setSessionData( $key, $data ) {
996 $this->session[$key] = $data;
997 }
998
999 public function isPathInfoBad() {
1000 return false;
1001 }
1002 }