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