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