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