Revert r43804 'This should probably be in Response, not Request, as we're setting...
[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 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 return $default;
235 }
236 }
237
238 /**
239 * Fetch a scalar from the input or return $default if it's not set.
240 * Returns a string. Arrays are discarded. Useful for
241 * non-freeform text inputs (e.g. predefined internal text keys
242 * selected by a drop-down menu). For freeform input, see getText().
243 *
244 * @param $name string
245 * @param $default string: optional default (or NULL)
246 * @return string
247 */
248 function getVal( $name, $default = NULL ) {
249 $val = $this->getGPCVal( $this->data, $name, $default );
250 if( is_array( $val ) ) {
251 $val = $default;
252 }
253 if( is_null( $val ) ) {
254 return null;
255 } else {
256 return (string)$val;
257 }
258 }
259
260 /**
261 * Set an aribtrary value into our get/post data.
262 * @param $key string Key name to use
263 * @param $value mixed Value to set
264 * @return mixed old value if one was present, null otherwise
265 */
266 function setVal( $key, $value ) {
267 $ret = isset( $this->data[$key] ) ? $this->data[$key] : null;
268 $this->data[$key] = $value;
269 return $ret;
270 }
271
272 /**
273 * Fetch an array from the input or return $default if it's not set.
274 * If source was scalar, will return an array with a single element.
275 * If no source and no default, returns NULL.
276 *
277 * @param $name string
278 * @param $default array: optional default (or NULL)
279 * @return array
280 */
281 function getArray( $name, $default = NULL ) {
282 $val = $this->getGPCVal( $this->data, $name, $default );
283 if( is_null( $val ) ) {
284 return null;
285 } else {
286 return (array)$val;
287 }
288 }
289
290 /**
291 * Fetch an array of integers, or return $default if it's not set.
292 * If source was scalar, will return an array with a single element.
293 * If no source and no default, returns NULL.
294 * If an array is returned, contents are guaranteed to be integers.
295 *
296 * @param $name string
297 * @param $default array: option default (or NULL)
298 * @return array of ints
299 */
300 function getIntArray( $name, $default = NULL ) {
301 $val = $this->getArray( $name, $default );
302 if( is_array( $val ) ) {
303 $val = array_map( 'intval', $val );
304 }
305 return $val;
306 }
307
308 /**
309 * Fetch an integer value from the input or return $default if not set.
310 * Guaranteed to return an integer; non-numeric input will typically
311 * return 0.
312 * @param $name string
313 * @param $default int
314 * @return int
315 */
316 function getInt( $name, $default = 0 ) {
317 return intval( $this->getVal( $name, $default ) );
318 }
319
320 /**
321 * Fetch an integer value from the input or return null if empty.
322 * Guaranteed to return an integer or null; non-numeric input will
323 * typically return null.
324 * @param $name string
325 * @return int
326 */
327 function getIntOrNull( $name ) {
328 $val = $this->getVal( $name );
329 return is_numeric( $val )
330 ? intval( $val )
331 : null;
332 }
333
334 /**
335 * Fetch a boolean value from the input or return $default if not set.
336 * Guaranteed to return true or false, with normal PHP semantics for
337 * boolean interpretation of strings.
338 * @param $name string
339 * @param $default bool
340 * @return bool
341 */
342 function getBool( $name, $default = false ) {
343 return $this->getVal( $name, $default ) ? true : false;
344 }
345
346 /**
347 * Return true if the named value is set in the input, whatever that
348 * value is (even "0"). Return false if the named value is not set.
349 * Example use is checking for the presence of check boxes in forms.
350 * @param $name string
351 * @return bool
352 */
353 function getCheck( $name ) {
354 # Checkboxes and buttons are only present when clicked
355 # Presence connotes truth, abscense false
356 $val = $this->getVal( $name, NULL );
357 return isset( $val );
358 }
359
360 /**
361 * Fetch a text string from the given array or return $default if it's not
362 * set. \r is stripped from the text, and with some language modules there
363 * is an input transliteration applied. This should generally be used for
364 * form <textarea> and <input> fields. Used for user-supplied freeform text
365 * input (for which input transformations may be required - e.g. Esperanto
366 * x-coding).
367 *
368 * @param $name string
369 * @param $default string: optional
370 * @return string
371 */
372 function getText( $name, $default = '' ) {
373 global $wgContLang;
374 $val = $this->getVal( $name, $default );
375 return str_replace( "\r\n", "\n",
376 $wgContLang->recodeInput( $val ) );
377 }
378
379 /**
380 * Extracts the given named values into an array.
381 * If no arguments are given, returns all input values.
382 * No transformation is performed on the values.
383 */
384 function getValues() {
385 $names = func_get_args();
386 if ( count( $names ) == 0 ) {
387 $names = array_keys( $this->data );
388 }
389
390 $retVal = array();
391 foreach ( $names as $name ) {
392 $value = $this->getVal( $name );
393 if ( !is_null( $value ) ) {
394 $retVal[$name] = $value;
395 }
396 }
397 return $retVal;
398 }
399
400 /**
401 * Returns true if the present request was reached by a POST operation,
402 * false otherwise (GET, HEAD, or command-line).
403 *
404 * Note that values retrieved by the object may come from the
405 * GET URL etc even on a POST request.
406 *
407 * @return bool
408 */
409 function wasPosted() {
410 return $_SERVER['REQUEST_METHOD'] == 'POST';
411 }
412
413 /**
414 * Returns true if there is a session cookie set.
415 * This does not necessarily mean that the user is logged in!
416 *
417 * If you want to check for an open session, use session_id()
418 * instead; that will also tell you if the session was opened
419 * during the current request (in which case the cookie will
420 * be sent back to the client at the end of the script run).
421 *
422 * @return bool
423 */
424 function checkSessionCookie() {
425 return isset( $_COOKIE[session_name()] );
426 }
427
428 /**
429 * Return the path portion of the request URI.
430 * @return string
431 */
432 function getRequestURL() {
433 if( isset( $_SERVER['REQUEST_URI'] ) ) {
434 $base = $_SERVER['REQUEST_URI'];
435 } elseif( isset( $_SERVER['SCRIPT_NAME'] ) ) {
436 // Probably IIS; doesn't set REQUEST_URI
437 $base = $_SERVER['SCRIPT_NAME'];
438 if( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
439 $base .= '?' . $_SERVER['QUERY_STRING'];
440 }
441 } else {
442 // This shouldn't happen!
443 throw new MWException( "Web server doesn't provide either " .
444 "REQUEST_URI or SCRIPT_NAME. Report details of your " .
445 "web server configuration to http://bugzilla.wikimedia.org/" );
446 }
447 // User-agents should not send a fragment with the URI, but
448 // if they do, and the web server passes it on to us, we
449 // need to strip it or we get false-positive redirect loops
450 // or weird output URLs
451 $hash = strpos( $base, '#' );
452 if( $hash !== false ) {
453 $base = substr( $base, 0, $hash );
454 }
455 if( $base{0} == '/' ) {
456 return $base;
457 } else {
458 // We may get paths with a host prepended; strip it.
459 return preg_replace( '!^[^:]+://[^/]+/!', '/', $base );
460 }
461 }
462
463 /**
464 * Return the request URI with the canonical service and hostname.
465 * @return string
466 */
467 function getFullRequestURL() {
468 global $wgServer;
469 return $wgServer . $this->getRequestURL();
470 }
471
472 /**
473 * Take an arbitrary query and rewrite the present URL to include it
474 * @param $query String: query string fragment; do not include initial '?'
475 * @return string
476 */
477 function appendQuery( $query ) {
478 global $wgTitle;
479 $basequery = '';
480 foreach( $_GET as $var => $val ) {
481 if ( $var == 'title' )
482 continue;
483 if ( is_array( $val ) )
484 /* This will happen given a request like
485 * http://en.wikipedia.org/w/index.php?title[]=Special:Userlogin&returnto[]=Main_Page
486 */
487 continue;
488 $basequery .= '&' . urlencode( $var ) . '=' . urlencode( $val );
489 }
490 $basequery .= '&' . $query;
491
492 # Trim the extra &
493 $basequery = substr( $basequery, 1 );
494 return $wgTitle->getLocalURL( $basequery );
495 }
496
497 /**
498 * HTML-safe version of appendQuery().
499 * @param $query String: query string fragment; do not include initial '?'
500 * @return string
501 */
502 function escapeAppendQuery( $query ) {
503 return htmlspecialchars( $this->appendQuery( $query ) );
504 }
505
506 function appendQueryValue( $key, $value, $onlyquery = false ) {
507 return $this->appendQueryArray( array( $key => $value ), $onlyquery );
508 }
509
510 /**
511 * Appends or replaces value of query variables.
512 * @param $array Array of values to replace/add to query
513 * @param $onlyquery Bool: whether to only return the query string and not
514 * the complete URL
515 * @return string
516 */
517 function appendQueryArray( $array, $onlyquery = false ) {
518 global $wgTitle;
519 $newquery = $_GET;
520 unset( $newquery['title'] );
521 $newquery = array_merge( $newquery, $array );
522 $query = wfArrayToCGI( $newquery );
523 return $onlyquery ? $query : $wgTitle->getLocalURL( $query );
524 }
525
526 /**
527 * Check for limit and offset parameters on the input, and return sensible
528 * defaults if not given. The limit must be positive and is capped at 5000.
529 * Offset must be positive but is not capped.
530 *
531 * @param $deflimit Integer: limit to use if no input and the user hasn't set the option.
532 * @param $optionname String: to specify an option other than rclimit to pull from.
533 * @return array first element is limit, second is offset
534 */
535 function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
536 global $wgUser;
537
538 $limit = $this->getInt( 'limit', 0 );
539 if( $limit < 0 ) $limit = 0;
540 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
541 $limit = (int)$wgUser->getOption( $optionname );
542 }
543 if( $limit <= 0 ) $limit = $deflimit;
544 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
545
546 $offset = $this->getInt( 'offset', 0 );
547 if( $offset < 0 ) $offset = 0;
548
549 return array( $limit, $offset );
550 }
551
552 /**
553 * Return the path to the temporary file where PHP has stored the upload.
554 * @param $key String:
555 * @return string or NULL if no such file.
556 */
557 function getFileTempname( $key ) {
558 if( !isset( $_FILES[$key] ) ) {
559 return NULL;
560 }
561 return $_FILES[$key]['tmp_name'];
562 }
563
564 /**
565 * Return the size of the upload, or 0.
566 * @param $key String:
567 * @return integer
568 */
569 function getFileSize( $key ) {
570 if( !isset( $_FILES[$key] ) ) {
571 return 0;
572 }
573 return $_FILES[$key]['size'];
574 }
575
576 /**
577 * Return the upload error or 0
578 * @param $key String:
579 * @return integer
580 */
581 function getUploadError( $key ) {
582 if( !isset( $_FILES[$key] ) || !isset( $_FILES[$key]['error'] ) ) {
583 return 0/*UPLOAD_ERR_OK*/;
584 }
585 return $_FILES[$key]['error'];
586 }
587
588 /**
589 * Return the original filename of the uploaded file, as reported by
590 * the submitting user agent. HTML-style character entities are
591 * interpreted and normalized to Unicode normalization form C, in part
592 * to deal with weird input from Safari with non-ASCII filenames.
593 *
594 * Other than this the name is not verified for being a safe filename.
595 *
596 * @param $key String:
597 * @return string or NULL if no such file.
598 */
599 function getFileName( $key ) {
600 if( !isset( $_FILES[$key] ) ) {
601 return NULL;
602 }
603 $name = $_FILES[$key]['name'];
604
605 # Safari sends filenames in HTML-encoded Unicode form D...
606 # Horrid and evil! Let's try to make some kind of sense of it.
607 $name = Sanitizer::decodeCharReferences( $name );
608 $name = UtfNormal::cleanUp( $name );
609 wfDebug( "WebRequest::getFileName() '" . $_FILES[$key]['name'] . "' normalized to '$name'\n" );
610 return $name;
611 }
612
613 /**
614 * Return a handle to WebResponse style object, for setting cookies,
615 * headers and other stuff, for Request being worked on.
616 */
617 function response() {
618 /* Lazy initialization of response object for this request */
619 if (!is_object($this->_response)) {
620 $this->_response = new WebResponse;
621 }
622 return $this->_response;
623 }
624
625 /**
626 * Get a request header, or false if it isn't set
627 * @param $name String: case-insensitive header name
628 */
629 function getHeader( $name ) {
630 $name = strtoupper( $name );
631 if ( function_exists( 'apache_request_headers' ) ) {
632 if ( !isset( $this->headers ) ) {
633 $this->headers = array();
634 foreach ( apache_request_headers() as $tempName => $tempValue ) {
635 $this->headers[ strtoupper( $tempName ) ] = $tempValue;
636 }
637 }
638 if ( isset( $this->headers[$name] ) ) {
639 return $this->headers[$name];
640 } else {
641 return false;
642 }
643 } else {
644 $name = 'HTTP_' . str_replace( '-', '_', $name );
645 if ( isset( $_SERVER[$name] ) ) {
646 return $_SERVER[$name];
647 } else {
648 return false;
649 }
650 }
651 }
652
653 /*
654 * Get data from $_SESSION
655 */
656 function getSessionData( $key ) {
657 if( !isset( $_SESSION[$key] ) )
658 return null;
659 return $_SESSION[$key];
660 }
661 function setSessionData( $key, $data ) {
662 $_SESSION[$key] = $data;
663 }
664 }
665
666 /**
667 * WebRequest clone which takes values from a provided array.
668 *
669 * @ingroup HTTP
670 */
671 class FauxRequest extends WebRequest {
672 var $wasPosted = false;
673
674 /**
675 * @param $data Array of *non*-urlencoded key => value pairs, the
676 * fake GET/POST values
677 * @param $wasPosted Bool: whether to treat the data as POST
678 */
679 function FauxRequest( $data, $wasPosted = false, $session = null ) {
680 if( is_array( $data ) ) {
681 $this->data = $data;
682 } else {
683 throw new MWException( "FauxRequest() got bogus data" );
684 }
685 $this->wasPosted = $wasPosted;
686 $this->headers = array();
687 $this->session = $session ? $session : array();
688 }
689
690 function notImplemented( $method ) {
691 throw new MWException( "{$method}() not implemented" );
692 }
693
694 function getText( $name, $default = '' ) {
695 # Override; don't recode since we're using internal data
696 return (string)$this->getVal( $name, $default );
697 }
698
699 function getValues() {
700 return $this->data;
701 }
702
703 function wasPosted() {
704 return $this->wasPosted;
705 }
706
707 function checkSessionCookie() {
708 return false;
709 }
710
711 function getRequestURL() {
712 $this->notImplemented( __METHOD__ );
713 }
714
715 function appendQuery( $query ) {
716 $this->notImplemented( __METHOD__ );
717 }
718
719 function getHeader( $name ) {
720 return isset( $this->headers[$name] ) ? $this->headers[$name] : false;
721 }
722
723 function getSessionData( $key ) {
724 if( !isset( $this->session[$key] ) )
725 return null;
726 return $this->session[$key];
727 }
728 function setSessionData( $key, $data ) {
729 $this->notImplemented( __METHOD__ );
730 }
731
732 }