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