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