Fix typo in comment
[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 var $data = array();
46
47 function __construct() {
48 /// @fixme This preemptive de-quoting can interfere with other web libraries
49 /// and increases our memory footprint. It would be cleaner to do on
50 /// demand; but currently we have no wrapper for $_SERVER etc.
51 $this->checkMagicQuotes();
52
53 // POST overrides GET data
54 // We don't use $_REQUEST here to avoid interference from cookies...
55 $this->data = array_merge( $_GET, $_POST );
56 }
57
58 /**
59 * Check for title, action, and/or variant data in the URL
60 * and interpolate it into the GET variables.
61 * This should only be run after $wgContLang is available,
62 * as we may need the list of language variants to determine
63 * available variant URLs.
64 */
65 function interpolateTitle() {
66 global $wgUsePathInfo;
67 if ( $wgUsePathInfo ) {
68 // PATH_INFO is mangled due to http://bugs.php.net/bug.php?id=31892
69 // And also by Apache 2.x, double slashes are converted to single slashes.
70 // So we will use REQUEST_URI if possible.
71 $matches = array();
72 if ( !empty( $_SERVER['REQUEST_URI'] ) ) {
73 // Slurp out the path portion to examine...
74 $url = $_SERVER['REQUEST_URI'];
75 if ( !preg_match( '!^https?://!', $url ) ) {
76 $url = 'http://unused' . $url;
77 }
78 $a = parse_url( $url );
79 if( $a ) {
80 $path = $a['path'];
81
82 global $wgScript;
83 if( $path == $wgScript ) {
84 // Script inside a rewrite path?
85 // Abort to keep from breaking...
86 return;
87 }
88 // Raw PATH_INFO style
89 $matches = $this->extractTitle( $path, "$wgScript/$1" );
90
91 global $wgArticlePath;
92 if( !$matches && $wgArticlePath ) {
93 $matches = $this->extractTitle( $path, $wgArticlePath );
94 }
95
96 global $wgActionPaths;
97 if( !$matches && $wgActionPaths ) {
98 $matches = $this->extractTitle( $path, $wgActionPaths, 'action' );
99 }
100
101 global $wgVariantArticlePath, $wgContLang;
102 if( !$matches && $wgVariantArticlePath ) {
103 $variantPaths = array();
104 foreach( $wgContLang->getVariants() as $variant ) {
105 $variantPaths[$variant] =
106 str_replace( '$2', $variant, $wgVariantArticlePath );
107 }
108 $matches = $this->extractTitle( $path, $variantPaths, 'variant' );
109 }
110 }
111 } elseif ( isset( $_SERVER['ORIG_PATH_INFO'] ) && $_SERVER['ORIG_PATH_INFO'] != '' ) {
112 // Mangled PATH_INFO
113 // http://bugs.php.net/bug.php?id=31892
114 // Also reported when ini_get('cgi.fix_pathinfo')==false
115 $matches['title'] = substr( $_SERVER['ORIG_PATH_INFO'], 1 );
116
117 } elseif ( isset( $_SERVER['PATH_INFO'] ) && ($_SERVER['PATH_INFO'] != '') ) {
118 // Regular old PATH_INFO yay
119 $matches['title'] = substr( $_SERVER['PATH_INFO'], 1 );
120 }
121 foreach( $matches as $key => $val) {
122 $this->data[$key] = $_GET[$key] = $_REQUEST[$key] = $val;
123 }
124 }
125 }
126
127 /**
128 * Internal URL rewriting function; tries to extract page title and,
129 * optionally, one other fixed parameter value from a URL path.
130 *
131 * @param string $path the URL path given from the client
132 * @param array $bases one or more URLs, optionally with $1 at the end
133 * @param string $key if provided, the matching key in $bases will be
134 * passed on as the value of this URL parameter
135 * @return array of URL variables to interpolate; empty if no match
136 */
137 private function extractTitle( $path, $bases, $key=false ) {
138 foreach( (array)$bases as $keyValue => $base ) {
139 // Find the part after $wgArticlePath
140 $base = str_replace( '$1', '', $base );
141 $baseLen = strlen( $base );
142 if( substr( $path, 0, $baseLen ) == $base ) {
143 $raw = substr( $path, $baseLen );
144 if( $raw !== '' ) {
145 $matches = array( 'title' => rawurldecode( $raw ) );
146 if( $key ) {
147 $matches[$key] = $keyValue;
148 }
149 return $matches;
150 }
151 }
152 }
153 return array();
154 }
155
156 private $_response;
157
158 /**
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
164 */
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 );
171 }
172 }
173 return $arr;
174 }
175
176 /**
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
182 */
183 function checkMagicQuotes() {
184 if ( 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 );
191 }
192 }
193
194 /**
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
199 */
200 function normalizeUnicode( $data ) {
201 if( is_array( $data ) ) {
202 foreach( $data as $key => $val ) {
203 $data[$key] = $this->normalizeUnicode( $val );
204 }
205 } else {
206 $data = UtfNormal::cleanUp( $data );
207 }
208 return $data;
209 }
210
211 /**
212 * Fetch a value from the given array or return $default if it's not set.
213 *
214 * @param array $arr
215 * @param string $name
216 * @param mixed $default
217 * @return mixed
218 * @private
219 */
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 );
228 }
229 }
230 $data = $this->normalizeUnicode( $data );
231 return $data;
232 } else {
233 return $default;
234 }
235 }
236
237 /**
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().
242 *
243 * @param string $name
244 * @param string $default optional default (or NULL)
245 * @return string
246 */
247 function getVal( $name, $default = NULL ) {
248 $val = $this->getGPCVal( $this->data, $name, $default );
249 if( is_array( $val ) ) {
250 $val = $default;
251 }
252 if( is_null( $val ) ) {
253 return null;
254 } else {
255 return (string)$val;
256 }
257 }
258
259 /**
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.
263 *
264 * @param string $name
265 * @param array $default optional default (or NULL)
266 * @return array
267 */
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;
274 }
275 }
276
277 /**
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.
282 *
283 * @param string $name
284 * @param array $default option default (or NULL)
285 * @return array of ints
286 */
287 function getIntArray( $name, $default = NULL ) {
288 $val = $this->getArray( $name, $default );
289 if( is_array( $val ) ) {
290 $val = array_map( 'intval', $val );
291 }
292 return $val;
293 }
294
295 /**
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
302 */
303 function getInt( $name, $default = 0 ) {
304 return intval( $this->getVal( $name, $default ) );
305 }
306
307 /**
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
313 */
314 function getIntOrNull( $name ) {
315 $val = $this->getVal( $name );
316 return is_numeric( $val )
317 ? intval( $val )
318 : null;
319 }
320
321 /**
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
328 */
329 function getBool( $name, $default = false ) {
330 return $this->getVal( $name, $default ) ? true : false;
331 }
332
333 /**
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
339 */
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 );
345 }
346
347 /**
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).
354 *
355 * @param string $name
356 * @param string $default optional
357 * @return string
358 */
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 ) );
364 }
365
366 /**
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.
370 */
371 function getValues() {
372 $names = func_get_args();
373 if ( count( $names ) == 0 ) {
374 $names = array_keys( $this->data );
375 }
376
377 $retVal = array();
378 foreach ( $names as $name ) {
379 $value = $this->getVal( $name );
380 if ( !is_null( $value ) ) {
381 $retVal[$name] = $value;
382 }
383 }
384 return $retVal;
385 }
386
387 /**
388 * Returns true if the present request was reached by a POST operation,
389 * false otherwise (GET, HEAD, or command-line).
390 *
391 * Note that values retrieved by the object may come from the
392 * GET URL etc even on a POST request.
393 *
394 * @return bool
395 */
396 function wasPosted() {
397 return $_SERVER['REQUEST_METHOD'] == 'POST';
398 }
399
400 /**
401 * Returns true if there is a session cookie set.
402 * This does not necessarily mean that the user is logged in!
403 *
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).
408 *
409 * @return bool
410 */
411 function checkSessionCookie() {
412 return isset( $_COOKIE[session_name()] );
413 }
414
415 /**
416 * Return the path portion of the request URI.
417 * @return string
418 */
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'];
427 }
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/" );
433 }
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 );
441 }
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 );
447 }
448 }
449
450 /**
451 * Return the request URI with the canonical service and hostname.
452 * @return string
453 */
454 function getFullRequestURL() {
455 global $wgServer;
456 return $wgServer . $this->getRequestURL();
457 }
458
459 /**
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
463 */
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
473 */
474 continue;
475 $basequery .= '&' . urlencode( $var ) . '=' . urlencode( $val );
476 }
477 $basequery .= '&' . $query;
478
479 # Trim the extra &
480 $basequery = substr( $basequery, 1 );
481 return $wgTitle->getLocalURL( $basequery );
482 }
483
484 /**
485 * HTML-safe version of appendQuery().
486 * @param $query String: query string fragment; do not include initial '?'
487 * @return string
488 */
489 function escapeAppendQuery( $query ) {
490 return htmlspecialchars( $this->appendQuery( $query ) );
491 }
492
493 /**
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.
497 *
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
501 */
502 function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
503 global $wgUser;
504
505 $limit = $this->getInt( 'limit', 0 );
506 if( $limit < 0 ) $limit = 0;
507 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
508 $limit = (int)$wgUser->getOption( $optionname );
509 }
510 if( $limit <= 0 ) $limit = $deflimit;
511 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
512
513 $offset = $this->getInt( 'offset', 0 );
514 if( $offset < 0 ) $offset = 0;
515
516 return array( $limit, $offset );
517 }
518
519 /**
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.
523 */
524 function getFileTempname( $key ) {
525 if( !isset( $_FILES[$key] ) ) {
526 return NULL;
527 }
528 return $_FILES[$key]['tmp_name'];
529 }
530
531 /**
532 * Return the size of the upload, or 0.
533 * @param $key String:
534 * @return integer
535 */
536 function getFileSize( $key ) {
537 if( !isset( $_FILES[$key] ) ) {
538 return 0;
539 }
540 return $_FILES[$key]['size'];
541 }
542
543 /**
544 * Return the upload error or 0
545 * @param $key String:
546 * @return integer
547 */
548 function getUploadError( $key ) {
549 if( !isset( $_FILES[$key] ) || !isset( $_FILES[$key]['error'] ) ) {
550 return 0/*UPLOAD_ERR_OK*/;
551 }
552 return $_FILES[$key]['error'];
553 }
554
555 /**
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.
560 *
561 * Other than this the name is not verified for being a safe filename.
562 *
563 * @param $key String:
564 * @return string or NULL if no such file.
565 */
566 function getFileName( $key ) {
567 if( !isset( $_FILES[$key] ) ) {
568 return NULL;
569 }
570 $name = $_FILES[$key]['name'];
571
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;
578 }
579
580 /**
581 * Return a handle to WebResponse style object, for setting cookies,
582 * headers and other stuff, for Request being worked on.
583 */
584 function response() {
585 /* Lazy initialization of response object for this request */
586 if (!is_object($this->_response)) {
587 $this->_response = new WebResponse;
588 }
589 return $this->_response;
590 }
591
592 }
593
594 /**
595 * WebRequest clone which takes values from a provided array.
596 *
597 */
598 class FauxRequest extends WebRequest {
599 var $wasPosted = false;
600
601 /**
602 * @param array $data Array of *non*-urlencoded key => value pairs, the
603 * fake GET/POST values
604 * @param bool $wasPosted Whether to treat the data as POST
605 */
606 function FauxRequest( $data, $wasPosted = false ) {
607 if( is_array( $data ) ) {
608 $this->data = $data;
609 } else {
610 throw new MWException( "FauxRequest() got bogus data" );
611 }
612 $this->wasPosted = $wasPosted;
613 }
614
615 function getText( $name, $default = '' ) {
616 # Override; don't recode since we're using internal data
617 return (string)$this->getVal( $name, $default );
618 }
619
620 function getValues() {
621 return $this->data;
622 }
623
624 function wasPosted() {
625 return $this->wasPosted;
626 }
627
628 function checkSessionCookie() {
629 return false;
630 }
631
632 function getRequestURL() {
633 throw new MWException( 'FauxRequest::getRequestURL() not implemented' );
634 }
635
636 function appendQuery( $query ) {
637 throw new MWException( 'FauxRequest::appendQuery() not implemented' );
638 }
639
640 }
641
642