* recover dropped check of $wgUsePathInfo from r81363
[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['SCRIPT_NAME'] ) ) {
498 // Probably IIS; doesn't set REQUEST_URI
499 $base = $_SERVER['SCRIPT_NAME'];
500 if( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
501 $base .= '?' . $_SERVER['QUERY_STRING'];
502 }
503 } else {
504 // This shouldn't happen!
505 throw new MWException( "Web server doesn't provide either " .
506 "REQUEST_URI or SCRIPT_NAME. Report details of your " .
507 "web server configuration to http://bugzilla.wikimedia.org/" );
508 }
509 // User-agents should not send a fragment with the URI, but
510 // if they do, and the web server passes it on to us, we
511 // need to strip it or we get false-positive redirect loops
512 // or weird output URLs
513 $hash = strpos( $base, '#' );
514 if( $hash !== false ) {
515 $base = substr( $base, 0, $hash );
516 }
517 if( $base{0} == '/' ) {
518 return $base;
519 } else {
520 // We may get paths with a host prepended; strip it.
521 return preg_replace( '!^[^:]+://[^/]+/!', '/', $base );
522 }
523 }
524
525 /**
526 * Return the request URI with the canonical service and hostname.
527 *
528 * @return String
529 */
530 public function getFullRequestURL() {
531 global $wgServer;
532 return $wgServer . $this->getRequestURL();
533 }
534
535 /**
536 * Take an arbitrary query and rewrite the present URL to include it
537 * @param $query String: query string fragment; do not include initial '?'
538 *
539 * @return String
540 */
541 public function appendQuery( $query ) {
542 global $wgTitle;
543 $basequery = '';
544 foreach( $_GET as $var => $val ) {
545 if ( $var == 'title' ) {
546 continue;
547 }
548 if ( is_array( $val ) ) {
549 /* This will happen given a request like
550 * http://en.wikipedia.org/w/index.php?title[]=Special:Userlogin&returnto[]=Main_Page
551 */
552 continue;
553 }
554 $basequery .= '&' . urlencode( $var ) . '=' . urlencode( $val );
555 }
556 $basequery .= '&' . $query;
557
558 # Trim the extra &
559 $basequery = substr( $basequery, 1 );
560 return $wgTitle->getLocalURL( $basequery );
561 }
562
563 /**
564 * HTML-safe version of appendQuery().
565 *
566 * @param $query String: query string fragment; do not include initial '?'
567 * @return String
568 */
569 public function escapeAppendQuery( $query ) {
570 return htmlspecialchars( $this->appendQuery( $query ) );
571 }
572
573 public function appendQueryValue( $key, $value, $onlyquery = false ) {
574 return $this->appendQueryArray( array( $key => $value ), $onlyquery );
575 }
576
577 /**
578 * Appends or replaces value of query variables.
579 *
580 * @param $array Array of values to replace/add to query
581 * @param $onlyquery Bool: whether to only return the query string and not
582 * the complete URL
583 * @return String
584 */
585 public function appendQueryArray( $array, $onlyquery = false ) {
586 global $wgTitle;
587 $newquery = $_GET;
588 unset( $newquery['title'] );
589 $newquery = array_merge( $newquery, $array );
590 $query = wfArrayToCGI( $newquery );
591 return $onlyquery ? $query : $wgTitle->getLocalURL( $query );
592 }
593
594 /**
595 * Check for limit and offset parameters on the input, and return sensible
596 * defaults if not given. The limit must be positive and is capped at 5000.
597 * Offset must be positive but is not capped.
598 *
599 * @param $deflimit Integer: limit to use if no input and the user hasn't set the option.
600 * @param $optionname String: to specify an option other than rclimit to pull from.
601 * @return array first element is limit, second is offset
602 */
603 public function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
604 global $wgUser;
605
606 $limit = $this->getInt( 'limit', 0 );
607 if( $limit < 0 ) {
608 $limit = 0;
609 }
610 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
611 $limit = (int)$wgUser->getOption( $optionname );
612 }
613 if( $limit <= 0 ) {
614 $limit = $deflimit;
615 }
616 if( $limit > 5000 ) {
617 $limit = 5000; # We have *some* limits...
618 }
619
620 $offset = $this->getInt( 'offset', 0 );
621 if( $offset < 0 ) {
622 $offset = 0;
623 }
624
625 return array( $limit, $offset );
626 }
627
628 /**
629 * Return the path to the temporary file where PHP has stored the upload.
630 *
631 * @param $key String:
632 * @return string or NULL if no such file.
633 */
634 public function getFileTempname( $key ) {
635 $file = new WebRequestUpload( $this, $key );
636 return $file->getTempName();
637 }
638
639 /**
640 * Return the size of the upload, or 0.
641 *
642 * @deprecated
643 * @param $key String:
644 * @return integer
645 */
646 public function getFileSize( $key ) {
647 $file = new WebRequestUpload( $this, $key );
648 return $file->getSize();
649 }
650
651 /**
652 * Return the upload error or 0
653 *
654 * @param $key String:
655 * @return integer
656 */
657 public function getUploadError( $key ) {
658 $file = new WebRequestUpload( $this, $key );
659 return $file->getError();
660 }
661
662 /**
663 * Return the original filename of the uploaded file, as reported by
664 * the submitting user agent. HTML-style character entities are
665 * interpreted and normalized to Unicode normalization form C, in part
666 * to deal with weird input from Safari with non-ASCII filenames.
667 *
668 * Other than this the name is not verified for being a safe filename.
669 *
670 * @param $key String:
671 * @return string or NULL if no such file.
672 */
673 public function getFileName( $key ) {
674 $file = new WebRequestUpload( $this, $key );
675 return $file->getName();
676 }
677
678 /**
679 * Return a WebRequestUpload object corresponding to the key
680 *
681 * @param @key string
682 * @return WebRequestUpload
683 */
684 public function getUpload( $key ) {
685 return new WebRequestUpload( $this, $key );
686 }
687
688 /**
689 * Return a handle to WebResponse style object, for setting cookies,
690 * headers and other stuff, for Request being worked on.
691 *
692 * @return WebResponse
693 */
694 public function response() {
695 /* Lazy initialization of response object for this request */
696 if ( !is_object( $this->response ) ) {
697 $class = ( $this instanceof FauxRequest ) ? 'FauxResponse' : 'WebResponse';
698 $this->response = new $class();
699 }
700 return $this->response;
701 }
702
703 /**
704 * Get a request header, or false if it isn't set
705 * @param $name String: case-insensitive header name
706 */
707 public function getHeader( $name ) {
708 $name = strtoupper( $name );
709 if ( function_exists( 'apache_request_headers' ) ) {
710 if ( !$this->headers ) {
711 foreach ( apache_request_headers() as $tempName => $tempValue ) {
712 $this->headers[ strtoupper( $tempName ) ] = $tempValue;
713 }
714 }
715 if ( isset( $this->headers[$name] ) ) {
716 return $this->headers[$name];
717 } else {
718 return false;
719 }
720 } else {
721 $name = 'HTTP_' . str_replace( '-', '_', $name );
722 if ( $name === 'HTTP_CONTENT_LENGTH' && !isset( $_SERVER[$name] ) ) {
723 $name = 'CONTENT_LENGTH';
724 }
725 if ( isset( $_SERVER[$name] ) ) {
726 return $_SERVER[$name];
727 } else {
728 return false;
729 }
730 }
731 }
732
733 /**
734 * Get data from $_SESSION
735 *
736 * @param $key String: name of key in $_SESSION
737 * @return Mixed
738 */
739 public function getSessionData( $key ) {
740 if( !isset( $_SESSION[$key] ) ) {
741 return null;
742 }
743 return $_SESSION[$key];
744 }
745
746 /**
747 * Set session data
748 *
749 * @param $key String: name of key in $_SESSION
750 * @param $data Mixed
751 */
752 public function setSessionData( $key, $data ) {
753 $_SESSION[$key] = $data;
754 }
755
756 /**
757 * Returns true if the PATH_INFO ends with an extension other than a script
758 * extension. This could confuse IE for scripts that send arbitrary data which
759 * is not HTML but may be detected as such.
760 *
761 * Various past attempts to use the URL to make this check have generally
762 * run up against the fact that CGI does not provide a standard method to
763 * determine the URL. PATH_INFO may be mangled (e.g. if cgi.fix_pathinfo=0),
764 * but only by prefixing it with the script name and maybe some other stuff,
765 * the extension is not mangled. So this should be a reasonably portable
766 * way to perform this security check.
767 */
768 public function isPathInfoBad() {
769 global $wgScriptExtension;
770
771 if ( !isset( $_SERVER['PATH_INFO'] ) ) {
772 return false;
773 }
774 $pi = $_SERVER['PATH_INFO'];
775 $dotPos = strrpos( $pi, '.' );
776 if ( $dotPos === false ) {
777 return false;
778 }
779 $ext = substr( $pi, $dotPos );
780 return !in_array( $ext, array( $wgScriptExtension, '.php', '.php5' ) );
781 }
782
783 /**
784 * Parse the Accept-Language header sent by the client into an array
785 * @return array( languageCode => q-value ) sorted by q-value in descending order
786 * May contain the "language" '*', which applies to languages other than those explicitly listed.
787 * This is aligned with rfc2616 section 14.4
788 */
789 public function getAcceptLang() {
790 // Modified version of code found at http://www.thefutureoftheweb.com/blog/use-accept-language-header
791 $acceptLang = $this->getHeader( 'Accept-Language' );
792 if ( !$acceptLang ) {
793 return array();
794 }
795
796 // Return the language codes in lower case
797 $acceptLang = strtolower( $acceptLang );
798
799 // Break up string into pieces (languages and q factors)
800 $lang_parse = null;
801 preg_match_all( '/([a-z]{1,8}(-[a-z]{1,8})?|\*)\s*(;\s*q\s*=\s*(1|0(\.[0-9]+)?)?)?/',
802 $acceptLang, $lang_parse );
803
804 if ( !count( $lang_parse[1] ) ) {
805 return array();
806 }
807
808 // Create a list like "en" => 0.8
809 $langs = array_combine( $lang_parse[1], $lang_parse[4] );
810 // Set default q factor to 1
811 foreach ( $langs as $lang => $val ) {
812 if ( $val === '' ) {
813 $langs[$lang] = 1;
814 } else if ( $val == 0 ) {
815 unset($langs[$lang]);
816 }
817 }
818
819 // Sort list
820 arsort( $langs, SORT_NUMERIC );
821 return $langs;
822 }
823 }
824
825 /**
826 * Object to access the $_FILES array
827 */
828 class WebRequestUpload {
829 protected $request;
830 protected $doesExist;
831 protected $fileInfo;
832
833 /**
834 * Constructor. Should only be called by WebRequest
835 *
836 * @param $request WebRequest The associated request
837 * @param $key string Key in $_FILES array (name of form field)
838 */
839 public function __construct( $request, $key ) {
840 $this->request = $request;
841 $this->doesExist = isset( $_FILES[$key] );
842 if ( $this->doesExist ) {
843 $this->fileInfo = $_FILES[$key];
844 }
845 }
846
847 /**
848 * Return whether a file with this name was uploaded.
849 *
850 * @return bool
851 */
852 public function exists() {
853 return $this->doesExist;
854 }
855
856 /**
857 * Return the original filename of the uploaded file
858 *
859 * @return mixed Filename or null if non-existent
860 */
861 public function getName() {
862 if ( !$this->exists() ) {
863 return null;
864 }
865
866 global $wgContLang;
867 $name = $this->fileInfo['name'];
868
869 # Safari sends filenames in HTML-encoded Unicode form D...
870 # Horrid and evil! Let's try to make some kind of sense of it.
871 $name = Sanitizer::decodeCharReferences( $name );
872 $name = $wgContLang->normalize( $name );
873 wfDebug( __METHOD__ . ": {$this->fileInfo['name']} normalized to '$name'\n" );
874 return $name;
875 }
876
877 /**
878 * Return the file size of the uploaded file
879 *
880 * @return int File size or zero if non-existent
881 */
882 public function getSize() {
883 if ( !$this->exists() ) {
884 return 0;
885 }
886
887 return $this->fileInfo['size'];
888 }
889
890 /**
891 * Return the path to the temporary file
892 *
893 * @return mixed Path or null if non-existent
894 */
895 public function getTempName() {
896 if ( !$this->exists() ) {
897 return null;
898 }
899
900 return $this->fileInfo['tmp_name'];
901 }
902
903 /**
904 * Return the upload error. See link for explanation
905 * http://www.php.net/manual/en/features.file-upload.errors.php
906 *
907 * @return int One of the UPLOAD_ constants, 0 if non-existent
908 */
909 public function getError() {
910 if ( !$this->exists() ) {
911 return 0; # UPLOAD_ERR_OK
912 }
913
914 return $this->fileInfo['error'];
915 }
916
917 /**
918 * Returns whether this upload failed because of overflow of a maximum set
919 * in php.ini
920 *
921 * @return bool
922 */
923 public function isIniSizeOverflow() {
924 if ( $this->getError() == UPLOAD_ERR_INI_SIZE ) {
925 # PHP indicated that upload_max_filesize is exceeded
926 return true;
927 }
928
929 $contentLength = $this->request->getHeader( 'CONTENT_LENGTH' );
930 if ( $contentLength > wfShorthandToInteger( ini_get( 'post_max_size' ) ) ) {
931 # post_max_size is exceeded
932 return true;
933 }
934
935 return false;
936 }
937 }
938
939 /**
940 * WebRequest clone which takes values from a provided array.
941 *
942 * @ingroup HTTP
943 */
944 class FauxRequest extends WebRequest {
945 private $wasPosted = false;
946 private $session = array();
947
948 /**
949 * @param $data Array of *non*-urlencoded key => value pairs, the
950 * fake GET/POST values
951 * @param $wasPosted Bool: whether to treat the data as POST
952 * @param $session Mixed: session array or null
953 */
954 public function __construct( $data, $wasPosted = false, $session = null ) {
955 if( is_array( $data ) ) {
956 $this->data = $data;
957 } else {
958 throw new MWException( "FauxRequest() got bogus data" );
959 }
960 $this->wasPosted = $wasPosted;
961 if( $session )
962 $this->session = $session;
963 }
964
965 private function notImplemented( $method ) {
966 throw new MWException( "{$method}() not implemented" );
967 }
968
969 public function getText( $name, $default = '' ) {
970 # Override; don't recode since we're using internal data
971 return (string)$this->getVal( $name, $default );
972 }
973
974 public function getValues() {
975 return $this->data;
976 }
977
978 public function wasPosted() {
979 return $this->wasPosted;
980 }
981
982 public function checkSessionCookie() {
983 return false;
984 }
985
986 public function getRequestURL() {
987 $this->notImplemented( __METHOD__ );
988 }
989
990 public function appendQuery( $query ) {
991 global $wgTitle;
992 $basequery = '';
993 foreach( $this->data as $var => $val ) {
994 if ( $var == 'title' ) {
995 continue;
996 }
997 if ( is_array( $val ) ) {
998 /* This will happen given a request like
999 * http://en.wikipedia.org/w/index.php?title[]=Special:Userlogin&returnto[]=Main_Page
1000 */
1001 continue;
1002 }
1003 $basequery .= '&' . urlencode( $var ) . '=' . urlencode( $val );
1004 }
1005 $basequery .= '&' . $query;
1006
1007 # Trim the extra &
1008 $basequery = substr( $basequery, 1 );
1009 return $wgTitle->getLocalURL( $basequery );
1010 }
1011
1012 public function getHeader( $name ) {
1013 return isset( $this->headers[$name] ) ? $this->headers[$name] : false;
1014 }
1015
1016 public function setHeader( $name, $val ) {
1017 $this->headers[$name] = $val;
1018 }
1019
1020 public function getSessionData( $key ) {
1021 if( isset( $this->session[$key] ) )
1022 return $this->session[$key];
1023 }
1024
1025 public function setSessionData( $key, $data ) {
1026 $this->session[$key] = $data;
1027 }
1028
1029 public function isPathInfoBad() {
1030 return false;
1031 }
1032 }