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