dbf284a925a0fc1adadebf90d72798da8b208fa8
3 * Deal with importing all those nasssty globals and things
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
26 * Some entry points may use this file without first enabling the
29 if ( !function_exists( '__autoload' ) ) {
30 require_once( dirname(__FILE__
) . '/normal/UtfNormal.php' );
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
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();
56 // POST overrides GET data
57 // We don't use $_REQUEST here to avoid interference from cookies...
58 $this->data
= $_POST +
$_GET;
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.
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.
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;
81 $a = parse_url( $url );
83 $path = isset( $a['path'] ) ?
$a['path'] : '';
86 if( $path == $wgScript ) {
87 // Script inside a rewrite path?
88 // Abort to keep from breaking...
91 // Raw PATH_INFO style
92 $matches = $this->extractTitle( $path, "$wgScript/$1" );
94 global $wgArticlePath;
95 if( !$matches && $wgArticlePath ) {
96 $matches = $this->extractTitle( $path, $wgArticlePath );
99 global $wgActionPaths;
100 if( !$matches && $wgActionPaths ) {
101 $matches = $this->extractTitle( $path, $wgActionPaths, 'action' );
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 );
111 $matches = $this->extractTitle( $path, $variantPaths, 'variant' );
114 } elseif ( isset( $_SERVER['ORIG_PATH_INFO'] ) && $_SERVER['ORIG_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 );
120 } elseif ( isset( $_SERVER['PATH_INFO'] ) && ($_SERVER['PATH_INFO'] != '') ) {
121 // Regular old PATH_INFO yay
122 $matches['title'] = substr( $_SERVER['PATH_INFO'], 1 );
124 foreach( $matches as $key => $val) {
125 $this->data
[$key] = $_GET[$key] = $_REQUEST[$key] = $val;
131 * Internal URL rewriting function; tries to extract page title and,
132 * optionally, one other fixed parameter value from a URL path.
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
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 );
148 $matches = array( 'title' => rawurldecode( $raw ) );
150 $matches[$key] = $keyValue;
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
166 function &fix_magic_quotes( &$arr ) {
167 foreach( $arr as $key => $val ) {
168 if( is_array( $val ) ) {
169 $this->fix_magic_quotes( $arr[$key] );
171 $arr[$key] = stripslashes( $val );
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.
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 );
196 * Recursively normalizes UTF-8 strings in the given array.
197 * @param $data string or array
198 * @return cleaned-up version of the given
201 function normalizeUnicode( $data ) {
202 if( is_array( $data ) ) {
203 foreach( $data as $key => $val ) {
204 $data[$key] = $this->normalizeUnicode( $val );
207 $data = UtfNormal
::cleanUp( $data );
213 * Fetch a value from the given array or return $default if it's not set.
216 * @param $name string
217 * @param $default mixed
221 function getGPCVal( $arr, $name, $default ) {
222 # PHP is so nice to not touch input data, except sometimes:
223 # http://us2.php.net/variables.external#language.variables.external.dot-in-names
224 # Work around PHP *feature* to avoid *bugs* elsewhere.
225 $name = strtr( $name, '.', '_' );
226 if( isset( $arr[$name] ) ) {
229 if( isset( $_GET[$name] ) && !is_array( $data ) ) {
230 # Check for alternate/legacy character encoding.
231 if( isset( $wgContLang ) ) {
232 $data = $wgContLang->checkTitleEncoding( $data );
235 $data = $this->normalizeUnicode( $data );
244 * Fetch a scalar from the input or return $default if it's not set.
245 * Returns a string. Arrays are discarded. Useful for
246 * non-freeform text inputs (e.g. predefined internal text keys
247 * selected by a drop-down menu). For freeform input, see getText().
249 * @param $name string
250 * @param $default string: optional default (or NULL)
253 function getVal( $name, $default = NULL ) {
254 $val = $this->getGPCVal( $this->data
, $name, $default );
255 if( is_array( $val ) ) {
258 if( is_null( $val ) ) {
266 * Set an aribtrary value into our get/post data.
267 * @param $key string Key name to use
268 * @param $value mixed Value to set
269 * @return mixed old value if one was present, null otherwise
271 function setVal( $key, $value ) {
272 $ret = isset( $this->data
[$key] ) ?
$this->data
[$key] : null;
273 $this->data
[$key] = $value;
278 * Fetch an array from the input 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.
282 * @param $name string
283 * @param $default array: optional default (or NULL)
286 function getArray( $name, $default = NULL ) {
287 $val = $this->getGPCVal( $this->data
, $name, $default );
288 if( is_null( $val ) ) {
296 * Fetch an array of integers, or return $default if it's not set.
297 * If source was scalar, will return an array with a single element.
298 * If no source and no default, returns NULL.
299 * If an array is returned, contents are guaranteed to be integers.
301 * @param $name string
302 * @param $default array: option default (or NULL)
303 * @return array of ints
305 function getIntArray( $name, $default = NULL ) {
306 $val = $this->getArray( $name, $default );
307 if( is_array( $val ) ) {
308 $val = array_map( 'intval', $val );
314 * Fetch an integer value from the input or return $default if not set.
315 * Guaranteed to return an integer; non-numeric input will typically
317 * @param $name string
318 * @param $default int
321 function getInt( $name, $default = 0 ) {
322 return intval( $this->getVal( $name, $default ) );
326 * Fetch an integer value from the input or return null if empty.
327 * Guaranteed to return an integer or null; non-numeric input will
328 * typically return null.
329 * @param $name string
332 function getIntOrNull( $name ) {
333 $val = $this->getVal( $name );
334 return is_numeric( $val )
340 * Fetch a boolean value from the input or return $default if not set.
341 * Guaranteed to return true or false, with normal PHP semantics for
342 * boolean interpretation of strings.
343 * @param $name string
344 * @param $default bool
347 function getBool( $name, $default = false ) {
348 return $this->getVal( $name, $default ) ?
true : false;
352 * Return true if the named value is set in the input, whatever that
353 * value is (even "0"). Return false if the named value is not set.
354 * Example use is checking for the presence of check boxes in forms.
355 * @param $name string
358 function getCheck( $name ) {
359 # Checkboxes and buttons are only present when clicked
360 # Presence connotes truth, abscense false
361 $val = $this->getVal( $name, NULL );
362 return isset( $val );
366 * Fetch a text string from the given array or return $default if it's not
367 * set. \r is stripped from the text, and with some language modules there
368 * is an input transliteration applied. This should generally be used for
369 * form <textarea> and <input> fields. Used for user-supplied freeform text
370 * input (for which input transformations may be required - e.g. Esperanto
373 * @param $name string
374 * @param $default string: optional
377 function getText( $name, $default = '' ) {
379 $val = $this->getVal( $name, $default );
380 return str_replace( "\r\n", "\n",
381 $wgContLang->recodeInput( $val ) );
385 * Extracts the given named values into an array.
386 * If no arguments are given, returns all input values.
387 * No transformation is performed on the values.
389 function getValues() {
390 $names = func_get_args();
391 if ( count( $names ) == 0 ) {
392 $names = array_keys( $this->data
);
396 foreach ( $names as $name ) {
397 $value = $this->getVal( $name );
398 if ( !is_null( $value ) ) {
399 $retVal[$name] = $value;
406 * Returns true if the present request was reached by a POST operation,
407 * false otherwise (GET, HEAD, or command-line).
409 * Note that values retrieved by the object may come from the
410 * GET URL etc even on a POST request.
414 function wasPosted() {
415 return $_SERVER['REQUEST_METHOD'] == 'POST';
419 * Returns true if there is a session cookie set.
420 * This does not necessarily mean that the user is logged in!
422 * If you want to check for an open session, use session_id()
423 * instead; that will also tell you if the session was opened
424 * during the current request (in which case the cookie will
425 * be sent back to the client at the end of the script run).
429 function checkSessionCookie() {
430 return isset( $_COOKIE[session_name()] );
434 * Return the path portion of the request URI.
437 function getRequestURL() {
438 if( isset( $_SERVER['REQUEST_URI'] ) ) {
439 $base = $_SERVER['REQUEST_URI'];
440 } elseif( isset( $_SERVER['SCRIPT_NAME'] ) ) {
441 // Probably IIS; doesn't set REQUEST_URI
442 $base = $_SERVER['SCRIPT_NAME'];
443 if( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
444 $base .= '?' . $_SERVER['QUERY_STRING'];
447 // This shouldn't happen!
448 throw new MWException( "Web server doesn't provide either " .
449 "REQUEST_URI or SCRIPT_NAME. Report details of your " .
450 "web server configuration to http://bugzilla.wikimedia.org/" );
452 // User-agents should not send a fragment with the URI, but
453 // if they do, and the web server passes it on to us, we
454 // need to strip it or we get false-positive redirect loops
455 // or weird output URLs
456 $hash = strpos( $base, '#' );
457 if( $hash !== false ) {
458 $base = substr( $base, 0, $hash );
460 if( $base{0} == '/' ) {
463 // We may get paths with a host prepended; strip it.
464 return preg_replace( '!^[^:]+://[^/]+/!', '/', $base );
469 * Return the request URI with the canonical service and hostname.
472 function getFullRequestURL() {
474 return $wgServer . $this->getRequestURL();
478 * Take an arbitrary query and rewrite the present URL to include it
479 * @param $query String: query string fragment; do not include initial '?'
482 function appendQuery( $query ) {
485 foreach( $_GET as $var => $val ) {
486 if ( $var == 'title' )
488 if ( is_array( $val ) )
489 /* This will happen given a request like
490 * http://en.wikipedia.org/w/index.php?title[]=Special:Userlogin&returnto[]=Main_Page
493 $basequery .= '&' . urlencode( $var ) . '=' . urlencode( $val );
495 $basequery .= '&' . $query;
498 $basequery = substr( $basequery, 1 );
499 return $wgTitle->getLocalURL( $basequery );
503 * HTML-safe version of appendQuery().
504 * @param $query String: query string fragment; do not include initial '?'
507 function escapeAppendQuery( $query ) {
508 return htmlspecialchars( $this->appendQuery( $query ) );
511 function appendQueryValue( $key, $value, $onlyquery = false ) {
512 return $this->appendQueryArray( array( $key => $value ), $onlyquery );
516 * Appends or replaces value of query variables.
517 * @param $array Array of values to replace/add to query
518 * @param $onlyquery Bool: whether to only return the query string and not
522 function appendQueryArray( $array, $onlyquery = false ) {
525 unset( $newquery['title'] );
526 $newquery = array_merge( $newquery, $array );
527 $query = wfArrayToCGI( $newquery );
528 return $onlyquery ?
$query : $wgTitle->getLocalURL( $query );
532 * Check for limit and offset parameters on the input, and return sensible
533 * defaults if not given. The limit must be positive and is capped at 5000.
534 * Offset must be positive but is not capped.
536 * @param $deflimit Integer: limit to use if no input and the user hasn't set the option.
537 * @param $optionname String: to specify an option other than rclimit to pull from.
538 * @return array first element is limit, second is offset
540 function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
543 $limit = $this->getInt( 'limit', 0 );
544 if( $limit < 0 ) $limit = 0;
545 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
546 $limit = (int)$wgUser->getOption( $optionname );
548 if( $limit <= 0 ) $limit = $deflimit;
549 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
551 $offset = $this->getInt( 'offset', 0 );
552 if( $offset < 0 ) $offset = 0;
554 return array( $limit, $offset );
558 * Return the path to the temporary file where PHP has stored the upload.
559 * @param $key String:
560 * @return string or NULL if no such file.
562 function getFileTempname( $key ) {
563 if( !isset( $_FILES[$key] ) ) {
566 return $_FILES[$key]['tmp_name'];
570 * Return the size of the upload, or 0.
571 * @param $key String:
574 function getFileSize( $key ) {
575 if( !isset( $_FILES[$key] ) ) {
578 return $_FILES[$key]['size'];
582 * Return the upload error or 0
583 * @param $key String:
586 function getUploadError( $key ) {
587 if( !isset( $_FILES[$key] ) ||
!isset( $_FILES[$key]['error'] ) ) {
588 return 0/*UPLOAD_ERR_OK*/;
590 return $_FILES[$key]['error'];
594 * Return the original filename of the uploaded file, as reported by
595 * the submitting user agent. HTML-style character entities are
596 * interpreted and normalized to Unicode normalization form C, in part
597 * to deal with weird input from Safari with non-ASCII filenames.
599 * Other than this the name is not verified for being a safe filename.
601 * @param $key String:
602 * @return string or NULL if no such file.
604 function getFileName( $key ) {
605 if( !isset( $_FILES[$key] ) ) {
608 $name = $_FILES[$key]['name'];
610 # Safari sends filenames in HTML-encoded Unicode form D...
611 # Horrid and evil! Let's try to make some kind of sense of it.
612 $name = Sanitizer
::decodeCharReferences( $name );
613 $name = UtfNormal
::cleanUp( $name );
614 wfDebug( "WebRequest::getFileName() '" . $_FILES[$key]['name'] . "' normalized to '$name'\n" );
619 * Return a handle to WebResponse style object, for setting cookies,
620 * headers and other stuff, for Request being worked on.
622 function response() {
623 /* Lazy initialization of response object for this request */
624 if (!is_object($this->_response
)) {
625 $this->_response
= new WebResponse
;
627 return $this->_response
;
631 * Get a request header, or false if it isn't set
632 * @param $name String: case-insensitive header name
634 function getHeader( $name ) {
635 $name = strtoupper( $name );
636 if ( function_exists( 'apache_request_headers' ) ) {
637 if ( !isset( $this->headers
) ) {
638 $this->headers
= array();
639 foreach ( apache_request_headers() as $tempName => $tempValue ) {
640 $this->headers
[ strtoupper( $tempName ) ] = $tempValue;
643 if ( isset( $this->headers
[$name] ) ) {
644 return $this->headers
[$name];
649 $name = 'HTTP_' . str_replace( '-', '_', $name );
650 if ( isset( $_SERVER[$name] ) ) {
651 return $_SERVER[$name];
659 * Get data from $_SESSION
661 function getSessionData( $key ) {
662 if( !isset( $_SESSION[$key] ) )
664 return $_SESSION[$key];
666 function setSessionData( $key, $data ) {
667 $_SESSION[$key] = $data;
672 * WebRequest clone which takes values from a provided array.
676 class FauxRequest
extends WebRequest
{
677 var $wasPosted = false;
680 * @param $data Array of *non*-urlencoded key => value pairs, the
681 * fake GET/POST values
682 * @param $wasPosted Bool: whether to treat the data as POST
684 function FauxRequest( $data, $wasPosted = false, $session = null ) {
685 if( is_array( $data ) ) {
688 throw new MWException( "FauxRequest() got bogus data" );
690 $this->wasPosted
= $wasPosted;
691 $this->headers
= array();
692 $this->session
= $session ?
$session : array();
695 function notImplemented( $method ) {
696 throw new MWException( "{$method}() not implemented" );
699 function getText( $name, $default = '' ) {
700 # Override; don't recode since we're using internal data
701 return (string)$this->getVal( $name, $default );
704 function getValues() {
708 function wasPosted() {
709 return $this->wasPosted
;
712 function checkSessionCookie() {
716 function getRequestURL() {
717 $this->notImplemented( __METHOD__
);
720 function appendQuery( $query ) {
721 $this->notImplemented( __METHOD__
);
724 function getHeader( $name ) {
725 return isset( $this->headers
[$name] ) ?
$this->headers
[$name] : false;
728 function getSessionData( $key ) {
729 if( !isset( $this->session
[$key] ) )
731 return $this->session
[$key];
733 function setSessionData( $key, $data ) {
734 $this->notImplemented( __METHOD__
);