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