Fix regression in even sizing of diff columns; forgot to restore a couple bits I...
[mediawiki.git] / includes / WebRequest.php
blob1a59766e7bf267d4fdcd6a34452770ee88ebe403
1 <?php
2 /**
3 * Deal with importing all those nasssty globals and things
4 */
6 # Copyright (C) 2003 Brion Vibber <brion@pobox.com>
7 # http://www.mediawiki.org/
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.
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.
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
25 /**
26 * Some entry points may use this file without first enabling the
27 * autoloader.
29 if ( !function_exists( '__autoload' ) ) {
30 require_once( dirname(__FILE__) . '/normal/UtfNormal.php' );
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.
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.
44 class WebRequest {
45 function __construct() {
46 $this->checkMagicQuotes();
47 global $wgUsePathInfo;
48 if ( $wgUsePathInfo ) {
49 // PATH_INFO is mangled due to http://bugs.php.net/bug.php?id=31892
50 // And also by Apache 2.x, double slashes are converted to single slashes.
51 // So we will use REQUEST_URI if possible.
52 $title = '';
53 if ( !empty( $_SERVER['REQUEST_URI'] ) ) {
54 global $wgArticlePath, $wgActionPaths;
55 $paths["view"] = $wgArticlePath;
56 $paths = array_merge( $paths, $wgActionPaths );
57 $title = $this->extractActionPaths( $paths );
58 } elseif ( isset( $_SERVER['ORIG_PATH_INFO'] ) && $_SERVER['ORIG_PATH_INFO'] != '' ) {
59 # Mangled PATH_INFO
60 # http://bugs.php.net/bug.php?id=31892
61 # Also reported when ini_get('cgi.fix_pathinfo')==false
62 $title = substr( $_SERVER['ORIG_PATH_INFO'], 1 );
63 } elseif ( isset( $_SERVER['PATH_INFO'] ) && ($_SERVER['PATH_INFO'] != '') && $wgUsePathInfo ) {
64 $title = substr( $_SERVER['PATH_INFO'], 1 );
66 if ( strval( $title ) != '' ) {
67 $_GET['title'] = $_REQUEST['title'] = $title;
72 private function extractActionPaths( $paths ) {
73 $url = $_SERVER['REQUEST_URI'];
74 if ( !preg_match( '!^https?://!', $url ) ) {
75 $url = 'http://unused' . $url;
77 $a = parse_url( $url );
78 foreach( $paths as $action => $path ) {
79 // Find the part after $wgArticlePath
80 $base = str_replace( '$1', '', $path );
81 if ( $a && substr( $a['path'], 0, strlen( $base ) ) == $base ) {
82 return urldecode( substr( $a['path'], strlen( $base ) ) );
87 private $_response;
89 /**
90 * Recursively strips slashes from the given array;
91 * used for undoing the evil that is magic_quotes_gpc.
92 * @param array &$arr will be modified
93 * @return array the original array
94 * @private
96 function &fix_magic_quotes( &$arr ) {
97 foreach( $arr as $key => $val ) {
98 if( is_array( $val ) ) {
99 $this->fix_magic_quotes( $arr[$key] );
100 } else {
101 $arr[$key] = stripslashes( $val );
104 return $arr;
108 * If magic_quotes_gpc option is on, run the global arrays
109 * through fix_magic_quotes to strip out the stupid slashes.
110 * WARNING: This should only be done once! Running a second
111 * time could damage the values.
112 * @private
114 function checkMagicQuotes() {
115 if ( get_magic_quotes_gpc() ) {
116 $this->fix_magic_quotes( $_COOKIE );
117 $this->fix_magic_quotes( $_ENV );
118 $this->fix_magic_quotes( $_GET );
119 $this->fix_magic_quotes( $_POST );
120 $this->fix_magic_quotes( $_REQUEST );
121 $this->fix_magic_quotes( $_SERVER );
126 * Recursively normalizes UTF-8 strings in the given array.
127 * @param array $data string or array
128 * @return cleaned-up version of the given
129 * @private
131 function normalizeUnicode( $data ) {
132 if( is_array( $data ) ) {
133 foreach( $data as $key => $val ) {
134 $data[$key] = $this->normalizeUnicode( $val );
136 } else {
137 $data = UtfNormal::cleanUp( $data );
139 return $data;
143 * Fetch a value from the given array or return $default if it's not set.
145 * @param array $arr
146 * @param string $name
147 * @param mixed $default
148 * @return mixed
149 * @private
151 function getGPCVal( $arr, $name, $default ) {
152 if( isset( $arr[$name] ) ) {
153 global $wgContLang;
154 $data = $arr[$name];
155 if( isset( $_GET[$name] ) && !is_array( $data ) ) {
156 # Check for alternate/legacy character encoding.
157 if( isset( $wgContLang ) ) {
158 $data = $wgContLang->checkTitleEncoding( $data );
161 $data = $this->normalizeUnicode( $data );
162 return $data;
163 } else {
164 return $default;
169 * Fetch a scalar from the input or return $default if it's not set.
170 * Returns a string. Arrays are discarded. Useful for
171 * non-freeform text inputs (e.g. predefined internal text keys
172 * selected by a drop-down menu). For freeform input, see getText().
174 * @param string $name
175 * @param string $default optional default (or NULL)
176 * @return string
178 function getVal( $name, $default = NULL ) {
179 $val = $this->getGPCVal( $_REQUEST, $name, $default );
180 if( is_array( $val ) ) {
181 $val = $default;
183 if( is_null( $val ) ) {
184 return null;
185 } else {
186 return (string)$val;
191 * Fetch an array from the input or return $default if it's not set.
192 * If source was scalar, will return an array with a single element.
193 * If no source and no default, returns NULL.
195 * @param string $name
196 * @param array $default optional default (or NULL)
197 * @return array
199 function getArray( $name, $default = NULL ) {
200 $val = $this->getGPCVal( $_REQUEST, $name, $default );
201 if( is_null( $val ) ) {
202 return null;
203 } else {
204 return (array)$val;
209 * Fetch an array of integers, or return $default if it's not set.
210 * If source was scalar, will return an array with a single element.
211 * If no source and no default, returns NULL.
212 * If an array is returned, contents are guaranteed to be integers.
214 * @param string $name
215 * @param array $default option default (or NULL)
216 * @return array of ints
218 function getIntArray( $name, $default = NULL ) {
219 $val = $this->getArray( $name, $default );
220 if( is_array( $val ) ) {
221 $val = array_map( 'intval', $val );
223 return $val;
227 * Fetch an integer value from the input or return $default if not set.
228 * Guaranteed to return an integer; non-numeric input will typically
229 * return 0.
230 * @param string $name
231 * @param int $default
232 * @return int
234 function getInt( $name, $default = 0 ) {
235 return intval( $this->getVal( $name, $default ) );
239 * Fetch an integer value from the input or return null if empty.
240 * Guaranteed to return an integer or null; non-numeric input will
241 * typically return null.
242 * @param string $name
243 * @return int
245 function getIntOrNull( $name ) {
246 $val = $this->getVal( $name );
247 return is_numeric( $val )
248 ? intval( $val )
249 : null;
253 * Fetch a boolean value from the input or return $default if not set.
254 * Guaranteed to return true or false, with normal PHP semantics for
255 * boolean interpretation of strings.
256 * @param string $name
257 * @param bool $default
258 * @return bool
260 function getBool( $name, $default = false ) {
261 return $this->getVal( $name, $default ) ? true : false;
265 * Return true if the named value is set in the input, whatever that
266 * value is (even "0"). Return false if the named value is not set.
267 * Example use is checking for the presence of check boxes in forms.
268 * @param string $name
269 * @return bool
271 function getCheck( $name ) {
272 # Checkboxes and buttons are only present when clicked
273 # Presence connotes truth, abscense false
274 $val = $this->getVal( $name, NULL );
275 return isset( $val );
279 * Fetch a text string from the given array or return $default if it's not
280 * set. \r is stripped from the text, and with some language modules there
281 * is an input transliteration applied. This should generally be used for
282 * form <textarea> and <input> fields. Used for user-supplied freeform text
283 * input (for which input transformations may be required - e.g. Esperanto
284 * x-coding).
286 * @param string $name
287 * @param string $default optional
288 * @return string
290 function getText( $name, $default = '' ) {
291 global $wgContLang;
292 $val = $this->getVal( $name, $default );
293 return str_replace( "\r\n", "\n",
294 $wgContLang->recodeInput( $val ) );
298 * Extracts the given named values into an array.
299 * If no arguments are given, returns all input values.
300 * No transformation is performed on the values.
302 function getValues() {
303 $names = func_get_args();
304 if ( count( $names ) == 0 ) {
305 $names = array_keys( $_REQUEST );
308 $retVal = array();
309 foreach ( $names as $name ) {
310 $value = $this->getVal( $name );
311 if ( !is_null( $value ) ) {
312 $retVal[$name] = $value;
315 return $retVal;
319 * Returns true if the present request was reached by a POST operation,
320 * false otherwise (GET, HEAD, or command-line).
322 * Note that values retrieved by the object may come from the
323 * GET URL etc even on a POST request.
325 * @return bool
327 function wasPosted() {
328 return $_SERVER['REQUEST_METHOD'] == 'POST';
332 * Returns true if there is a session cookie set.
333 * This does not necessarily mean that the user is logged in!
335 * If you want to check for an open session, use session_id()
336 * instead; that will also tell you if the session was opened
337 * during the current request (in which case the cookie will
338 * be sent back to the client at the end of the script run).
340 * @return bool
342 function checkSessionCookie() {
343 return isset( $_COOKIE[session_name()] );
347 * Return the path portion of the request URI.
348 * @return string
350 function getRequestURL() {
351 if( isset( $_SERVER['REQUEST_URI'] ) ) {
352 $base = $_SERVER['REQUEST_URI'];
353 } elseif( isset( $_SERVER['SCRIPT_NAME'] ) ) {
354 // Probably IIS; doesn't set REQUEST_URI
355 $base = $_SERVER['SCRIPT_NAME'];
356 if( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
357 $base .= '?' . $_SERVER['QUERY_STRING'];
359 } else {
360 // This shouldn't happen!
361 throw new MWException( "Web server doesn't provide either " .
362 "REQUEST_URI or SCRIPT_NAME. Report details of your " .
363 "web server configuration to http://bugzilla.wikimedia.org/" );
365 // User-agents should not send a fragment with the URI, but
366 // if they do, and the web server passes it on to us, we
367 // need to strip it or we get false-positive redirect loops
368 // or weird output URLs
369 $hash = strpos( $base, '#' );
370 if( $hash !== false ) {
371 $base = substr( $base, 0, $hash );
373 if( $base{0} == '/' ) {
374 return $base;
375 } else {
376 // We may get paths with a host prepended; strip it.
377 return preg_replace( '!^[^:]+://[^/]+/!', '/', $base );
382 * Return the request URI with the canonical service and hostname.
383 * @return string
385 function getFullRequestURL() {
386 global $wgServer;
387 return $wgServer . $this->getRequestURL();
391 * Take an arbitrary query and rewrite the present URL to include it
392 * @param $query String: query string fragment; do not include initial '?'
393 * @return string
395 function appendQuery( $query ) {
396 global $wgTitle;
397 $basequery = '';
398 foreach( $_GET as $var => $val ) {
399 if ( $var == 'title' )
400 continue;
401 if ( is_array( $val ) )
402 /* This will happen given a request like
403 * http://en.wikipedia.org/w/index.php?title[]=Special:Userlogin&returnto[]=Main_Page
405 continue;
406 $basequery .= '&' . urlencode( $var ) . '=' . urlencode( $val );
408 $basequery .= '&' . $query;
410 # Trim the extra &
411 $basequery = substr( $basequery, 1 );
412 return $wgTitle->getLocalURL( $basequery );
416 * HTML-safe version of appendQuery().
417 * @param $query String: query string fragment; do not include initial '?'
418 * @return string
420 function escapeAppendQuery( $query ) {
421 return htmlspecialchars( $this->appendQuery( $query ) );
425 * Check for limit and offset parameters on the input, and return sensible
426 * defaults if not given. The limit must be positive and is capped at 5000.
427 * Offset must be positive but is not capped.
429 * @param $deflimit Integer: limit to use if no input and the user hasn't set the option.
430 * @param $optionname String: to specify an option other than rclimit to pull from.
431 * @return array first element is limit, second is offset
433 function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
434 global $wgUser;
436 $limit = $this->getInt( 'limit', 0 );
437 if( $limit < 0 ) $limit = 0;
438 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
439 $limit = (int)$wgUser->getOption( $optionname );
441 if( $limit <= 0 ) $limit = $deflimit;
442 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
444 $offset = $this->getInt( 'offset', 0 );
445 if( $offset < 0 ) $offset = 0;
447 return array( $limit, $offset );
451 * Return the path to the temporary file where PHP has stored the upload.
452 * @param $key String:
453 * @return string or NULL if no such file.
455 function getFileTempname( $key ) {
456 if( !isset( $_FILES[$key] ) ) {
457 return NULL;
459 return $_FILES[$key]['tmp_name'];
463 * Return the size of the upload, or 0.
464 * @param $key String:
465 * @return integer
467 function getFileSize( $key ) {
468 if( !isset( $_FILES[$key] ) ) {
469 return 0;
471 return $_FILES[$key]['size'];
475 * Return the upload error or 0
476 * @param $key String:
477 * @return integer
479 function getUploadError( $key ) {
480 if( !isset( $_FILES[$key] ) || !isset( $_FILES[$key]['error'] ) ) {
481 return 0/*UPLOAD_ERR_OK*/;
483 return $_FILES[$key]['error'];
487 * Return the original filename of the uploaded file, as reported by
488 * the submitting user agent. HTML-style character entities are
489 * interpreted and normalized to Unicode normalization form C, in part
490 * to deal with weird input from Safari with non-ASCII filenames.
492 * Other than this the name is not verified for being a safe filename.
494 * @param $key String:
495 * @return string or NULL if no such file.
497 function getFileName( $key ) {
498 if( !isset( $_FILES[$key] ) ) {
499 return NULL;
501 $name = $_FILES[$key]['name'];
503 # Safari sends filenames in HTML-encoded Unicode form D...
504 # Horrid and evil! Let's try to make some kind of sense of it.
505 $name = Sanitizer::decodeCharReferences( $name );
506 $name = UtfNormal::cleanUp( $name );
507 wfDebug( "WebRequest::getFileName() '" . $_FILES[$key]['name'] . "' normalized to '$name'\n" );
508 return $name;
512 * Return a handle to WebResponse style object, for setting cookies,
513 * headers and other stuff, for Request being worked on.
515 function response() {
516 /* Lazy initialization of response object for this request */
517 if (!is_object($this->_response)) {
518 $this->_response = new WebResponse;
520 return $this->_response;
526 * WebRequest clone which takes values from a provided array.
529 class FauxRequest extends WebRequest {
530 var $data = null;
531 var $wasPosted = false;
533 function FauxRequest( $data, $wasPosted = false ) {
534 if( is_array( $data ) ) {
535 $this->data = $data;
536 } else {
537 throw new MWException( "FauxRequest() got bogus data" );
539 $this->wasPosted = $wasPosted;
542 function getVal( $name, $default = NULL ) {
543 return $this->getGPCVal( $this->data, $name, $default );
546 function getText( $name, $default = '' ) {
547 # Override; don't recode since we're using internal data
548 return $this->getVal( $name, $default );
551 function getValues() {
552 return $this->data;
555 function wasPosted() {
556 return $this->wasPosted;
559 function checkSessionCookie() {
560 return false;
563 function getRequestURL() {
564 throw new MWException( 'FauxRequest::getRequestURL() not implemented' );
567 function appendQuery( $query ) {
568 throw new MWException( 'FauxRequest::appendQuery() not implemented' );