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