Use Doxygen @addtogroup instead of phpdoc @package && @subpackage
[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 * The WebRequest class encapsulates getting at data passed in the
26 * URL or via a POSTed form, handling remove of "magic quotes" slashes,
27 * stripping illegal input characters and normalizing Unicode sequences.
28 *
29 * Usually this is used via a global singleton, $wgRequest. You should
30 * not create a second WebRequest object; make a FauxRequest object if
31 * you want to pass arbitrary data to some function in place of the web
32 * input.
33 *
34 */
35
36 /**
37 * Some entry points may use this file without first enabling the
38 * autoloader.
39 */
40 if ( !function_exists( '__autoload' ) ) {
41 require_once( dirname(__FILE__) . '/normal/UtfNormal.php' );
42 }
43
44 class WebRequest {
45 function __construct() {
46 $this->checkMagicQuotes();
47 global $wgUsePathInfo;
48 if ( $wgUsePathInfo ) {
49 if ( isset( $_SERVER['ORIG_PATH_INFO'] ) && $_SERVER['ORIG_PATH_INFO'] != '' ) {
50 # Mangled PATH_INFO
51 # http://bugs.php.net/bug.php?id=31892
52 # Also reported when ini_get('cgi.fix_pathinfo')==false
53 $_GET['title'] = $_REQUEST['title'] = substr( $_SERVER['ORIG_PATH_INFO'], 1 );
54 } elseif ( isset( $_SERVER['PATH_INFO'] ) && ($_SERVER['PATH_INFO'] != '') && $wgUsePathInfo ) {
55 $_GET['title'] = $_REQUEST['title'] = substr( $_SERVER['PATH_INFO'], 1 );
56 }
57 }
58 }
59
60 private $_response;
61
62 /**
63 * Recursively strips slashes from the given array;
64 * used for undoing the evil that is magic_quotes_gpc.
65 * @param array &$arr will be modified
66 * @return array the original array
67 * @private
68 */
69 function &fix_magic_quotes( &$arr ) {
70 foreach( $arr as $key => $val ) {
71 if( is_array( $val ) ) {
72 $this->fix_magic_quotes( $arr[$key] );
73 } else {
74 $arr[$key] = stripslashes( $val );
75 }
76 }
77 return $arr;
78 }
79
80 /**
81 * If magic_quotes_gpc option is on, run the global arrays
82 * through fix_magic_quotes to strip out the stupid slashes.
83 * WARNING: This should only be done once! Running a second
84 * time could damage the values.
85 * @private
86 */
87 function checkMagicQuotes() {
88 if ( get_magic_quotes_gpc() ) {
89 $this->fix_magic_quotes( $_COOKIE );
90 $this->fix_magic_quotes( $_ENV );
91 $this->fix_magic_quotes( $_GET );
92 $this->fix_magic_quotes( $_POST );
93 $this->fix_magic_quotes( $_REQUEST );
94 $this->fix_magic_quotes( $_SERVER );
95 }
96 }
97
98 /**
99 * Recursively normalizes UTF-8 strings in the given array.
100 * @param array $data string or array
101 * @return cleaned-up version of the given
102 * @private
103 */
104 function normalizeUnicode( $data ) {
105 if( is_array( $data ) ) {
106 foreach( $data as $key => $val ) {
107 $data[$key] = $this->normalizeUnicode( $val );
108 }
109 } else {
110 $data = UtfNormal::cleanUp( $data );
111 }
112 return $data;
113 }
114
115 /**
116 * Fetch a value from the given array or return $default if it's not set.
117 *
118 * @param array $arr
119 * @param string $name
120 * @param mixed $default
121 * @return mixed
122 * @private
123 */
124 function getGPCVal( $arr, $name, $default ) {
125 if( isset( $arr[$name] ) ) {
126 global $wgContLang;
127 $data = $arr[$name];
128 if( isset( $_GET[$name] ) && !is_array( $data ) ) {
129 # Check for alternate/legacy character encoding.
130 if( isset( $wgContLang ) ) {
131 $data = $wgContLang->checkTitleEncoding( $data );
132 }
133 }
134 $data = $this->normalizeUnicode( $data );
135 return $data;
136 } else {
137 return $default;
138 }
139 }
140
141 /**
142 * Fetch a scalar from the input or return $default if it's not set.
143 * Returns a string. Arrays are discarded.
144 *
145 * @param string $name
146 * @param string $default optional default (or NULL)
147 * @return string
148 */
149 function getVal( $name, $default = NULL ) {
150 $val = $this->getGPCVal( $_REQUEST, $name, $default );
151 if( is_array( $val ) ) {
152 $val = $default;
153 }
154 if( is_null( $val ) ) {
155 return null;
156 } else {
157 return (string)$val;
158 }
159 }
160
161 /**
162 * Fetch an array from the input or return $default if it's not set.
163 * If source was scalar, will return an array with a single element.
164 * If no source and no default, returns NULL.
165 *
166 * @param string $name
167 * @param array $default optional default (or NULL)
168 * @return array
169 */
170 function getArray( $name, $default = NULL ) {
171 $val = $this->getGPCVal( $_REQUEST, $name, $default );
172 if( is_null( $val ) ) {
173 return null;
174 } else {
175 return (array)$val;
176 }
177 }
178
179 /**
180 * Fetch an array of integers, or return $default if it's not set.
181 * If source was scalar, will return an array with a single element.
182 * If no source and no default, returns NULL.
183 * If an array is returned, contents are guaranteed to be integers.
184 *
185 * @param string $name
186 * @param array $default option default (or NULL)
187 * @return array of ints
188 */
189 function getIntArray( $name, $default = NULL ) {
190 $val = $this->getArray( $name, $default );
191 if( is_array( $val ) ) {
192 $val = array_map( 'intval', $val );
193 }
194 return $val;
195 }
196
197 /**
198 * Fetch an integer value from the input or return $default if not set.
199 * Guaranteed to return an integer; non-numeric input will typically
200 * return 0.
201 * @param string $name
202 * @param int $default
203 * @return int
204 */
205 function getInt( $name, $default = 0 ) {
206 return intval( $this->getVal( $name, $default ) );
207 }
208
209 /**
210 * Fetch an integer value from the input or return null if empty.
211 * Guaranteed to return an integer or null; non-numeric input will
212 * typically return null.
213 * @param string $name
214 * @return int
215 */
216 function getIntOrNull( $name ) {
217 $val = $this->getVal( $name );
218 return is_numeric( $val )
219 ? intval( $val )
220 : null;
221 }
222
223 /**
224 * Fetch a boolean value from the input or return $default if not set.
225 * Guaranteed to return true or false, with normal PHP semantics for
226 * boolean interpretation of strings.
227 * @param string $name
228 * @param bool $default
229 * @return bool
230 */
231 function getBool( $name, $default = false ) {
232 return $this->getVal( $name, $default ) ? true : false;
233 }
234
235 /**
236 * Return true if the named value is set in the input, whatever that
237 * value is (even "0"). Return false if the named value is not set.
238 * Example use is checking for the presence of check boxes in forms.
239 * @param string $name
240 * @return bool
241 */
242 function getCheck( $name ) {
243 # Checkboxes and buttons are only present when clicked
244 # Presence connotes truth, abscense false
245 $val = $this->getVal( $name, NULL );
246 return isset( $val );
247 }
248
249 /**
250 * Fetch a text string from the given array or return $default if it's not
251 * set. \r is stripped from the text, and with some language modules there
252 * is an input transliteration applied. This should generally be used for
253 * form <textarea> and <input> fields.
254 *
255 * @param string $name
256 * @param string $default optional
257 * @return string
258 */
259 function getText( $name, $default = '' ) {
260 global $wgContLang;
261 $val = $this->getVal( $name, $default );
262 return str_replace( "\r\n", "\n",
263 $wgContLang->recodeInput( $val ) );
264 }
265
266 /**
267 * Extracts the given named values into an array.
268 * If no arguments are given, returns all input values.
269 * No transformation is performed on the values.
270 */
271 function getValues() {
272 $names = func_get_args();
273 if ( count( $names ) == 0 ) {
274 $names = array_keys( $_REQUEST );
275 }
276
277 $retVal = array();
278 foreach ( $names as $name ) {
279 $value = $this->getVal( $name );
280 if ( !is_null( $value ) ) {
281 $retVal[$name] = $value;
282 }
283 }
284 return $retVal;
285 }
286
287 /**
288 * Returns true if the present request was reached by a POST operation,
289 * false otherwise (GET, HEAD, or command-line).
290 *
291 * Note that values retrieved by the object may come from the
292 * GET URL etc even on a POST request.
293 *
294 * @return bool
295 */
296 function wasPosted() {
297 return $_SERVER['REQUEST_METHOD'] == 'POST';
298 }
299
300 /**
301 * Returns true if there is a session cookie set.
302 * This does not necessarily mean that the user is logged in!
303 *
304 * @return bool
305 */
306 function checkSessionCookie() {
307 return isset( $_COOKIE[ini_get('session.name')] );
308 }
309
310 /**
311 * Return the path portion of the request URI.
312 * @return string
313 */
314 function getRequestURL() {
315 if( isset( $_SERVER['REQUEST_URI'] ) ) {
316 $base = $_SERVER['REQUEST_URI'];
317 } elseif( isset( $_SERVER['SCRIPT_NAME'] ) ) {
318 // Probably IIS; doesn't set REQUEST_URI
319 $base = $_SERVER['SCRIPT_NAME'];
320 if( isset( $_SERVER['QUERY_STRING'] ) && $_SERVER['QUERY_STRING'] != '' ) {
321 $base .= '?' . $_SERVER['QUERY_STRING'];
322 }
323 } else {
324 // This shouldn't happen!
325 throw new MWException( "Web server doesn't provide either " .
326 "REQUEST_URI or SCRIPT_NAME. Report details of your " .
327 "web server configuration to http://bugzilla.wikimedia.org/" );
328 }
329 if( $base{0} == '/' ) {
330 return $base;
331 } else {
332 // We may get paths with a host prepended; strip it.
333 return preg_replace( '!^[^:]+://[^/]+/!', '/', $base );
334 }
335 }
336
337 /**
338 * Return the request URI with the canonical service and hostname.
339 * @return string
340 */
341 function getFullRequestURL() {
342 global $wgServer;
343 return $wgServer . $this->getRequestURL();
344 }
345
346 /**
347 * Take an arbitrary query and rewrite the present URL to include it
348 * @param $query String: query string fragment; do not include initial '?'
349 * @return string
350 */
351 function appendQuery( $query ) {
352 global $wgTitle;
353 $basequery = '';
354 foreach( $_GET as $var => $val ) {
355 if ( $var == 'title' )
356 continue;
357 if ( is_array( $val ) )
358 /* This will happen given a request like
359 * http://en.wikipedia.org/w/index.php?title[]=Special:Userlogin&returnto[]=Main_Page
360 */
361 continue;
362 $basequery .= '&' . urlencode( $var ) . '=' . urlencode( $val );
363 }
364 $basequery .= '&' . $query;
365
366 # Trim the extra &
367 $basequery = substr( $basequery, 1 );
368 return $wgTitle->getLocalURL( $basequery );
369 }
370
371 /**
372 * HTML-safe version of appendQuery().
373 * @param $query String: query string fragment; do not include initial '?'
374 * @return string
375 */
376 function escapeAppendQuery( $query ) {
377 return htmlspecialchars( $this->appendQuery( $query ) );
378 }
379
380 /**
381 * Check for limit and offset parameters on the input, and return sensible
382 * defaults if not given. The limit must be positive and is capped at 5000.
383 * Offset must be positive but is not capped.
384 *
385 * @param $deflimit Integer: limit to use if no input and the user hasn't set the option.
386 * @param $optionname String: to specify an option other than rclimit to pull from.
387 * @return array first element is limit, second is offset
388 */
389 function getLimitOffset( $deflimit = 50, $optionname = 'rclimit' ) {
390 global $wgUser;
391
392 $limit = $this->getInt( 'limit', 0 );
393 if( $limit < 0 ) $limit = 0;
394 if( ( $limit == 0 ) && ( $optionname != '' ) ) {
395 $limit = (int)$wgUser->getOption( $optionname );
396 }
397 if( $limit <= 0 ) $limit = $deflimit;
398 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
399
400 $offset = $this->getInt( 'offset', 0 );
401 if( $offset < 0 ) $offset = 0;
402
403 return array( $limit, $offset );
404 }
405
406 /**
407 * Return the path to the temporary file where PHP has stored the upload.
408 * @param $key String:
409 * @return string or NULL if no such file.
410 */
411 function getFileTempname( $key ) {
412 if( !isset( $_FILES[$key] ) ) {
413 return NULL;
414 }
415 return $_FILES[$key]['tmp_name'];
416 }
417
418 /**
419 * Return the size of the upload, or 0.
420 * @param $key String:
421 * @return integer
422 */
423 function getFileSize( $key ) {
424 if( !isset( $_FILES[$key] ) ) {
425 return 0;
426 }
427 return $_FILES[$key]['size'];
428 }
429
430 /**
431 * Return the upload error or 0
432 * @param $key String:
433 * @return integer
434 */
435 function getUploadError( $key ) {
436 if( !isset( $_FILES[$key] ) || !isset( $_FILES[$key]['error'] ) ) {
437 return 0/*UPLOAD_ERR_OK*/;
438 }
439 return $_FILES[$key]['error'];
440 }
441
442 /**
443 * Return the original filename of the uploaded file, as reported by
444 * the submitting user agent. HTML-style character entities are
445 * interpreted and normalized to Unicode normalization form C, in part
446 * to deal with weird input from Safari with non-ASCII filenames.
447 *
448 * Other than this the name is not verified for being a safe filename.
449 *
450 * @param $key String:
451 * @return string or NULL if no such file.
452 */
453 function getFileName( $key ) {
454 if( !isset( $_FILES[$key] ) ) {
455 return NULL;
456 }
457 $name = $_FILES[$key]['name'];
458
459 # Safari sends filenames in HTML-encoded Unicode form D...
460 # Horrid and evil! Let's try to make some kind of sense of it.
461 $name = Sanitizer::decodeCharReferences( $name );
462 $name = UtfNormal::cleanUp( $name );
463 wfDebug( "WebRequest::getFileName() '" . $_FILES[$key]['name'] . "' normalized to '$name'\n" );
464 return $name;
465 }
466
467 /**
468 * Return a handle to WebResponse style object, for setting cookies,
469 * headers and other stuff, for Request being worked on.
470 */
471 function response() {
472 /* Lazy initialization of response object for this request */
473 if (!is_object($this->_response)) {
474 $this->_response = new WebResponse;
475 }
476 return $this->_response;
477 }
478
479 }
480
481 /**
482 * WebRequest clone which takes values from a provided array.
483 *
484 */
485 class FauxRequest extends WebRequest {
486 var $data = null;
487 var $wasPosted = false;
488
489 function FauxRequest( $data, $wasPosted = false ) {
490 if( is_array( $data ) ) {
491 $this->data = $data;
492 } else {
493 throw new MWException( "FauxRequest() got bogus data" );
494 }
495 $this->wasPosted = $wasPosted;
496 }
497
498 function getVal( $name, $default = NULL ) {
499 return $this->getGPCVal( $this->data, $name, $default );
500 }
501
502 function getText( $name, $default = '' ) {
503 # Override; don't recode since we're using internal data
504 return $this->getVal( $name, $default );
505 }
506
507 function getValues() {
508 return $this->data;
509 }
510
511 function wasPosted() {
512 return $this->wasPosted;
513 }
514
515 function checkSessionCookie() {
516 return false;
517 }
518
519 function getRequestURL() {
520 throw new MWException( 'FauxRequest::getRequestURL() not implemented' );
521 }
522
523 function appendQuery( $query ) {
524 throw new MWException( 'FauxRequest::appendQuery() not implemented' );
525 }
526
527 }
528
529 ?>