]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/Request.php
Remove FPDF
[SourceForge/phpwiki.git] / lib / Request.php
1 <?php
2
3 /*
4  * Copyright (C) 2002,2004,2005,2006,2009 $ThePhpWikiProgrammingTeam
5  *
6  * This file is part of PhpWiki.
7  *
8  * PhpWiki is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * PhpWiki is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License along
19  * with PhpWiki; if not, write to the Free Software Foundation, Inc.,
20  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21  */
22
23 class Request
24 {
25     public $args = array();
26
27     function __construct()
28     {
29         $this->_fix_magic_quotes_gpc();
30         $this->_fix_multipart_form_data();
31
32         switch ($this->get('REQUEST_METHOD')) {
33             case 'GET':
34             case 'HEAD':
35                 $this->args = &$GLOBALS['HTTP_GET_VARS'];
36                 break;
37             case 'POST':
38                 $this->args = &$GLOBALS['HTTP_POST_VARS'];
39                 break;
40             default:
41                 $this->args = array();
42                 break;
43         }
44
45         $this->session = new Request_SessionVars;
46         $this->cookies = new Request_CookieVars;
47
48         if (ACCESS_LOG or ACCESS_LOG_SQL) {
49             $this->_accesslog = new Request_AccessLog(ACCESS_LOG, ACCESS_LOG_SQL);
50         }
51
52         $GLOBALS['request'] = $this;
53     }
54
55     function get($key)
56     {
57         if (!empty($GLOBALS['HTTP_SERVER_VARS']))
58             $vars = &$GLOBALS['HTTP_SERVER_VARS'];
59         elseif (!empty($GLOBALS['HTTP_ENV_VARS']))
60             $vars = &$GLOBALS['HTTP_ENV_VARS']; // cgi or other servers than Apache
61         else
62             trigger_error("Serious php configuration error!"
63                     . " No HTTP_SERVER_VARS and HTTP_ENV_VARS vars available."
64                     . " These should get defined in lib/prepend.php",
65                 E_USER_WARNING);
66
67         if (isset($vars[$key]))
68             return $vars[$key];
69
70         switch ($key) {
71             case 'REMOTE_HOST':
72                 $addr = $vars['REMOTE_ADDR'];
73                 if (defined('ENABLE_REVERSE_DNS') && ENABLE_REVERSE_DNS)
74                     return $vars[$key] = gethostbyaddr($addr);
75                 else
76                     return $addr;
77             default:
78                 return false;
79         }
80     }
81
82     /**
83      * @param $key
84      * @return string|bool
85      */
86     function getArg($key)
87     {
88         if (isset($this->args[$key]))
89             return $this->args[$key];
90         return false;
91     }
92
93     function getArgs()
94     {
95         return $this->args;
96     }
97
98     function setArg($key, $val)
99     {
100         if ($val === false)
101             unset($this->args[$key]);
102         else
103             $this->args[$key] = $val;
104     }
105
106     // Well oh well. Do we really want to pass POST params back as GET?
107     function getURLtoSelf($args = false, $exclude = array())
108     {
109         $get_args = $this->args;
110         if ($args)
111             $get_args = array_merge($get_args, $args);
112
113         // leave out empty arg values
114         foreach ($get_args as $g => $v) {
115             if ($v === false or $v === '') unset($get_args[$g]);
116         }
117
118         // Err... good point...
119         // sortby buttons
120         if ($this->isPost()) {
121             $exclude = array_merge($exclude, array('action', 'auth'));
122             //$get_args = $args; // or only the provided
123             /*
124             trigger_error("Request::getURLtoSelf() should probably not be from POST",
125                           E_USER_NOTICE);
126             */
127         }
128
129         foreach ($exclude as $ex) {
130             if (!empty($get_args[$ex])) unset($get_args[$ex]);
131         }
132
133         $pagename = $get_args['pagename'];
134         unset ($get_args['pagename']);
135         if (!empty($get_args['action']) and $get_args['action'] == 'browse')
136             unset($get_args['action']);
137
138         return WikiURL($pagename, $get_args);
139     }
140
141     function isPost()
142     {
143         return $this->get("REQUEST_METHOD") == "POST";
144     }
145
146     function isGetOrHead()
147     {
148         return in_array($this->get('REQUEST_METHOD'),
149             array('GET', 'HEAD'));
150     }
151
152     function httpVersion()
153     {
154         if (!preg_match('@HTTP\s*/\s*(\d+.\d+)@', $this->get('SERVER_PROTOCOL'), $m))
155             return false;
156         return (float)$m[1];
157     }
158
159     /* Redirects after edit may fail if no theme signature image is defined.
160      * Set DISABLE_HTTP_REDIRECT = true then.
161      */
162     function redirect($url, $noreturn = true)
163     {
164         $bogus = defined('DISABLE_HTTP_REDIRECT') && DISABLE_HTTP_REDIRECT;
165
166         if (!$bogus) {
167             header("Location: $url");
168             /*
169              * "302 Found" is not really meant to be sent in response
170              * to a POST.  Worse still, according to (both HTTP 1.0
171              * and 1.1) spec, the user, if it is sent, the user agent
172              * is supposed to use the same method to fetch the
173              * redirected URI as the original.
174              *
175              * That means if we redirect from a POST, the user-agent
176              * supposed to generate another POST.  Not what we want.
177              * (We do this after a page save after all.)
178              *
179              * Fortunately, most/all browsers don't do that.
180              *
181              * "303 See Other" is what we really want.  But it only
182              * exists in HTTP/1.1
183              *
184              * FIXME: this is still not spec compliant for HTTP
185              * version < 1.1.
186              */
187             $status = $this->httpVersion() >= 1.1 ? 303 : 302;
188             $this->setStatus($status);
189         }
190
191         if ($noreturn) {
192             $this->discardOutput(); // This might print the gzip headers. Not good.
193             $this->buffer_output(false);
194
195             include_once 'lib/Template.php';
196             $tmpl = new Template('redirect', $this, array('REDIRECT_URL' => $url));
197             $tmpl->printXML();
198             $this->finish();
199         } elseif ($bogus) {
200             // Safari needs window.location.href = targeturl
201             return JavaScript("
202               function redirect(url) {
203                 if (typeof location.replace == 'function')
204                   location.replace(url);
205                 else if (typeof location.assign == 'function')
206                   location.assign(url);
207                 else if (self.location.href)
208                   self.location.href = url;
209                 else
210                   window.location = url;
211               }
212               redirect('" . addslashes($url) . "')");
213         }
214     }
215
216     /** Set validators for this response.
217      *
218      * This sets a (possibly incomplete) set of validators
219      * for this response.
220      *
221      * The validator set can be extended using appendValidators().
222      *
223      * When you're all done setting and appending validators, you
224      * must call checkValidators() to check them and set the
225      * appropriate headers in the HTTP response.
226      *
227      * Example Usage:
228      *  ...
229      *  $request->setValidators(array('pagename' => $pagename,
230      *                                '%mtime' => $rev->get('mtime')));
231      *  ...
232      *  // Wups... response content depends on $otherpage, too...
233      *  $request->appendValidators(array('otherpage' => $otherpagerev->getPageName(),
234      *                                   '%mtime' => $otherpagerev->get('mtime')));
235      *  ...
236      *  // After all validators have been set:
237      *  $request->checkValidators();
238      */
239     function setValidators($validator_set)
240     {
241         if (is_array($validator_set))
242             $validator_set = new HTTP_ValidatorSet($validator_set);
243         $this->_validators = $validator_set;
244     }
245
246     /** Append more validators for this response.
247      *  i.e dependencies on other pages mtimes
248      *  now it may be called in init also to simplify client code.
249      */
250     function appendValidators($validator_set)
251     {
252         if (!isset($this->_validators)) {
253             $this->setValidators($validator_set);
254             return;
255         }
256         $this->_validators->append($validator_set);
257     }
258
259     /** Check validators and set headers in HTTP response
260      *
261      * This sets the appropriate "Last-Modified" and "ETag"
262      * headers in the HTTP response.
263      *
264      * Additionally, if the validators match any(all) conditional
265      * headers in the HTTP request, this method will not return, but
266      * instead will send "304 Not Modified" or "412 Precondition
267      * Failed" (as appropriate) back to the client.
268      */
269     function checkValidators()
270     {
271         $validators = &$this->_validators;
272
273         // Set validator headers
274         if (!empty($this->_is_buffering_output) or !headers_sent()) {
275             if (($etag = $validators->getETag()) !== false)
276                 header("ETag: " . $etag->asString());
277             if (($mtime = $validators->getModificationTime()) !== false)
278                 header("Last-Modified: " . Rfc1123DateTime($mtime));
279
280             // Set cache control headers
281             $this->cacheControl();
282         }
283
284         if (CACHE_CONTROL == 'NO_CACHE')
285             return; // don't check conditionals...
286
287         // Check conditional headers in request
288         $status = $validators->checkConditionalRequest($this);
289         if ($status) {
290             // Return short response due to failed conditionals
291             $this->setStatus($status);
292             echo "\n\n";
293             $this->discardOutput();
294             $this->finish();
295             exit();
296         }
297     }
298
299     /** Set the cache control headers in the HTTP response.
300      */
301     function cacheControl($strategy = CACHE_CONTROL, $max_age = CACHE_CONTROL_MAX_AGE)
302     {
303         if ($strategy == 'NO_CACHE') {
304             $cache_control = "no-cache"; // better set private. See Pear HTTP_Header
305             $max_age = -20;
306         } elseif ($strategy == 'ALLOW_STALE' && $max_age > 0) {
307             $cache_control = sprintf("max-age=%d", $max_age);
308         } else {
309             $cache_control = "must-revalidate";
310             $max_age = -20;
311         }
312         header("Cache-Control: $cache_control");
313         header("Expires: " . Rfc1123DateTime(time() + $max_age));
314         header("Vary: Cookie"); // FIXME: add more here?
315     }
316
317     function setStatus($status)
318     {
319         if (preg_match('|^HTTP/.*?\s(\d+)|i', $status, $m)) {
320             header($status);
321             $status = $m[1];
322         } else {
323             $status = (integer)$status;
324             $reason = array('200' => 'OK',
325                 '302' => 'Found',
326                 '303' => 'See Other',
327                 '304' => 'Not Modified',
328                 '400' => 'Bad Request',
329                 '401' => 'Unauthorized',
330                 '403' => 'Forbidden',
331                 '404' => 'Not Found',
332                 '412' => 'Precondition Failed');
333             // FIXME: is it always okay to send HTTP/1.1 here, even for older clients?
334             header(sprintf("HTTP/1.1 %d %s", $status, $reason[$status]));
335         }
336
337         if (isset($this->_log_entry))
338             $this->_log_entry->setStatus($status);
339     }
340
341     function buffer_output($compress = true)
342     {
343         // FIXME: disables sessions (some byte before all headers_sent())
344         /*if (defined('USECACHE') and !USECACHE) {
345             $this->_is_buffering_output = false;
346             return;
347         }*/
348         if (defined('COMPRESS_OUTPUT')) {
349             if (!COMPRESS_OUTPUT)
350                 $compress = false;
351         } elseif (isCGI()) // necessary?
352             $compress = false;
353
354         if ($this->getArg('start_debug')) $compress = false;
355         if ($this->getArg('nocache'))
356             $compress = false;
357
358         // Should we compress even when apache_note is not available?
359         // sf.net bug #933183 and http://bugs.php.net/17557
360         // This effectively eliminates CGI, but all other servers also. hmm.
361         if ($compress
362             and (!function_exists('ob_gzhandler')
363                 or !function_exists('apache_note'))
364         )
365             $compress = false;
366
367         // "output handler 'ob_gzhandler' cannot be used twice"
368         // http://www.php.net/ob_gzhandler
369         if ($compress and ini_get("zlib.output_compression"))
370             $compress = false;
371
372         // New: we check for the client Accept-Encoding: "gzip" presence also
373         // This should eliminate a lot or reported problems.
374         if ($compress
375             and (!$this->get("HTTP_ACCEPT_ENCODING")
376                 or !strstr($this->get("HTTP_ACCEPT_ENCODING"), "gzip"))
377         )
378             $compress = false;
379
380         // Most RSS clients are NOT(!) application/xml gzip compatible yet.
381         // Even if they are sending the accept-encoding gzip header!
382         // wget is, Mozilla, and MSIE no.
383         // Of the RSS readers only MagpieRSS 0.5.2 is. http://www.rssgov.com/rssparsers.html
384         // See also http://phpwiki.sourceforge.net/phpwiki/KnownBugs
385         if ($compress
386             and $this->getArg('format')
387                 and strstr($this->getArg('format'), 'rss')
388         )
389             $compress = false;
390
391         if ($compress) {
392             ob_start('phpwiki_gzhandler');
393
394             // TODO: dont send a length or get the gzip'ed data length.
395             $this->_is_compressing_output = true;
396             header("Content-Encoding: gzip");
397             /*
398              * Attempt to prevent Apache from doing the dreaded double-gzip.
399              *
400              * It would be better if we could detect when apache was going
401              * to zip for us, and then let it ... but I have yet to figure
402              * out how to do that.
403              */
404             if (function_exists('apache_note'))
405                 @apache_note('no-gzip', 1);
406         } else {
407             // Now we alway buffer output.
408             // This is so we can set HTTP headers (e.g. for redirect)
409             // at any point.
410             // FIXME: change the name of this method.
411             ob_start();
412             $this->_is_compressing_output = false;
413         }
414         $this->_is_buffering_output = true;
415         $this->_ob_get_length = 0;
416     }
417
418     function discardOutput()
419     {
420         if (!empty($this->_is_buffering_output)) {
421             if (ob_get_length()) ob_clean();
422             $this->_is_buffering_output = false;
423         } else {
424             trigger_error("Not buffering output", E_USER_NOTICE);
425         }
426     }
427
428     /**
429      * Longer texts need too much memory on tiny or memory-limit=8MB systems.
430      * We might want to flush our buffer and restart again.
431      * (This would be fine if php would release its memory)
432      * Note that this must not be called inside Template expansion or other
433      * sections with ob_buffering.
434      */
435     function chunkOutput()
436     {
437         if (!empty($this->_is_buffering_output)
438             or (@ob_get_level())
439         ) {
440             $this->_do_chunked_output = true;
441             if (empty($this->_ob_get_length)) $this->_ob_get_length = 0;
442             $this->_ob_get_length += ob_get_length();
443             while (ob_get_level() > 0) {
444                 ob_end_flush();
445             }
446             if (ob_get_level() > 0) {
447                 ob_end_clean();
448             }
449             ob_start();
450         }
451     }
452
453     function finish()
454     {
455         $this->_finishing = true;
456         if (!empty($this->_accesslog)) {
457             $this->_accesslog->push($this);
458             if (empty($this->_do_chunked_output) and empty($this->_ob_get_length))
459                 $this->_ob_get_length = ob_get_length();
460             $this->_accesslog->setSize($this->_ob_get_length);
461             global $RUNTIMER;
462             if ($RUNTIMER) $this->_accesslog->setDuration($RUNTIMER->getTime());
463             // sql logging must be done before the db is closed.
464             if (isset($this->_accesslog->logtable))
465                 $this->_accesslog->write_sql();
466         }
467
468         if (!empty($this->_is_buffering_output)) {
469             // if _is_compressing_output then ob_get_length() returns
470             // the uncompressed length, not the gzip'ed as required.
471             if (!headers_sent() and !$this->_is_compressing_output) {
472                 // php url-rewriting miscalculates the ob length. fixes bug #1376007
473                 if (ini_get('use_trans_sid') == 'off') {
474                     if (empty($this->_do_chunked_output)) {
475                         $this->_ob_get_length = ob_get_length();
476                     }
477                     header(sprintf("Content-Length: %d", $this->_ob_get_length));
478                 }
479             }
480             $this->_is_buffering_output = false;
481             ob_end_flush();
482         } elseif (@ob_get_level()) {
483             ob_end_flush();
484         }
485         session_write_close();
486         if (!empty($this->_dbi)) {
487             $this->_dbi->close();
488             unset($this->_dbi);
489         }
490
491         exit;
492     }
493
494     function getSessionVar($key)
495     {
496         return $this->session->get($key);
497     }
498
499     function setSessionVar($key, $val)
500     {
501         if ($key == 'wiki_user') {
502             if (empty($val->page))
503                 $val->page = $this->getArg('pagename');
504             if (empty($val->action))
505                 $val->action = $this->getArg('action');
506             // avoid recursive objects and session resource handles
507             // avoid overlarge session data (max 4000 byte!)
508             if (isset($val->_group)) {
509                 unset($val->_group->_request);
510                 unset($val->_group->user);
511             }
512             unset($val->_HomePagehandle);
513             unset($val->_auth_dbi);
514         }
515         return $this->session->set($key, $val);
516     }
517
518     function deleteSessionVar($key)
519     {
520         return $this->session->delete($key);
521     }
522
523     function getCookieVar($key)
524     {
525         return $this->cookies->get($key);
526     }
527
528     function setCookieVar($key, $val, $lifetime_in_days = false, $path = false)
529     {
530         return $this->cookies->set($key, $val, $lifetime_in_days, $path);
531     }
532
533     function deleteCookieVar($key)
534     {
535         return $this->cookies->delete($key);
536     }
537
538     function getUploadedFile($key)
539     {
540         return Request_UploadedFile::getUploadedFile($key);
541     }
542
543     function _fix_magic_quotes_gpc()
544     {
545         $needs_fix = array('HTTP_POST_VARS',
546             'HTTP_GET_VARS',
547             'HTTP_COOKIE_VARS',
548             'HTTP_SERVER_VARS',
549             'HTTP_POST_FILES');
550
551         // Fix magic quotes.
552         if (get_magic_quotes_gpc()) {
553             foreach ($needs_fix as $vars)
554                 $this->_stripslashes($GLOBALS[$vars]);
555         }
556     }
557
558     function _stripslashes(&$var)
559     {
560         if (is_array($var)) {
561             foreach ($var as $key => $val)
562                 $this->_stripslashes($var[$key]);
563         } elseif (is_string($var))
564             $var = stripslashes($var);
565     }
566
567     function _fix_multipart_form_data()
568     {
569         if (preg_match('|^multipart/form-data|', $this->get('CONTENT_TYPE')))
570             $this->_strip_leading_nl($GLOBALS['HTTP_POST_VARS']);
571     }
572
573     function _strip_leading_nl(&$var)
574     {
575         if (is_array($var)) {
576             foreach ($var as $key => $val)
577                 $this->_strip_leading_nl($var[$key]);
578         } elseif (is_string($var))
579             $var = preg_replace('|^\r?\n?|', '', $var);
580     }
581 }
582
583 class Request_SessionVars
584 {
585     function __construct()
586     {
587         // Prevent cacheing problems with IE 5
588         session_cache_limiter('none');
589
590         // Avoid to get a notice if session is already started,
591         // for example if session.auto_start is activated
592         if (!session_id())
593             session_start();
594     }
595
596     function get($key)
597     {
598         $vars = &$GLOBALS['HTTP_SESSION_VARS'];
599         if (isset($vars[$key]))
600             return $vars[$key];
601         if (isset($_SESSION) and isset($_SESSION[$key])) // php-5.2
602             return $_SESSION[$key];
603         return false;
604     }
605
606     function set($key, $val)
607     {
608         $vars = &$GLOBALS['HTTP_SESSION_VARS'];
609         if (!function_usable('get_cfg_var') or get_cfg_var('register_globals')) {
610             // This is funky but necessary, at least in some PHP's
611             $GLOBALS[$key] = $val;
612         }
613         $vars[$key] = $val;
614         if (isset($_SESSION)) // php-5.2
615             $_SESSION[$key] = $val;
616     }
617
618     function delete($key)
619     {
620         $vars = &$GLOBALS['HTTP_SESSION_VARS'];
621         if (!function_usable('ini_get') or ini_get('register_globals'))
622             unset($GLOBALS[$key]);
623         if (DEBUG) trigger_error("delete session $key", E_USER_WARNING);
624         unset($vars[$key]);
625         if (isset($_SESSION)) // php-5.2
626             unset($_SESSION[$key]);
627     }
628 }
629
630 class Request_CookieVars
631 {
632
633     function get($key)
634     {
635         $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
636         if (isset($vars[$key])) {
637             @$decode = base64_decode($vars[$key]);
638             if (strlen($decode) > 3 and substr($decode, 1, 1) == ':') {
639                 @$val = unserialize($decode);
640                 if (!empty($val))
641                     return $val;
642             }
643             @$val = urldecode($vars[$key]);
644             if (!empty($val))
645                 return $val;
646         }
647         return false;
648     }
649
650     function get_old($key)
651     {
652         if (defined('FUSIONFORGE') and FUSIONFORGE) {
653             return false;
654         }
655         $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
656         if (isset($vars[$key])) {
657             @$decode = base64_decode($vars[$key]);
658             if (strlen($decode) > 3 and substr($decode, 1, 1) == ':') {
659                 @$val = unserialize($decode);
660                 if (!empty($val))
661                     return $val;
662             }
663             @$val = unserialize($vars[$key]);
664             if (!empty($val))
665                 return $val;
666             @$val = $vars[$key];
667             if (!empty($val))
668                 return $val;
669         }
670         return false;
671     }
672
673     function set($key, $val, $persist_days = false, $path = false)
674     {
675         // if already defined, ignore
676         if (defined('MAIN_setUser') and $key = getCookieName()) return;
677         if (defined('WIKI_XMLRPC') and WIKI_XMLRPC) return;
678
679         $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
680         if (is_numeric($persist_days)) {
681             $expires = time() + (24 * 3600) * $persist_days;
682         } else {
683             $expires = 0;
684         }
685         if (is_array($val) or is_object($val))
686             $packedval = base64_encode(serialize($val));
687         else
688             $packedval = urlencode($val);
689         $vars[$key] = $packedval;
690         @$_COOKIE[$key] = $packedval;
691         if ($path)
692             @setcookie($key, $packedval, $expires, $path);
693         else
694             @setcookie($key, $packedval, $expires);
695     }
696
697     function delete($key)
698     {
699         static $deleted = array();
700         if (isset($deleted[$key])) return;
701         if (defined('WIKI_XMLRPC') and WIKI_XMLRPC) return;
702
703         $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
704         if (!defined('COOKIE_DOMAIN'))
705             @setcookie($key, '', 0);
706         else
707             @setcookie($key, '', 0, COOKIE_DOMAIN);
708         unset($GLOBALS['HTTP_COOKIE_VARS'][$key]);
709         unset($_COOKIE[$key]);
710         $deleted[$key] = 1;
711     }
712 }
713
714 /* Win32 Note:
715    [\winnt\php.ini]
716    You must set "upload_tmp_dir" = "/tmp/" or "C:/tmp/"
717    Best on the same drive as apache, with forward slashes
718    and with ending slash!
719    Otherwise "\\" => "" and the uploaded file will not be found.
720 */
721 class Request_UploadedFile
722 {
723     function __construct($fileinfo)
724     {
725         $this->_info = $fileinfo;
726     }
727
728     function getUploadedFile($postname)
729     {
730         global $HTTP_POST_FILES;
731
732         // Against php5 with !ini_get('register-long-arrays'). See Bug #1180115
733         if (empty($HTTP_POST_FILES) and !empty($_FILES))
734             $HTTP_POST_FILES =& $_FILES;
735         if (!isset($HTTP_POST_FILES[$postname]))
736             return false;
737
738         $fileinfo =& $HTTP_POST_FILES[$postname];
739         if ($fileinfo['error']) {
740             // See https://sourceforge.net/forum/message.php?msg_id=3093651
741             $err = (int)$fileinfo['error'];
742             // errmsgs by Shilad Sen
743             switch ($err) {
744                 case 1:
745                     trigger_error(_("Upload error: file too big"), E_USER_WARNING);
746                     break;
747                 case 2:
748                     trigger_error(_("Upload error: file too big"), E_USER_WARNING);
749                     break;
750                 case 3:
751                     trigger_error(_("Upload error: file only partially received"), E_USER_WARNING);
752                     break;
753                 case 4:
754                     trigger_error(_("Upload error: no file selected"), E_USER_WARNING);
755                     break;
756                 default:
757                     trigger_error(_("Upload error: unknown error #") . $err, E_USER_WARNING);
758             }
759             return false;
760         }
761
762         // With windows/php 4.2.1 is_uploaded_file() always returns false.
763         // Be sure that upload_tmp_dir ends with a slash!
764         if (!is_uploaded_file($fileinfo['tmp_name'])) {
765             if (isWindows()) {
766                 if (!$tmp_file = get_cfg_var('upload_tmp_dir')) {
767                     $tmp_file = dirname(tempnam('', ''));
768                 }
769                 $tmp_file .= '/' . basename($fileinfo['tmp_name']);
770                 /* ending slash in php.ini upload_tmp_dir is required. */
771                 if (realpath(ereg_replace('/+', '/', $tmp_file)) != realpath($fileinfo['tmp_name'])) {
772                     trigger_error(sprintf("Uploaded tmpfile illegal: %s != %s.", $tmp_file, $fileinfo['tmp_name']) .
773                             "\n" .
774                             "Probably illegal TEMP environment or upload_tmp_dir setting. " .
775                             "Esp. on WINDOWS be sure to set upload_tmp_dir in php.ini to use forward slashes and " .
776                             "end with a slash. upload_tmp_dir = \"C:/WINDOWS/TEMP/\" is good suggestion.",
777                         E_USER_ERROR);
778                     return false;
779                 }
780             } else {
781                 trigger_error(sprintf("Uploaded tmpfile %s not found.", $fileinfo['tmp_name']) . "\n" .
782                         " Probably illegal TEMP environment or upload_tmp_dir setting.",
783                     E_USER_WARNING);
784             }
785         }
786         return new Request_UploadedFile($fileinfo);
787     }
788
789     function getSize()
790     {
791         return $this->_info['size'];
792     }
793
794     function getName()
795     {
796         return $this->_info['name'];
797     }
798
799     function getType()
800     {
801         return $this->_info['type'];
802     }
803
804     function getTmpName()
805     {
806         return $this->_info['tmp_name'];
807     }
808
809     function open()
810     {
811         if (($fd = fopen($this->_info['tmp_name'], "rb"))) {
812             if ($this->getSize() < filesize($this->_info['tmp_name'])) {
813                 // FIXME: Some PHP's (or is it some browsers?) put
814                 //    HTTP/MIME headers in the file body, some don't.
815                 //
816                 // At least, I think that's the case.  I know I used
817                 // to need this code, now I don't.
818                 //
819                 // This code is more-or-less untested currently.
820                 //
821                 // Dump HTTP headers.
822                 while (($header = fgets($fd, 4096))) {
823                     if (trim($header) == '') {
824                         break;
825                     } elseif (!preg_match('/^content-(length|type):/i', $header)) {
826                         rewind($fd);
827                         break;
828                     }
829                 }
830             }
831         }
832         return $fd;
833     }
834
835     function getContents()
836     {
837         $fd = $this->open();
838         $data = fread($fd, $this->getSize());
839         fclose($fd);
840         return $data;
841     }
842 }
843
844 /**
845  * Create NCSA "combined" log entry for current request.
846  * Also needed for advanced spam prevention.
847  * global object holding global state (sql or file, entries, to dump)
848  */
849 class Request_AccessLog
850 {
851     /**
852      * @param string $logfile Log file name.
853      * @param bool $do_sql
854      */
855     function __construct($logfile, $do_sql = false)
856     {
857         //global $request; // request not yet initialized!
858
859         $this->logfile = $logfile;
860         if ($logfile and !is_writeable($logfile)) {
861             trigger_error
862             (sprintf(_("%s is not writable."), _("The PhpWiki access log file"))
863                     . "\n"
864                     . sprintf(_("Please ensure that %s is writable, or redefine %s in config/config.ini."),
865                         sprintf(_("the file “%s”"), ACCESS_LOG),
866                         'ACCESS_LOG')
867                 , E_USER_NOTICE);
868         }
869         //$request->_accesslog =& $this;
870         //if (empty($request->_accesslog->entries))
871         register_shutdown_function("Request_AccessLogEntry_shutdown_function");
872
873         if ($do_sql) {
874             global $DBParams;
875             if (!in_array($DBParams['dbtype'], array('SQL', 'ADODB'))) {
876                 trigger_error("Unsupported database backend for ACCESS_LOG_SQL. Need DATABASE_TYPE=SQL or ADODB.");
877             } else {
878                 //$this->_dbi =& $request->_dbi;
879                 $this->logtable = (!empty($DBParams['prefix']) ? $DBParams['prefix'] : '') . "accesslog";
880             }
881         }
882         $this->entries = array();
883         $this->entries[] = new Request_AccessLogEntry($this);
884     }
885
886     function _do($cmd, &$arg)
887     {
888         if ($this->entries)
889             for ($i = 0; $i < count($this->entries); $i++)
890                 $this->entries[$i]->$cmd($arg);
891     }
892
893     function push(&$request)
894     {
895         $this->_do('push', $request);
896     }
897
898     function setSize($arg)
899     {
900         $this->_do('setSize', $arg);
901     }
902
903     function setStatus($arg)
904     {
905         $this->_do('setStatus', $arg);
906     }
907
908     function setDuration($arg)
909     {
910         $this->_do('setDuration', $arg);
911     }
912
913     /**
914      * Read sequentially all previous entries from the beginning.
915      * while ($logentry = Request_AccessLogEntry::read()) ;
916      * For internal log analyzers: RecentReferrers, WikiAccessRestrictions
917      */
918     function read()
919     {
920         return $this->logtable ? $this->read_sql() : $this->read_file();
921     }
922
923     /**
924      * Return iterator of referer items reverse sorted (latest first).
925      */
926     function get_referer($limit = 15, $external_only = false)
927     {
928         if ($external_only) { // see stdlin.php:isExternalReferrer()
929             $base = SERVER_URL;
930             $blen = strlen($base);
931         }
932         if (!empty($this->_dbi)) {
933             // check same hosts in referer and request and remove them
934             $ext_where = " AND LEFT(referer,$blen) <> " . $this->_dbi->quote($base)
935                 . " AND LEFT(referer,$blen) <> LEFT(CONCAT(" . $this->_dbi->quote(SERVER_URL) . ",request_uri),$blen)";
936             return $this->_read_sql_query("(referer <>'' AND NOT(ISNULL(referer)))"
937                 . ($external_only ? $ext_where : '')
938                 . " ORDER BY time_stamp DESC"
939                 . ($limit ? " LIMIT $limit" : ""));
940         } else {
941             $iter = new WikiDB_Array_generic_iter(0);
942             $logs =& $iter->_array;
943             while ($logentry = $this->read_file()) {
944                 if (!empty($logentry->referer)
945                     and (!$external_only or (substr($logentry->referer, 0, $blen) != $base))
946                 ) {
947                     $iter->_array[] = $logentry;
948                     if ($limit and count($logs) > $limit)
949                         array_shift($logs);
950                 }
951             }
952             $logs = array_reverse($logs);
953             $logs = array_slice($logs, 0, min($limit, count($logs)));
954             return $iter;
955         }
956     }
957
958     /**
959      * Read sequentially all previous entries from log file.
960      */
961     function read_file()
962     {
963         global $request;
964         if ($this->logfile) $this->logfile = ACCESS_LOG; // support Request_AccessLog::read
965
966         if (empty($this->reader)) // start at the beginning
967             $this->reader = fopen($this->logfile, "r");
968         if ($s = fgets($this->reader)) {
969             $entry = new Request_AccessLogEntry($this);
970             if (preg_match('/^(\S+)\s(\S+)\s(\S+)\s\[(.+?)\] "([^"]+)" (\d+) (\d+) "([^"]*)" "([^"]*)"$/', $s, $m)) {
971                 list(, $entry->host, $entry->ident, $entry->user, $entry->time,
972                     $entry->request, $entry->status, $entry->size,
973                     $entry->referer, $entry->user_agent) = $m;
974             }
975             return $entry;
976         } else { // until the end
977             fclose($this->reader);
978             return false;
979         }
980     }
981
982     function _read_sql_query($where = '')
983     {
984         $dbh =& $GLOBALS['request']->_dbi;
985         $log_tbl =& $this->logtable;
986         return $dbh->genericSqlIter("SELECT *,request_uri as request,request_time as time,remote_user as user,"
987             . "remote_host as host,agent as user_agent"
988             . " FROM $log_tbl"
989             . ($where ? " WHERE $where" : ""));
990     }
991
992     function read_sql($where = '')
993     {
994         if (empty($this->sqliter))
995             $this->sqliter = $this->_read_sql_query($where);
996         return $this->sqliter->next();
997     }
998
999     /* done in request->finish() before the db is closed */
1000     function write_sql()
1001     {
1002         $dbh =& $GLOBALS['request']->_dbi;
1003         if (isset($this->entries) and $dbh and $dbh->isOpen())
1004             foreach ($this->entries as $entry) {
1005                 $entry->write_sql();
1006             }
1007     }
1008
1009     /* done in the shutdown callback */
1010     function write_file()
1011     {
1012         if (isset($this->entries) and $this->logfile)
1013             foreach ($this->entries as $entry) {
1014                 $entry->write_file();
1015             }
1016         unset($this->entries);
1017     }
1018
1019     /* in an ideal world... */
1020     function write()
1021     {
1022         if ($this->logfile) $this->write_file();
1023         if ($this->logtable) $this->write_sql();
1024         unset($this->entries);
1025     }
1026 }
1027
1028 class Request_AccessLogEntry
1029 {
1030     /**
1031      * The log entry will be automatically appended to the log file or
1032      * SQL table when the current request terminates.
1033      *
1034      * If you want to modify a Request_AccessLogEntry before it gets
1035      * written (e.g. via the setStatus and setSize methods) you should
1036      * use an '&' on the constructor, so that you're working with the
1037      * original (rather than a copy) object.
1038      *
1039      * <pre>
1040      *    $log_entry = & new Request_AccessLogEntry("/tmp/wiki_access_log");
1041      *    $log_entry->setStatus(401);
1042      *    $log_entry->push($request);
1043      * </pre>
1044      *
1045      */
1046     function __construct(&$accesslog)
1047     {
1048         $this->_accesslog = $accesslog;
1049         $this->logfile = $accesslog->logfile;
1050         $this->time = time();
1051         $this->status = 200; // see setStatus()
1052         $this->size = 0; // see setSize()
1053     }
1054
1055     /**
1056      * @param $request object  Request object for current request.
1057      */
1058     function push(&$request)
1059     {
1060         $this->host = $request->get('REMOTE_HOST');
1061         $this->ident = $request->get('REMOTE_IDENT');
1062         if (!$this->ident)
1063             $this->ident = '-';
1064         $user = $request->getUser();
1065         if ($user->isAuthenticated())
1066             $this->user = $user->UserName();
1067         else
1068             $this->user = '-';
1069         $this->request = join(' ', array($request->get('REQUEST_METHOD'),
1070             $request->get('REQUEST_URI'),
1071             $request->get('SERVER_PROTOCOL')));
1072         $this->referer = (string)$request->get('HTTP_REFERER');
1073         $this->user_agent = (string)$request->get('HTTP_USER_AGENT');
1074     }
1075
1076     /**
1077      * Set result status code.
1078      *
1079      * @param $status integer  HTTP status code.
1080      */
1081     function setStatus($status)
1082     {
1083         $this->status = $status;
1084     }
1085
1086     /**
1087      * Set response size.
1088      *
1089      * @param $size integer
1090      */
1091     function setSize($size = 0)
1092     {
1093         $this->size = (int)$size;
1094     }
1095
1096     function setDuration($seconds)
1097     {
1098         // Pear DB does not correctly quote , in floats using ?. e.g. in european locales.
1099         // Workaround:
1100         $this->duration = strtr(sprintf("%f", $seconds), ",", ".");
1101     }
1102
1103     /**
1104      * Get time zone offset.
1105      *
1106      * This is a static member function.
1107      *
1108      * @param int $time Unix timestamp (defaults to current time).
1109      * @return string Zone offset, e.g. "-0800" for PST.
1110      */
1111     function _zone_offset($time = 0)
1112     {
1113         if (!$time)
1114             $time = time();
1115         $offset = date("Z", $time);
1116         $negoffset = "";
1117         if ($offset < 0) {
1118             $negoffset = "-";
1119             $offset = -$offset;
1120         }
1121         $offhours = floor($offset / 3600);
1122         $offmins = $offset / 60 - $offhours * 60;
1123         return sprintf("%s%02d%02d", $negoffset, $offhours, $offmins);
1124     }
1125
1126     /**
1127      * Format time in NCSA format.
1128      *
1129      * This is a static member function.
1130      *
1131      * @param int $time Unix timestamp (defaults to current time).
1132      * @return string Formatted date & time.
1133      */
1134     function _ncsa_time($time = 0)
1135     {
1136         if (!$time)
1137             $time = time();
1138         return date("d/M/Y:H:i:s", $time) .
1139             " " . $this->_zone_offset();
1140     }
1141
1142     function write()
1143     {
1144         if ($this->_accesslog->logfile) $this->write_file();
1145         if ($this->_accesslog->logtable) $this->write_sql();
1146     }
1147
1148     /**
1149      * Write entry to log file.
1150      */
1151     function write_file()
1152     {
1153         $entry = sprintf('%s %s %s [%s] "%s" %d %d "%s" "%s"',
1154             $this->host, $this->ident, $this->user,
1155             $this->_ncsa_time($this->time),
1156             $this->request, $this->status, $this->size,
1157             $this->referer, $this->user_agent);
1158         if (!empty($this->_accesslog->reader)) {
1159             fclose($this->_accesslog->reader);
1160             unset($this->_accesslog->reader);
1161         }
1162         //Error log doesn't provide locking.
1163         //error_log("$entry\n", 3, $this->logfile);
1164         // Alternate method
1165         if (($fp = fopen($this->logfile, "a"))) {
1166             flock($fp, LOCK_EX);
1167             fputs($fp, "$entry\n");
1168             fclose($fp);
1169         }
1170     }
1171
1172     /* This is better been done by apache mod_log_sql */
1173     /* If ACCESS_LOG_SQL & 2 we do write it by our own */
1174     function write_sql()
1175     {
1176         global $request;
1177
1178         $dbh =& $request->_dbi;
1179         if ($dbh and $dbh->isOpen() and $this->_accesslog->logtable) {
1180             //$log_tbl =& $this->_accesslog->logtable;
1181             if ($request->get('REQUEST_METHOD') == "POST") {
1182                 // strangely HTTP_POST_VARS doesn't contain all posted vars.
1183                 $args = $_POST; // copy not ref. clone not needed on hashes
1184                 // garble passwords
1185                 if (!empty($args['auth']['passwd'])) $args['auth']['passwd'] = '<not displayed>';
1186                 if (!empty($args['dbadmin']['passwd'])) $args['dbadmin']['passwd'] = '<not displayed>';
1187                 if (!empty($args['pref']['passwd'])) $args['pref']['passwd'] = '<not displayed>';
1188                 if (!empty($args['pref']['passwd2'])) $args['pref']['passwd2'] = '<not displayed>';
1189                 $this->request_args = substr(serialize($args), 0, 254); // if VARCHAR(255) is used.
1190             } else {
1191                 $this->request_args = $request->get('QUERY_STRING');
1192             }
1193             $this->request_method = $request->get('REQUEST_METHOD');
1194             $this->request_uri = $request->get('REQUEST_URI');
1195             // duration problem: sprintf "%f" might use comma e.g. "100,201" in european locales
1196             $dbh->_backend->write_accesslog($this);
1197         }
1198     }
1199 }
1200
1201 /**
1202  * Shutdown callback.
1203  *
1204  * @access private
1205  * @see Request_AccessLogEntry
1206  */
1207 function Request_AccessLogEntry_shutdown_function()
1208 {
1209     global $request;
1210
1211     if (isset($request->_accesslog->entries) and $request->_accesslog->logfile)
1212         foreach ($request->_accesslog->entries as $entry) {
1213             $entry->write_file();
1214         }
1215     unset($request->_accesslog->entries);
1216 }
1217
1218 class HTTP_ETag
1219 {
1220     function __construct($val, $is_weak = false)
1221     {
1222         $this->_val = wikihash($val);
1223         $this->_weak = $is_weak;
1224     }
1225
1226     /** Comparison
1227      *
1228      * Strong comparison: If either (or both) tag is weak, they
1229      *  are not equal.
1230      */
1231     function equals($that, $strong_match = false)
1232     {
1233         if ($this->_val != $that->_val)
1234             return false;
1235         if ($strong_match and ($this->_weak or $that->_weak))
1236             return false;
1237         return true;
1238     }
1239
1240     function asString()
1241     {
1242         $quoted = '"' . addslashes($this->_val) . '"';
1243         return $this->_weak ? "W/$quoted" : $quoted;
1244     }
1245
1246     /** Parse tag from header.
1247      *
1248      * This is a static member function.
1249      */
1250     function parse($strval)
1251     {
1252         if (!preg_match(':^(W/)?"(.+)"$:i', trim($strval), $m))
1253             return false; // parse failed
1254         list(, $weak, $str) = $m;
1255         return new HTTP_ETag(stripslashes($str), $weak);
1256     }
1257
1258     function matches($taglist, $strong_match = false)
1259     {
1260         $taglist = trim($taglist);
1261
1262         if ($taglist == '*') {
1263             if ($strong_match)
1264                 return !$this->_weak;
1265             else
1266                 return true;
1267         }
1268
1269         while (preg_match('@^(W/)?"((?:\\\\.|[^"])*)"\s*,?\s*@i',
1270             $taglist, $m)) {
1271             list($match, $weak, $str) = $m;
1272             $taglist = substr($taglist, strlen($match));
1273             $tag = new HTTP_ETag(stripslashes($str), $weak);
1274             if ($this->equals($tag, $strong_match)) {
1275                 return true;
1276             }
1277         }
1278         return false;
1279     }
1280 }
1281
1282 // Possible results from the HTTP_ValidatorSet::_check*() methods.
1283 // (Higher numerical values take precedence.)
1284 define ('_HTTP_VAL_PASS', 0); // Test is irrelevant
1285 define ('_HTTP_VAL_NOT_MODIFIED', 1); // Test passed, content not changed
1286 define ('_HTTP_VAL_MODIFIED', 2); // Test failed, content changed
1287 define ('_HTTP_VAL_FAILED', 3); // Precondition failed.
1288
1289 class HTTP_ValidatorSet
1290 {
1291     function __construct($validators)
1292     {
1293         $this->_mtime = $this->_weak = false;
1294         $this->_tag = array();
1295
1296         foreach ($validators as $key => $val) {
1297             if ($key == '%mtime') {
1298                 $this->_mtime = $val;
1299             } elseif ($key == '%weak') {
1300                 if ($val)
1301                     $this->_weak = true;
1302             } else {
1303                 $this->_tag[$key] = $val;
1304             }
1305         }
1306     }
1307
1308     function append($that)
1309     {
1310         if (is_array($that))
1311             $that = new HTTP_ValidatorSet($that);
1312
1313         // Pick the most recent mtime
1314         if (isset($that->_mtime))
1315             if (!isset($this->_mtime) || $that->_mtime > $this->_mtime)
1316                 $this->_mtime = $that->_mtime;
1317
1318         // If either is weak, we're weak
1319         if (!empty($that->_weak))
1320             $this->_weak = true;
1321         if (is_array($this->_tag))
1322             $this->_tag = array_merge($this->_tag, $that->_tag);
1323         else
1324             $this->_tag = $that->_tag;
1325     }
1326
1327     function getETag()
1328     {
1329         if (!$this->_tag)
1330             return false;
1331         return new HTTP_ETag($this->_tag, $this->_weak);
1332     }
1333
1334     function getModificationTime()
1335     {
1336         return $this->_mtime;
1337     }
1338
1339     function checkConditionalRequest(&$request)
1340     {
1341         $result = max($this->_checkIfUnmodifiedSince($request),
1342             $this->_checkIfModifiedSince($request),
1343             $this->_checkIfMatch($request),
1344             $this->_checkIfNoneMatch($request));
1345
1346         if ($result == _HTTP_VAL_PASS || $result == _HTTP_VAL_MODIFIED)
1347             return false; // "please proceed with normal processing"
1348         elseif ($result == _HTTP_VAL_FAILED)
1349             return 412; // "412 Precondition Failed"
1350         elseif ($result == _HTTP_VAL_NOT_MODIFIED)
1351             return 304; // "304 Not Modified"
1352
1353         trigger_error("Ack, shouldn't get here", E_USER_ERROR);
1354         return false;
1355     }
1356
1357     function _checkIfUnmodifiedSince(&$request)
1358     {
1359         if ($this->_mtime !== false) {
1360             $since = ParseRfc1123DateTime($request->get("HTTP_IF_UNMODIFIED_SINCE"));
1361             if ($since !== false && $this->_mtime > $since)
1362                 return _HTTP_VAL_FAILED;
1363         }
1364         return _HTTP_VAL_PASS;
1365     }
1366
1367     function _checkIfModifiedSince(&$request)
1368     {
1369         if ($this->_mtime !== false and $request->isGetOrHead()) {
1370             $since = ParseRfc1123DateTime($request->get("HTTP_IF_MODIFIED_SINCE"));
1371             if ($since !== false) {
1372                 if ($this->_mtime <= $since)
1373                     return _HTTP_VAL_NOT_MODIFIED;
1374                 return _HTTP_VAL_MODIFIED;
1375             }
1376         }
1377         return _HTTP_VAL_PASS;
1378     }
1379
1380     function _checkIfMatch(&$request)
1381     {
1382         if ($this->_tag && ($taglist = $request->get("HTTP_IF_MATCH"))) {
1383             $tag = $this->getETag();
1384             if (!$tag->matches($taglist, 'strong'))
1385                 return _HTTP_VAL_FAILED;
1386         }
1387         return _HTTP_VAL_PASS;
1388     }
1389
1390     function _checkIfNoneMatch(&$request)
1391     {
1392         if ($this->_tag && ($taglist = $request->get("HTTP_IF_NONE_MATCH"))) {
1393             $tag = $this->getETag();
1394             $strong_compare = !$request->isGetOrHead();
1395             if ($taglist) {
1396                 if ($tag->matches($taglist, $strong_compare)) {
1397                     if ($request->isGetOrHead())
1398                         return _HTTP_VAL_NOT_MODIFIED;
1399                     else
1400                         return _HTTP_VAL_FAILED;
1401                 }
1402                 return _HTTP_VAL_MODIFIED;
1403             }
1404         }
1405         return _HTTP_VAL_PASS;
1406     }
1407 }
1408
1409 // Local Variables:
1410 // mode: php
1411 // tab-width: 8
1412 // c-basic-offset: 4
1413 // c-hanging-comment-ender-p: nil
1414 // indent-tabs-mode: nil
1415 // End: