* (bug 12988) $wgMinimalPasswordLength no longer breaks create user by email
[mediawiki.git] / includes / WebRequest.php
blobfd8acc533c2f809420c02de01eaf05f03738ca10
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 var $data = array();
46 var $headers;
47 private $_response;
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();
55 // POST overrides GET data
56 // We don't use $_REQUEST here to avoid interference from cookies...
57 $this->data = array_merge( $_GET, $_POST );
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.
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;
80 $a = parse_url( $url );
81 if( $a ) {
82 $path = $a['path'];
84 global $wgScript;
85 if( $path == $wgScript ) {
86 // Script inside a rewrite path?
87 // Abort to keep from breaking...
88 return;
90 // Raw PATH_INFO style
91 $matches = $this->extractTitle( $path, "$wgScript/$1" );
93 global $wgArticlePath;
94 if( !$matches && $wgArticlePath ) {
95 $matches = $this->extractTitle( $path, $wgArticlePath );
98 global $wgActionPaths;
99 if( !$matches && $wgActionPaths ) {
100 $matches = $this->extractTitle( $path, $wgActionPaths, 'action' );
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 );
110 $matches = $this->extractTitle( $path, $variantPaths, 'variant' );
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 );
119 } elseif ( isset( $_SERVER['PATH_INFO'] ) && ($_SERVER['PATH_INFO'] != '') ) {
120 // Regular old PATH_INFO yay
121 $matches['title'] = substr( $_SERVER['PATH_INFO'], 1 );
123 foreach( $matches as $key => $val) {
124 $this->data[$key] = $_GET[$key] = $_REQUEST[$key] = $val;
130 * Internal URL rewriting function; tries to extract page title and,
131 * optionally, one other fixed parameter value from a URL path.
133 * @param string $path the URL path given from the client
134 * @param array $bases one or more URLs, optionally with $1 at the end
135 * @param string $key 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
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;
151 return $matches;
155 return array();
159 * Recursively strips slashes from the given array;
160 * used for undoing the evil that is magic_quotes_gpc.
161 * @param array &$arr will be modified
162 * @return array the original array
163 * @private
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 );
173 return $arr;
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
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 );
195 * Recursively normalizes UTF-8 strings in the given array.
196 * @param array $data string or array
197 * @return cleaned-up version of the given
198 * @private
200 function normalizeUnicode( $data ) {
201 if( is_array( $data ) ) {
202 foreach( $data as $key => $val ) {
203 $data[$key] = $this->normalizeUnicode( $val );
205 } else {
206 $data = UtfNormal::cleanUp( $data );
208 return $data;
212 * Fetch a value from the given array or return $default if it's not set.
214 * @param array $arr
215 * @param string $name
216 * @param mixed $default
217 * @return mixed
218 * @private
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 );
230 $data = $this->normalizeUnicode( $data );
231 return $data;
232 } else {
233 return $default;
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().
243 * @param string $name
244 * @param string $default optional default (or NULL)
245 * @return string
247 function getVal( $name, $default = NULL ) {
248 $val = $this->getGPCVal( $this->data, $name, $default );
249 if( is_array( $val ) ) {
250 $val = $default;
252 if( is_null( $val ) ) {
253 return null;
254 } else {
255 return (string)$val;
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.
264 * @param string $name
265 * @param array $default optional default (or NULL)
266 * @return array
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;
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.
283 * @param string $name
284 * @param array $default option default (or NULL)
285 * @return array of ints
287 function getIntArray( $name, $default = NULL ) {
288 $val = $this->getArray( $name, $default );
289 if( is_array( $val ) ) {
290 $val = array_map( 'intval', $val );
292 return $val;
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 string $name
300 * @param int $default
301 * @return int
303 function getInt( $name, $default = 0 ) {
304 return intval( $this->getVal( $name, $default ) );
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 string $name
312 * @return int
314 function getIntOrNull( $name ) {
315 $val = $this->getVal( $name );
316 return is_numeric( $val )
317 ? intval( $val )
318 : null;
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 string $name
326 * @param bool $default
327 * @return bool
329 function getBool( $name, $default = false ) {
330 return $this->getVal( $name, $default ) ? true : false;
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 string $name
338 * @return bool
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 );
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).
355 * @param string $name
356 * @param string $default optional
357 * @return string
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 ) );
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.
371 function getValues() {
372 $names = func_get_args();
373 if ( count( $names ) == 0 ) {
374 $names = array_keys( $this->data );
377 $retVal = array();
378 foreach ( $names as $name ) {
379 $value = $this->getVal( $name );
380 if ( !is_null( $value ) ) {
381 $retVal[$name] = $value;
384 return $retVal;
388 * Returns true if the present request was reached by a POST operation,
389 * false otherwise (GET, HEAD, or command-line).
391 * Note that values retrieved by the object may come from the
392 * GET URL etc even on a POST request.
394 * @return bool
396 function wasPosted() {
397 return $_SERVER['REQUEST_METHOD'] == 'POST';
401 * Returns true if there is a session cookie set.
402 * This does not necessarily mean that the user is logged in!
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).
409 * @return bool
411 function checkSessionCookie() {
412 return isset( $_COOKIE[session_name()] );
416 * Return the path portion of the request URI.
417 * @return string
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'];
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/" );
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 );
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 );
451 * Return the request URI with the canonical service and hostname.
452 * @return string
454 function getFullRequestURL() {
455 global $wgServer;
456 return $wgServer . $this->getRequestURL();
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
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
474 continue;
475 $basequery .= '&' . urlencode( $var ) . '=' . urlencode( $val );
477 $basequery .= '&' . $query;
479 # Trim the extra &
480 $basequery = substr( $basequery, 1 );
481 return $wgTitle->getLocalURL( $basequery );
485 * HTML-safe version of appendQuery().
486 * @param $query String: query string fragment; do not include initial '?'
487 * @return string
489 function escapeAppendQuery( $query ) {
490 return htmlspecialchars( $this->appendQuery( $query ) );
494 * Check for limit and offset parameters on the input, and return sensible
495 * defaults if not given. The limit must be positive and is capped at 5000.
496 * Offset must be positive but is not capped.
498 * @param $deflimit Integer: limit to use if no input and the user hasn't set the option.
499 * @param $optionname String: to specify an option other than rclimit to pull from.
500 * @return array first element is limit, second is offset
502 function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
503 global $wgUser;
505 $limit = $this->getInt( 'limit', 0 );
506 if( $limit < 0 ) $limit = 0;
507 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
508 $limit = (int)$wgUser->getOption( $optionname );
510 if( $limit <= 0 ) $limit = $deflimit;
511 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
513 $offset = $this->getInt( 'offset', 0 );
514 if( $offset < 0 ) $offset = 0;
516 return array( $limit, $offset );
520 * Return the path to the temporary file where PHP has stored the upload.
521 * @param $key String:
522 * @return string or NULL if no such file.
524 function getFileTempname( $key ) {
525 if( !isset( $_FILES[$key] ) ) {
526 return NULL;
528 return $_FILES[$key]['tmp_name'];
532 * Return the size of the upload, or 0.
533 * @param $key String:
534 * @return integer
536 function getFileSize( $key ) {
537 if( !isset( $_FILES[$key] ) ) {
538 return 0;
540 return $_FILES[$key]['size'];
544 * Return the upload error or 0
545 * @param $key String:
546 * @return integer
548 function getUploadError( $key ) {
549 if( !isset( $_FILES[$key] ) || !isset( $_FILES[$key]['error'] ) ) {
550 return 0/*UPLOAD_ERR_OK*/;
552 return $_FILES[$key]['error'];
556 * Return the original filename of the uploaded file, as reported by
557 * the submitting user agent. HTML-style character entities are
558 * interpreted and normalized to Unicode normalization form C, in part
559 * to deal with weird input from Safari with non-ASCII filenames.
561 * Other than this the name is not verified for being a safe filename.
563 * @param $key String:
564 * @return string or NULL if no such file.
566 function getFileName( $key ) {
567 if( !isset( $_FILES[$key] ) ) {
568 return NULL;
570 $name = $_FILES[$key]['name'];
572 # Safari sends filenames in HTML-encoded Unicode form D...
573 # Horrid and evil! Let's try to make some kind of sense of it.
574 $name = Sanitizer::decodeCharReferences( $name );
575 $name = UtfNormal::cleanUp( $name );
576 wfDebug( "WebRequest::getFileName() '" . $_FILES[$key]['name'] . "' normalized to '$name'\n" );
577 return $name;
581 * Return a handle to WebResponse style object, for setting cookies,
582 * headers and other stuff, for Request being worked on.
584 function response() {
585 /* Lazy initialization of response object for this request */
586 if (!is_object($this->_response)) {
587 $this->_response = new WebResponse;
589 return $this->_response;
593 * Get a request header, or false if it isn't set
594 * @param string $name Case-insensitive header name
596 function getHeader( $name ) {
597 $name = strtoupper( $name );
598 if ( function_exists( 'apache_request_headers' ) ) {
599 if ( !isset( $this->headers ) ) {
600 $this->headers = array();
601 foreach ( apache_request_headers() as $tempName => $tempValue ) {
602 $this->headers[ strtoupper( $tempName ) ] = $tempValue;
605 if ( isset( $this->headers[$name] ) ) {
606 return $this->headers[$name];
607 } else {
608 return false;
610 } else {
611 $name = 'HTTP_' . str_replace( '-', '_', $name );
612 if ( isset( $_SERVER[$name] ) ) {
613 return $_SERVER[$name];
614 } else {
615 return false;
622 * WebRequest clone which takes values from a provided array.
625 class FauxRequest extends WebRequest {
626 var $wasPosted = false;
629 * @param array $data Array of *non*-urlencoded key => value pairs, the
630 * fake GET/POST values
631 * @param bool $wasPosted Whether to treat the data as POST
633 function FauxRequest( $data, $wasPosted = false ) {
634 if( is_array( $data ) ) {
635 $this->data = $data;
636 } else {
637 throw new MWException( "FauxRequest() got bogus data" );
639 $this->wasPosted = $wasPosted;
640 $this->headers = array();
643 function getText( $name, $default = '' ) {
644 # Override; don't recode since we're using internal data
645 return (string)$this->getVal( $name, $default );
648 function getValues() {
649 return $this->data;
652 function wasPosted() {
653 return $this->wasPosted;
656 function checkSessionCookie() {
657 return false;
660 function getRequestURL() {
661 throw new MWException( 'FauxRequest::getRequestURL() not implemented' );
664 function appendQuery( $query ) {
665 throw new MWException( 'FauxRequest::appendQuery() not implemented' );
668 function getHeader( $name ) {
669 return isset( $this->headers[$name] ) ? $this->headers[$name] : false;