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