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