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