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