Delay $wgContLang unstubbing
[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 var $data = array();
47 var $headers;
48 private $_response;
49
50 function __construct() {
51 /// @fixme This preemptive de-quoting can interfere with other web libraries
52 /// and increases our memory footprint. It would be cleaner to do on
53 /// demand; but currently we have no wrapper for $_SERVER etc.
54 $this->checkMagicQuotes();
55
56 // POST overrides GET data
57 // We don't use $_REQUEST here to avoid interference from cookies...
58 $this->data = $_POST + $_GET;
59 }
60
61 /**
62 * Check for title, action, and/or variant data in the URL
63 * and interpolate it into the GET variables.
64 * This should only be run after $wgContLang is available,
65 * as we may need the list of language variants to determine
66 * available variant URLs.
67 */
68 function interpolateTitle() {
69 global $wgUsePathInfo;
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 if ( !empty( $_SERVER['REQUEST_URI'] ) ) {
76 // Slurp out the path portion to examine...
77 $url = $_SERVER['REQUEST_URI'];
78 if ( !preg_match( '!^https?://!', $url ) ) {
79 $url = 'http://unused' . $url;
80 }
81 $a = parse_url( $url );
82 if( $a ) {
83 $path = isset( $a['path'] ) ? $a['path'] : '';
84
85 global $wgScript;
86 if( $path == $wgScript ) {
87 // Script inside a rewrite path?
88 // Abort to keep from breaking...
89 return;
90 }
91 // Raw PATH_INFO style
92 $matches = $this->extractTitle( $path, "$wgScript/$1" );
93
94 global $wgArticlePath;
95 if( !$matches && $wgArticlePath ) {
96 $matches = $this->extractTitle( $path, $wgArticlePath );
97 }
98
99 global $wgActionPaths;
100 if( !$matches && $wgActionPaths ) {
101 $matches = $this->extractTitle( $path, $wgActionPaths, 'action' );
102 }
103
104 global $wgVariantArticlePath, $wgContLang;
105 if( !$matches && $wgVariantArticlePath ) {
106 $variantPaths = array();
107 foreach( $wgContLang->getVariants() as $variant ) {
108 $variantPaths[$variant] =
109 str_replace( '$2', $variant, $wgVariantArticlePath );
110 }
111 $matches = $this->extractTitle( $path, $variantPaths, 'variant' );
112 }
113 }
114 } elseif ( isset( $_SERVER['ORIG_PATH_INFO'] ) && $_SERVER['ORIG_PATH_INFO'] != '' ) {
115 // Mangled PATH_INFO
116 // http://bugs.php.net/bug.php?id=31892
117 // Also reported when ini_get('cgi.fix_pathinfo')==false
118 $matches['title'] = substr( $_SERVER['ORIG_PATH_INFO'], 1 );
119
120 } elseif ( isset( $_SERVER['PATH_INFO'] ) && ($_SERVER['PATH_INFO'] != '') ) {
121 // Regular old PATH_INFO yay
122 $matches['title'] = substr( $_SERVER['PATH_INFO'], 1 );
123 }
124 foreach( $matches as $key => $val) {
125 $this->data[$key] = $_GET[$key] = $_REQUEST[$key] = $val;
126 }
127 }
128 }
129
130 /**
131 * Internal URL rewriting function; tries to extract page title and,
132 * optionally, one other fixed parameter value from a URL path.
133 *
134 * @param $path string: the URL path given from the client
135 * @param $bases array: one or more URLs, optionally with $1 at the end
136 * @param $key string: if provided, the matching key in $bases will be
137 * passed on as the value of this URL parameter
138 * @return array of URL variables to interpolate; empty if no match
139 */
140 private function extractTitle( $path, $bases, $key=false ) {
141 foreach( (array)$bases as $keyValue => $base ) {
142 // Find the part after $wgArticlePath
143 $base = str_replace( '$1', '', $base );
144 $baseLen = strlen( $base );
145 if( substr( $path, 0, $baseLen ) == $base ) {
146 $raw = substr( $path, $baseLen );
147 if( $raw !== '' ) {
148 $matches = array( 'title' => rawurldecode( $raw ) );
149 if( $key ) {
150 $matches[$key] = $keyValue;
151 }
152 return $matches;
153 }
154 }
155 }
156 return array();
157 }
158
159 /**
160 * Recursively strips slashes from the given array;
161 * used for undoing the evil that is magic_quotes_gpc.
162 * @param $arr array: will be modified
163 * @return array the original array
164 * @private
165 */
166 function &fix_magic_quotes( &$arr ) {
167 foreach( $arr as $key => $val ) {
168 if( is_array( $val ) ) {
169 $this->fix_magic_quotes( $arr[$key] );
170 } else {
171 $arr[$key] = stripslashes( $val );
172 }
173 }
174 return $arr;
175 }
176
177 /**
178 * If magic_quotes_gpc option is on, run the global arrays
179 * through fix_magic_quotes to strip out the stupid slashes.
180 * WARNING: This should only be done once! Running a second
181 * time could damage the values.
182 * @private
183 */
184 function checkMagicQuotes() {
185 if ( function_exists( 'get_magic_quotes_gpc' ) && get_magic_quotes_gpc() ) {
186 $this->fix_magic_quotes( $_COOKIE );
187 $this->fix_magic_quotes( $_ENV );
188 $this->fix_magic_quotes( $_GET );
189 $this->fix_magic_quotes( $_POST );
190 $this->fix_magic_quotes( $_REQUEST );
191 $this->fix_magic_quotes( $_SERVER );
192 }
193 }
194
195 /**
196 * Recursively normalizes UTF-8 strings in the given array.
197 * @param $data string or array
198 * @return cleaned-up version of the given
199 * @private
200 */
201 function normalizeUnicode( $data ) {
202 if( is_array( $data ) ) {
203 foreach( $data as $key => $val ) {
204 $data[$key] = $this->normalizeUnicode( $val );
205 }
206 } else {
207 $data = UtfNormal::cleanUp( $data );
208 }
209 return $data;
210 }
211
212 /**
213 * Fetch a value from the given array or return $default if it's not set.
214 *
215 * @param $arr array
216 * @param $name string
217 * @param $default mixed
218 * @return mixed
219 * @private
220 */
221 function getGPCVal( $arr, $name, $default ) {
222 if( isset( $arr[$name] ) ) {
223 $data = $arr[$name];
224 if( isset( $_GET[$name] ) && !is_array( $data ) ) {
225 # Check for alternate/legacy character encoding.
226 $data = $this->checkTitleEncoding( $data );
227 }
228 $data = $this->normalizeUnicode( $data );
229 return $data;
230 } else {
231 return $default;
232 }
233 }
234
235 protected function checkTitleEncoding( $s ) {
236 global $wgContLang;
237 if( !isset($wgContLang) ) return $s;
238 # Check for non-UTF-8 URLs
239 $ishigh = preg_match( '/[\x80-\xff]/', $s);
240 if( !$ishigh ) return $s;
241
242 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
243 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
244 if( $isutf8 ) return $s;
245 # Do the heavy lifting by unstubbing $wgContLang
246 return $wgContLang->iconv( $wgContLang->fallback8bitEncoding(), "utf-8", $s );
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 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 null;
266 } else {
267 return (string)$val;
268 }
269 }
270
271 /**
272 * Set an aribtrary value into our get/post data.
273 * @param $key string Key name to use
274 * @param $value mixed Value to set
275 * @return mixed old value if one was present, null otherwise
276 */
277 function setVal( $key, $value ) {
278 $ret = isset( $this->data[$key] ) ? $this->data[$key] : null;
279 $this->data[$key] = $value;
280 return $ret;
281 }
282
283 /**
284 * Fetch an array from the input or return $default if it's not set.
285 * If source was scalar, will return an array with a single element.
286 * If no source and no default, returns NULL.
287 *
288 * @param $name string
289 * @param $default array: optional default (or NULL)
290 * @return array
291 */
292 function getArray( $name, $default = NULL ) {
293 $val = $this->getGPCVal( $this->data, $name, $default );
294 if( is_null( $val ) ) {
295 return null;
296 } else {
297 return (array)$val;
298 }
299 }
300
301 /**
302 * Fetch an array of integers, or return $default if it's not set.
303 * If source was scalar, will return an array with a single element.
304 * If no source and no default, returns NULL.
305 * If an array is returned, contents are guaranteed to be integers.
306 *
307 * @param $name string
308 * @param $default array: option default (or NULL)
309 * @return array of ints
310 */
311 function getIntArray( $name, $default = NULL ) {
312 $val = $this->getArray( $name, $default );
313 if( is_array( $val ) ) {
314 $val = array_map( 'intval', $val );
315 }
316 return $val;
317 }
318
319 /**
320 * Fetch an integer value from the input or return $default if not set.
321 * Guaranteed to return an integer; non-numeric input will typically
322 * return 0.
323 * @param $name string
324 * @param $default int
325 * @return int
326 */
327 function getInt( $name, $default = 0 ) {
328 return intval( $this->getVal( $name, $default ) );
329 }
330
331 /**
332 * Fetch an integer value from the input or return null if empty.
333 * Guaranteed to return an integer or null; non-numeric input will
334 * typically return null.
335 * @param $name string
336 * @return int
337 */
338 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 * @param $name string
350 * @param $default bool
351 * @return bool
352 */
353 function getBool( $name, $default = false ) {
354 return $this->getVal( $name, $default ) ? true : false;
355 }
356
357 /**
358 * Return true if the named value is set in the input, whatever that
359 * value is (even "0"). Return false if the named value is not set.
360 * Example use is checking for the presence of check boxes in forms.
361 * @param $name string
362 * @return bool
363 */
364 function getCheck( $name ) {
365 # Checkboxes and buttons are only present when clicked
366 # Presence connotes truth, abscense false
367 $val = $this->getVal( $name, NULL );
368 return isset( $val );
369 }
370
371 /**
372 * Fetch a text string from the given array or return $default if it's not
373 * set. \r is stripped from the text, and with some language modules there
374 * is an input transliteration applied. This should generally be used for
375 * form <textarea> and <input> fields. Used for user-supplied freeform text
376 * input (for which input transformations may be required - e.g. Esperanto
377 * x-coding).
378 *
379 * @param $name string
380 * @param $default string: optional
381 * @return string
382 */
383 function getText( $name, $default = '' ) {
384 global $wgContLang;
385 $val = $this->getVal( $name, $default );
386 return str_replace( "\r\n", "\n",
387 $wgContLang->recodeInput( $val ) );
388 }
389
390 /**
391 * Extracts the given named values into an array.
392 * If no arguments are given, returns all input values.
393 * No transformation is performed on the values.
394 */
395 function getValues() {
396 $names = func_get_args();
397 if ( count( $names ) == 0 ) {
398 $names = array_keys( $this->data );
399 }
400
401 $retVal = array();
402 foreach ( $names as $name ) {
403 $value = $this->getVal( $name );
404 if ( !is_null( $value ) ) {
405 $retVal[$name] = $value;
406 }
407 }
408 return $retVal;
409 }
410
411 /**
412 * Returns true if the present request was reached by a POST operation,
413 * false otherwise (GET, HEAD, or command-line).
414 *
415 * Note that values retrieved by the object may come from the
416 * GET URL etc even on a POST request.
417 *
418 * @return bool
419 */
420 function wasPosted() {
421 return $_SERVER['REQUEST_METHOD'] == 'POST';
422 }
423
424 /**
425 * Returns true if there is a session cookie set.
426 * This does not necessarily mean that the user is logged in!
427 *
428 * If you want to check for an open session, use session_id()
429 * instead; that will also tell you if the session was opened
430 * during the current request (in which case the cookie will
431 * be sent back to the client at the end of the script run).
432 *
433 * @return bool
434 */
435 function checkSessionCookie() {
436 return isset( $_COOKIE[session_name()] );
437 }
438
439 /**
440 * Return the path portion of the request URI.
441 * @return string
442 */
443 function getRequestURL() {
444 if( isset( $_SERVER['REQUEST_URI'] ) ) {
445 $base = $_SERVER['REQUEST_URI'];
446 } elseif( isset( $_SERVER['SCRIPT_NAME'] ) ) {
447 // Probably IIS; doesn't set REQUEST_URI
448 $base = $_SERVER['SCRIPT_NAME'];
449 if( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
450 $base .= '?' . $_SERVER['QUERY_STRING'];
451 }
452 } else {
453 // This shouldn't happen!
454 throw new MWException( "Web server doesn't provide either " .
455 "REQUEST_URI or SCRIPT_NAME. Report details of your " .
456 "web server configuration to http://bugzilla.wikimedia.org/" );
457 }
458 // User-agents should not send a fragment with the URI, but
459 // if they do, and the web server passes it on to us, we
460 // need to strip it or we get false-positive redirect loops
461 // or weird output URLs
462 $hash = strpos( $base, '#' );
463 if( $hash !== false ) {
464 $base = substr( $base, 0, $hash );
465 }
466 if( $base{0} == '/' ) {
467 return $base;
468 } else {
469 // We may get paths with a host prepended; strip it.
470 return preg_replace( '!^[^:]+://[^/]+/!', '/', $base );
471 }
472 }
473
474 /**
475 * Return the request URI with the canonical service and hostname.
476 * @return string
477 */
478 function getFullRequestURL() {
479 global $wgServer;
480 return $wgServer . $this->getRequestURL();
481 }
482
483 /**
484 * Take an arbitrary query and rewrite the present URL to include it
485 * @param $query String: query string fragment; do not include initial '?'
486 * @return string
487 */
488 function appendQuery( $query ) {
489 global $wgTitle;
490 $basequery = '';
491 foreach( $_GET as $var => $val ) {
492 if ( $var == 'title' )
493 continue;
494 if ( is_array( $val ) )
495 /* This will happen given a request like
496 * http://en.wikipedia.org/w/index.php?title[]=Special:Userlogin&returnto[]=Main_Page
497 */
498 continue;
499 $basequery .= '&' . urlencode( $var ) . '=' . urlencode( $val );
500 }
501 $basequery .= '&' . $query;
502
503 # Trim the extra &
504 $basequery = substr( $basequery, 1 );
505 return $wgTitle->getLocalURL( $basequery );
506 }
507
508 /**
509 * HTML-safe version of appendQuery().
510 * @param $query String: query string fragment; do not include initial '?'
511 * @return string
512 */
513 function escapeAppendQuery( $query ) {
514 return htmlspecialchars( $this->appendQuery( $query ) );
515 }
516
517 function appendQueryValue( $key, $value, $onlyquery = false ) {
518 return $this->appendQueryArray( array( $key => $value ), $onlyquery );
519 }
520
521 /**
522 * Appends or replaces value of query variables.
523 * @param $array Array of values to replace/add to query
524 * @param $onlyquery Bool: whether to only return the query string and not
525 * the complete URL
526 * @return string
527 */
528 function appendQueryArray( $array, $onlyquery = false ) {
529 global $wgTitle;
530 $newquery = $_GET;
531 unset( $newquery['title'] );
532 $newquery = array_merge( $newquery, $array );
533 $query = wfArrayToCGI( $newquery );
534 return $onlyquery ? $query : $wgTitle->getLocalURL( $query );
535 }
536
537 /**
538 * Check for limit and offset parameters on the input, and return sensible
539 * defaults if not given. The limit must be positive and is capped at 5000.
540 * Offset must be positive but is not capped.
541 *
542 * @param $deflimit Integer: limit to use if no input and the user hasn't set the option.
543 * @param $optionname String: to specify an option other than rclimit to pull from.
544 * @return array first element is limit, second is offset
545 */
546 function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
547 global $wgUser;
548
549 $limit = $this->getInt( 'limit', 0 );
550 if( $limit < 0 ) $limit = 0;
551 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
552 $limit = (int)$wgUser->getOption( $optionname );
553 }
554 if( $limit <= 0 ) $limit = $deflimit;
555 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
556
557 $offset = $this->getInt( 'offset', 0 );
558 if( $offset < 0 ) $offset = 0;
559
560 return array( $limit, $offset );
561 }
562
563 /**
564 * Return the path to the temporary file where PHP has stored the upload.
565 * @param $key String:
566 * @return string or NULL if no such file.
567 */
568 function getFileTempname( $key ) {
569 if( !isset( $_FILES[$key] ) ) {
570 return NULL;
571 }
572 return $_FILES[$key]['tmp_name'];
573 }
574
575 /**
576 * Return the size of the upload, or 0.
577 * @param $key String:
578 * @return integer
579 */
580 function getFileSize( $key ) {
581 if( !isset( $_FILES[$key] ) ) {
582 return 0;
583 }
584 return $_FILES[$key]['size'];
585 }
586
587 /**
588 * Return the upload error or 0
589 * @param $key String:
590 * @return integer
591 */
592 function getUploadError( $key ) {
593 if( !isset( $_FILES[$key] ) || !isset( $_FILES[$key]['error'] ) ) {
594 return 0/*UPLOAD_ERR_OK*/;
595 }
596 return $_FILES[$key]['error'];
597 }
598
599 /**
600 * Return the original filename of the uploaded file, as reported by
601 * the submitting user agent. HTML-style character entities are
602 * interpreted and normalized to Unicode normalization form C, in part
603 * to deal with weird input from Safari with non-ASCII filenames.
604 *
605 * Other than this the name is not verified for being a safe filename.
606 *
607 * @param $key String:
608 * @return string or NULL if no such file.
609 */
610 function getFileName( $key ) {
611 if( !isset( $_FILES[$key] ) ) {
612 return NULL;
613 }
614 $name = $_FILES[$key]['name'];
615
616 # Safari sends filenames in HTML-encoded Unicode form D...
617 # Horrid and evil! Let's try to make some kind of sense of it.
618 $name = Sanitizer::decodeCharReferences( $name );
619 $name = UtfNormal::cleanUp( $name );
620 wfDebug( "WebRequest::getFileName() '" . $_FILES[$key]['name'] . "' normalized to '$name'\n" );
621 return $name;
622 }
623
624 /**
625 * Return a handle to WebResponse style object, for setting cookies,
626 * headers and other stuff, for Request being worked on.
627 */
628 function response() {
629 /* Lazy initialization of response object for this request */
630 if (!is_object($this->_response)) {
631 $this->_response = new WebResponse;
632 }
633 return $this->_response;
634 }
635
636 /**
637 * Get a request header, or false if it isn't set
638 * @param $name String: case-insensitive header name
639 */
640 function getHeader( $name ) {
641 $name = strtoupper( $name );
642 if ( function_exists( 'apache_request_headers' ) ) {
643 if ( !isset( $this->headers ) ) {
644 $this->headers = array();
645 foreach ( apache_request_headers() as $tempName => $tempValue ) {
646 $this->headers[ strtoupper( $tempName ) ] = $tempValue;
647 }
648 }
649 if ( isset( $this->headers[$name] ) ) {
650 return $this->headers[$name];
651 } else {
652 return false;
653 }
654 } else {
655 $name = 'HTTP_' . str_replace( '-', '_', $name );
656 if ( isset( $_SERVER[$name] ) ) {
657 return $_SERVER[$name];
658 } else {
659 return false;
660 }
661 }
662 }
663
664 /*
665 * Get data from $_SESSION
666 */
667 function getSessionData( $key ) {
668 if( !isset( $_SESSION[$key] ) )
669 return null;
670 return $_SESSION[$key];
671 }
672 function setSessionData( $key, $data ) {
673 $_SESSION[$key] = $data;
674 }
675 }
676
677 /**
678 * WebRequest clone which takes values from a provided array.
679 *
680 * @ingroup HTTP
681 */
682 class FauxRequest extends WebRequest {
683 var $wasPosted = false;
684
685 /**
686 * @param $data Array of *non*-urlencoded key => value pairs, the
687 * fake GET/POST values
688 * @param $wasPosted Bool: whether to treat the data as POST
689 */
690 function FauxRequest( $data, $wasPosted = false, $session = null ) {
691 if( is_array( $data ) ) {
692 $this->data = $data;
693 } else {
694 throw new MWException( "FauxRequest() got bogus data" );
695 }
696 $this->wasPosted = $wasPosted;
697 $this->headers = array();
698 $this->session = $session ? $session : array();
699 }
700
701 function notImplemented( $method ) {
702 throw new MWException( "{$method}() not implemented" );
703 }
704
705 function getText( $name, $default = '' ) {
706 # Override; don't recode since we're using internal data
707 return (string)$this->getVal( $name, $default );
708 }
709
710 function getValues() {
711 return $this->data;
712 }
713
714 function wasPosted() {
715 return $this->wasPosted;
716 }
717
718 function checkSessionCookie() {
719 return false;
720 }
721
722 function getRequestURL() {
723 $this->notImplemented( __METHOD__ );
724 }
725
726 function appendQuery( $query ) {
727 $this->notImplemented( __METHOD__ );
728 }
729
730 function getHeader( $name ) {
731 return isset( $this->headers[$name] ) ? $this->headers[$name] : false;
732 }
733
734 function getSessionData( $key ) {
735 if( !isset( $this->session[$key] ) )
736 return null;
737 return $this->session[$key];
738 }
739 function setSessionData( $key, $data ) {
740 $this->notImplemented( __METHOD__ );
741 }
742
743 }