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