]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/Request.php
special support for formatted plugins (one-liners)
[SourceForge/phpwiki.git] / lib / Request.php
1 <?php // -*-php-*-
2 rcs_id('$Id: Request.php,v 1.50 2004-04-29 19:39:44 rurban Exp $');
3 /*
4  Copyright (C) 2002,2004 $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 // backward compatibility for PHP < 4.2.0
24 if (!function_exists('ob_clean')) {
25     function ob_clean() {
26         ob_end_clean();
27         ob_start();
28     }
29 }
30
31         
32 class Request {
33         
34     function Request() {
35         $this->_fix_magic_quotes_gpc();
36         $this->_fix_multipart_form_data();
37         
38         switch($this->get('REQUEST_METHOD')) {
39         case 'GET':
40         case 'HEAD':
41             $this->args = &$GLOBALS['HTTP_GET_VARS'];
42             break;
43         case 'POST':
44             $this->args = &$GLOBALS['HTTP_POST_VARS'];
45             break;
46         default:
47             $this->args = array();
48             break;
49         }
50         
51         $this->session = new Request_SessionVars; 
52         $this->cookies = new Request_CookieVars;
53         
54         if (ACCESS_LOG) {
55             if (! is_writeable(ACCESS_LOG)) {
56                 trigger_error
57                     (sprintf(_("%s is not writable."), _("The PhpWiki access log file"))
58                     . "\n"
59                     . sprintf(_("Please ensure that %s is writable, or redefine %s in index.php."),
60                             sprintf(_("the file '%s'"), ACCESS_LOG),
61                             'ACCESS_LOG')
62                     , E_USER_NOTICE);
63             }
64             else
65                 $this->_log_entry = & new Request_AccessLogEntry($this,
66                                                                 ACCESS_LOG);
67         }
68         
69         $GLOBALS['request'] = $this;
70     }
71
72     function get($key) {
73         if (!empty($GLOBALS['HTTP_SERVER_VARS']))
74             $vars = &$GLOBALS['HTTP_SERVER_VARS'];
75         else // cgi or other servers than Apache
76             $vars = &$GLOBALS['_ENV'];
77
78         if (isset($vars[$key]))
79             return $vars[$key];
80
81         switch ($key) {
82         case 'REMOTE_HOST':
83             $addr = $vars['REMOTE_ADDR'];
84             if (defined('ENABLE_REVERSE_DNS') && ENABLE_REVERSE_DNS)
85                 return $vars[$key] = gethostbyaddr($addr);
86             else
87                 return $addr;
88         default:
89             return false;
90         }
91     }
92
93     function getArg($key) {
94         if (isset($this->args[$key]))
95             return $this->args[$key];
96         return false;
97     }
98
99     function getArgs () {
100         return $this->args;
101     }
102     
103     function setArg($key, $val) {
104         if ($val === false)
105             unset($this->args[$key]);
106         else
107             $this->args[$key] = $val;
108     }
109     
110     // Well oh well. Do we really want to pass POST params back as GET?
111     function getURLtoSelf($args = false, $exclude = array()) {
112         $get_args = $this->args;
113         if ($args)
114             $get_args = array_merge($get_args, $args);
115
116         // Err... good point...
117         // sortby buttons
118         if ($this->isPost()) {
119             $exclude = array_merge($exclude, array('action','auth'));
120             //$get_args = $args; // or only the provided
121             /*
122             trigger_error("Request::getURLtoSelf() should probably not be from POST",
123                           E_USER_NOTICE);
124             */
125         }
126
127         foreach ($exclude as $ex) {
128             if (!empty($get_args[$ex])) unset($get_args[$ex]);
129         }
130
131         $pagename = $get_args['pagename'];
132         unset ($get_args['pagename']);
133         if (!empty($get_args['action']) and $get_args['action'] == 'browse')
134             unset($get_args['action']);
135
136         return WikiURL($pagename, $get_args);
137     }
138
139     function isPost () {
140         return $this->get("REQUEST_METHOD") == "POST";
141     }
142
143     function isGetOrHead () {
144         return in_array($this->get('REQUEST_METHOD'),
145                         array('GET', 'HEAD'));
146     }
147
148     function httpVersion() {
149         if (!preg_match('@HTTP\s*/\s*(\d+.\d+)@', $this->get('SERVER_PROTOCOL'), $m))
150             return false;
151         return (float) $m[1];
152     }
153     
154     function redirect($url, $noreturn=true) {
155         $bogus = defined('DISABLE_HTTP_REDIRECT') and DISABLE_HTTP_REDIRECT;
156         
157         if (!$bogus) {
158             header("Location: $url");
159             /*
160              * "302 Found" is not really meant to be sent in response
161              * to a POST.  Worse still, according to (both HTTP 1.0
162              * and 1.1) spec, the user, if it is sent, the user agent
163              * is supposed to use the same method to fetch the
164              * redirected URI as the original.
165              *
166              * That means if we redirect from a POST, the user-agent
167              * supposed to generate another POST.  Not what we want.
168              * (We do this after a page save after all.)
169              *
170              * Fortunately, most/all browsers don't do that.
171              *
172              * "303 See Other" is what we really want.  But it only
173              * exists in HTTP/1.1
174              *
175              * FIXME: this is still not spec compliant for HTTP
176              * version < 1.1.
177              */
178             $status = $this->httpVersion() >= 1.1 ? 303 : 302;
179
180             $this->setStatus($status);
181         }
182
183         if ($noreturn) {
184             include_once('lib/Template.php');
185             $this->discardOutput();
186             $tmpl = new Template('redirect', $this, array('REDIRECT_URL' => $url));
187             $tmpl->printXML();
188             $this->finish();
189         }
190         else if ($bogus) {
191             return JavaScript("
192               function redirect(url) {
193                 if (typeof location.replace == 'function')
194                   location.replace(url);
195                 else if (typeof location.assign == 'function')
196                   location.assign(url);
197                 else
198                   window.location = url;
199               }
200               redirect('" . addslashes($url) . "')");
201         }
202     }
203
204     /** Set validators for this response.
205      *
206      * This sets a (possibly incomplete) set of validators
207      * for this response.
208      *
209      * The validator set can be extended using appendValidators().
210      *
211      * When you're all done setting and appending validators, you
212      * must call checkValidators() to check them and set the
213      * appropriate headers in the HTTP response.
214      *
215      * Example Usage:
216      *  ...
217      *  $request->setValidators(array('pagename' => $pagename,
218      *                                '%mtime' => $rev->get('mtime')));
219      *  ...
220      *  // Wups... response content depends on $otherpage, too...
221      *  $request->appendValidators(array('otherpage' => $otherpagerev->getPageName(),
222      *                                   '%mtime' => $otherpagerev->get('mtime')));
223      *  ...
224      *  // After all validators have been set:
225      *  $request->checkValidators();
226      */
227     function setValidators($validator_set) {
228         if (is_array($validator_set))
229             $validator_set = new HTTP_ValidatorSet($validator_set);
230         $this->_validators = $validator_set;
231     }
232     
233     /** Append more validators for this response. 
234      *  i.e dependencies on other pages mtimes
235      *  now it may be called in init also to simplify client code.
236      */ 
237     function appendValidators($validator_set) {
238         if (!isset($this->_validators)) {
239             $this->setValidators($validator_set);
240             return;
241         }
242         $this->_validators->append($validator_set);
243     }
244     
245     /** Check validators and set headers in HTTP response
246      *
247      * This sets the appropriate "Last-Modified" and "ETag"
248      * headers in the HTTP response.
249      *
250      * Additionally, if the validators match any(all) conditional
251      * headers in the HTTP request, this method will not return, but
252      * instead will send "304 Not Modified" or "412 Precondition
253      * Failed" (as appropriate) back to the client.
254      */
255     function checkValidators() {
256         $validators = &$this->_validators;
257         
258         // Set validator headers
259         if (($etag = $validators->getETag()) !== false)
260             header("ETag: " . $etag->asString());
261         if (($mtime = $validators->getModificationTime()) !== false)
262             header("Last-Modified: " . Rfc1123DateTime($mtime));
263
264         // Set cache control headers
265         $this->cacheControl();
266
267         if (CACHE_CONTROL == 'NONE')
268             return;             // don't check conditionals...
269         
270         // Check conditional headers in request
271         $status = $validators->checkConditionalRequest($this);
272         if ($status) {
273             // Return short response due to failed conditionals
274             $this->setStatus($status);
275             print "\n\n";
276             $this->discardOutput();
277             $this->finish();
278             exit();
279         }
280     }
281
282     /** Set the cache control headers in the HTTP response.
283      */
284     function cacheControl($strategy=CACHE_CONTROL, $max_age=CACHE_CONTROL_MAX_AGE) {
285         if ($strategy == 'NONE') {
286             $cache_control = "no-cache";
287             $max_age = -20;
288         }
289         elseif ($strategy == 'ALLOW_STALE' && $max_age > 0) {
290             $cache_control = sprintf("max-age=%d", $max_age);
291         }
292         else {
293             $cache_control = "must-revalidate";
294             $max_age = -20;
295         }
296         header("Cache-Control: $cache_control");
297         header("Expires: " . Rfc1123DateTime(time() + $max_age));
298         header("Vary: Cookie"); // FIXME: add more here?
299     }
300     
301     function setStatus($status) {
302         if (preg_match('|^HTTP/.*?\s(\d+)|i', $status, $m)) {
303             header($status);
304             $status = $m[1];
305         }
306         else {
307             $status = (integer) $status;
308             $reason = array('200' => 'OK',
309                             '302' => 'Found',
310                             '303' => 'See Other',
311                             '304' => 'Not Modified',
312                             '400' => 'Bad Request',
313                             '401' => 'Unauthorized',
314                             '403' => 'Forbidden',
315                             '404' => 'Not Found',
316                             '412' => 'Precondition Failed');
317             // FIXME: is it always okay to send HTTP/1.1 here, even for older clients?
318             header(sprintf("HTTP/1.1 %d %s", $status, $reason[$status]));
319         }
320
321         if (isset($this->_log_entry))
322             $this->_log_entry->setStatus($status);
323     }
324
325     function buffer_output($compress = true) {
326         if (defined('COMPRESS_OUTPUT')) {
327             if (!COMPRESS_OUTPUT)
328                 $compress = false;
329         }
330         elseif (!function_exists('version_compare')
331                 || version_compare(phpversion(), '4.2.3', "<")) {
332             $compress = false;
333         }
334
335         // Should we compress even when apache_note is not available?
336         // sf.net bug #933183 and http://bugs.php.net/17557
337         if (!function_exists('ob_gzhandler') or !function_exists('apache_note'))
338             $compress = false;
339         
340         if ($compress) {
341             ob_start('ob_gzhandler');
342             /*
343              * Attempt to prevent Apache from doing the dreaded double-gzip.
344              *
345              * It would be better if we could detect when apache was going
346              * to zip for us, and then let it ... but I have yet to figure
347              * out how to do that.
348              */
349             if (function_exists('apache_note'))
350                 @apache_note('no-gzip', 1);
351         }
352         else {
353             // Now we alway buffer output.
354             // This is so we can set HTTP headers (e.g. for redirect)
355             // at any point.
356             // FIXME: change the name of this method.
357             ob_start();
358         }
359         $this->_is_buffering_output = true;
360     }
361
362     function discardOutput() {
363         if (!empty($this->_is_buffering_output))
364             ob_clean();
365         else
366             trigger_error("Not buffering output", E_USER_NOTICE);
367     }
368     
369     function finish() {
370         if (!empty($this->_is_buffering_output)) {
371             //header(sprintf("Content-Length: %d", ob_get_length()));
372             ob_end_flush();
373         }
374         exit;
375     }
376
377     function getSessionVar($key) {
378         return $this->session->get($key);
379     }
380     function setSessionVar($key, $val) {
381         return $this->session->set($key, $val);
382     }
383     function deleteSessionVar($key) {
384         return $this->session->delete($key);
385     }
386
387     function getCookieVar($key) {
388         return $this->cookies->get($key);
389     }
390     function setCookieVar($key, $val, $lifetime_in_days = false, $path = false) {
391         return $this->cookies->set($key, $val, $lifetime_in_days, $path);
392     }
393     function deleteCookieVar($key) {
394         return $this->cookies->delete($key);
395     }
396     
397     function getUploadedFile($key) {
398         return Request_UploadedFile::getUploadedFile($key);
399     }
400     
401
402     function _fix_magic_quotes_gpc() {
403         $needs_fix = array('HTTP_POST_VARS',
404                            'HTTP_GET_VARS',
405                            'HTTP_COOKIE_VARS',
406                            'HTTP_SERVER_VARS',
407                            'HTTP_POST_FILES');
408         
409         // Fix magic quotes.
410         if (get_magic_quotes_gpc()) {
411             foreach ($needs_fix as $vars)
412                 $this->_stripslashes($GLOBALS[$vars]);
413         }
414     }
415
416     function _stripslashes(&$var) {
417         if (is_array($var)) {
418             foreach ($var as $key => $val)
419                 $this->_stripslashes($var[$key]);
420         }
421         elseif (is_string($var))
422             $var = stripslashes($var);
423     }
424     
425     function _fix_multipart_form_data () {
426         if (preg_match('|^multipart/form-data|', $this->get('CONTENT_TYPE')))
427             $this->_strip_leading_nl($GLOBALS['HTTP_POST_VARS']);
428     }
429     
430     function _strip_leading_nl(&$var) {
431         if (is_array($var)) {
432             foreach ($var as $key => $val)
433                 $this->_strip_leading_nl($var[$key]);
434         }
435         elseif (is_string($var))
436             $var = preg_replace('|^\r?\n?|', '', $var);
437     }
438 }
439
440 class Request_SessionVars {
441     function Request_SessionVars() {
442         // Prevent cacheing problems with IE 5
443         session_cache_limiter('none');
444                                         
445         session_start();
446     }
447     
448     function get($key) {
449         $vars = &$GLOBALS['HTTP_SESSION_VARS'];
450         if (isset($vars[$key]))
451             return $vars[$key];
452         return false;
453     }
454     
455     function set($key, $val) {
456         $vars = &$GLOBALS['HTTP_SESSION_VARS'];
457         if ($key == 'wiki_user') {
458             $val->page   = $GLOBALS['request']->getArg('pagename');
459             $val->action = $GLOBALS['request']->getArg('action');
460         }
461         if (!function_usable('get_cfg_var') or get_cfg_var('register_globals')) {
462             // This is funky but necessary, at least in some PHP's
463             $GLOBALS[$key] = $val;
464         }
465         $vars[$key] = $val;
466         session_register($key);
467     }
468     
469     function delete($key) {
470         $vars = &$GLOBALS['HTTP_SESSION_VARS'];
471         if (!function_usable('ini_get') or ini_get('register_globals'))
472             unset($GLOBALS[$key]);
473         unset($vars[$key]);
474         session_unregister($key);
475     }
476 }
477
478 class Request_CookieVars {
479     
480     function get($key) {
481         $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
482         if (isset($vars[$key])) {
483             @$val = unserialize(base64_decode($vars[$key]));
484             if (!empty($val))
485                 return $val;
486             @$val = urldecode($vars[$key]);
487             if (!empty($val))
488                 return $val;
489         }
490         return false;
491     }
492
493     function get_old($key) {
494         $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
495         if (isset($vars[$key])) {
496             @$val = unserialize(base64_decode($vars[$key]));
497             if (!empty($val))
498                 return $val;
499             @$val = unserialize($vars[$key]);
500             if (!empty($val))
501                 return $val;
502             @$val = $vars[$key];
503             if (!empty($val))
504                 return $val;
505         }
506         return false;
507     }
508
509     function set($key, $val, $persist_days = false, $path = false) {
510         $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
511         if (is_numeric($persist_days)) {
512             $expires = time() + (24 * 3600) * $persist_days;
513         }
514         else {
515             $expires = 0;
516         }
517         if (is_array($val) or is_object($val))
518             $packedval = base64_encode(serialize($val));
519         else
520             $packedval = urlencode($val);
521         $vars[$key] = $packedval;
522         if ($path)
523             setcookie($key, $packedval, $expires, $path);
524         else
525             setcookie($key, $packedval, $expires);
526     }
527     
528     function delete($key) {
529         static $deleted = array();
530         if (isset($deleted[$key])) return;
531         $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
532         setcookie($key,'',0);
533         setcookie($key,'',0,defined('COOKIE_DOMAIN') ? COOKIE_DOMAIN : '/');
534         unset($vars[$key]);
535         unset($GLOBALS['HTTP_COOKIE_VARS'][$key]);
536         $deleted[$key] = 1;
537     }
538 }
539
540 /* Win32 Note:
541    [\winnt\php.ini]
542    You must set "upload_tmp_dir" = "/tmp/" or "C:/tmp/"
543    Best on the same drive as apache, with forward slashes 
544    and with ending slash!
545    Otherwise "\\" => "" and the uploaded file will not be found.
546 */
547 class Request_UploadedFile {
548     function getUploadedFile($postname) {
549         global $HTTP_POST_FILES;
550         
551         if (!isset($HTTP_POST_FILES[$postname]))
552             return false;
553         
554         $fileinfo = &$HTTP_POST_FILES[$postname];
555         if ($fileinfo['error']) {
556             trigger_error("Upload error: #" . $fileinfo['error'],
557                           E_USER_ERROR);
558             return false;
559         }
560
561         // With windows/php 4.2.1 is_uploaded_file() always returns false.
562         if (!is_uploaded_file($fileinfo['tmp_name'])) {
563             if (isWindows()) {
564                 if (!$tmp_file = get_cfg_var('upload_tmp_dir')) {
565                     $tmp_file = dirname(tempnam('', ''));
566                 }
567                 $tmp_file .= '/' . basename($fileinfo['tmp_name']);
568                 /* but ending slash in php.ini upload_tmp_dir is required. */
569                 if (ereg_replace('/+', '/', $tmp_file) != $fileinfo['tmp_name']) {
570                     trigger_error(sprintf("Uploaded tmpfile illegal: %s != %s",$tmp_file, $fileinfo['tmp_name']),
571                                   E_USER_ERROR);
572                     return false;
573                 } else {
574                     trigger_error(sprintf("Workaround for PHP/Windows is_uploaded_file() problem for %s.",
575                                           $fileinfo['tmp_name'])."\n".
576                                   "Probably illegal TEMP environment setting.",E_USER_NOTICE);
577                 }
578             } else {
579               trigger_error(sprintf("Uploaded tmpfile %s not found.",$fileinfo['tmp_name'])."\n".
580                            " Probably illegal TEMP environment setting.",
581                           E_USER_WARNING);
582             }
583         }
584         return new Request_UploadedFile($fileinfo);
585     }
586     
587     function Request_UploadedFile($fileinfo) {
588         $this->_info = $fileinfo;
589     }
590
591     function getSize() {
592         return $this->_info['size'];
593     }
594
595     function getName() {
596         return $this->_info['name'];
597     }
598
599     function getType() {
600         return $this->_info['type'];
601     }
602
603     function getTmpName() {
604         return $this->_info['tmp_name'];
605     }
606
607     function open() {
608         if ( ($fd = fopen($this->_info['tmp_name'], "rb")) ) {
609             if ($this->getSize() < filesize($this->_info['tmp_name'])) {
610                 // FIXME: Some PHP's (or is it some browsers?) put
611                 //    HTTP/MIME headers in the file body, some don't.
612                 //
613                 // At least, I think that's the case.  I know I used
614                 // to need this code, now I don't.
615                 //
616                 // This code is more-or-less untested currently.
617                 //
618                 // Dump HTTP headers.
619                 while ( ($header = fgets($fd, 4096)) ) {
620                     if (trim($header) == '') {
621                         break;
622                     }
623                     else if (!preg_match('/^content-(length|type):/i', $header)) {
624                         rewind($fd);
625                         break;
626                     }
627                 }
628             }
629         }
630         return $fd;
631     }
632
633     function getContents() {
634         $fd = $this->open();
635         $data = fread($fd, $this->getSize());
636         fclose($fd);
637         return $data;
638     }
639 }
640
641 /**
642  * Create NCSA "combined" log entry for current request.
643  */
644 class Request_AccessLogEntry
645 {
646     /**
647      * Constructor.
648      *
649      * The log entry will be automatically appended to the log file
650      * when the current request terminates.
651      *
652      * If you want to modify a Request_AccessLogEntry before it gets
653      * written (e.g. via the setStatus and setSize methods) you should
654      * use an '&' on the constructor, so that you're working with the
655      * original (rather than a copy) object.
656      *
657      * <pre>
658      *    $log_entry = & new Request_AccessLogEntry($req, "/tmp/wiki_access_log");
659      *    $log_entry->setStatus(401);
660      * </pre>
661      *
662      *
663      * @param $request object  Request object for current request.
664      * @param $logfile string  Log file name.
665      */
666     function Request_AccessLogEntry (&$request, $logfile) {
667         $this->logfile = $logfile;
668         
669         $this->host  = $request->get('REMOTE_HOST');
670         $this->ident = $request->get('REMOTE_IDENT');
671         if (!$this->ident)
672             $this->ident = '-';
673         $this->user = '-';        // FIXME: get logged-in user name
674         $this->time = time();
675         $this->request = join(' ', array($request->get('REQUEST_METHOD'),
676                                          $request->get('REQUEST_URI'),
677                                          $request->get('SERVER_PROTOCOL')));
678         $this->status = 200;
679         $this->size = 0;
680         $this->referer = (string) $request->get('HTTP_REFERER');
681         $this->user_agent = (string) $request->get('HTTP_USER_AGENT');
682
683         global $Request_AccessLogEntry_entries;
684         if (!isset($Request_AccessLogEntry_entries)) {
685             register_shutdown_function("Request_AccessLogEntry_shutdown_function");
686         }
687         $Request_AccessLogEntry_entries[] = &$this;
688     }
689
690     /**
691      * Set result status code.
692      *
693      * @param $status integer  HTTP status code.
694      */
695     function setStatus ($status) {
696         $this->status = $status;
697     }
698     
699     /**
700      * Set response size.
701      *
702      * @param $size integer
703      */
704     function setSize ($size) {
705         $this->size = $size;
706     }
707     
708     /**
709      * Get time zone offset.
710      *
711      * This is a static member function.
712      *
713      * @param $time integer Unix timestamp (defaults to current time).
714      * @return string Zone offset, e.g. "-0800" for PST.
715      */
716     function _zone_offset ($time = false) {
717         if (!$time)
718             $time = time();
719         $offset = date("Z", $time);
720         $negoffset = "";
721         if ($offset < 0) {
722             $negoffset = "-";
723             $offset = -$offset;
724         }
725         $offhours = floor($offset / 3600);
726         $offmins  = $offset / 60 - $offhours * 60;
727         return sprintf("%s%02d%02d", $negoffset, $offhours, $offmins);
728     }
729
730     /**
731      * Format time in NCSA format.
732      *
733      * This is a static member function.
734      *
735      * @param $time integer Unix timestamp (defaults to current time).
736      * @return string Formatted date & time.
737      */
738     function _ncsa_time($time = false) {
739         if (!$time)
740             $time = time();
741
742         return date("d/M/Y:H:i:s", $time) .
743             " " . $this->_zone_offset();
744     }
745
746     /**
747      * Write entry to log file.
748      */
749     function write() {
750         $entry = sprintf('%s %s %s [%s] "%s" %d %d "%s" "%s"',
751                          $this->host, $this->ident, $this->user,
752                          $this->_ncsa_time($this->time),
753                          $this->request, $this->status, $this->size,
754                          $this->referer, $this->user_agent);
755
756         //Error log doesn't provide locking.
757         //error_log("$entry\n", 3, $this->logfile);
758
759         // Alternate method
760         if (($fp = fopen($this->logfile, "a"))) {
761             flock($fp, LOCK_EX);
762             fputs($fp, "$entry\n");
763             fclose($fp);
764         }
765     }
766 }
767
768 /**
769  * Shutdown callback.
770  *
771  * @access private
772  * @see Request_AccessLogEntry
773  */
774 function Request_AccessLogEntry_shutdown_function ()
775 {
776     global $Request_AccessLogEntry_entries;
777     
778     foreach ($Request_AccessLogEntry_entries as $entry) {
779         $entry->write();
780     }
781     unset($Request_AccessLogEntry_entries);
782 }
783
784
785 class HTTP_ETag {
786     function HTTP_ETag($val, $is_weak=false) {
787         $this->_val = hash($val);
788         $this->_weak = $is_weak;
789     }
790
791     /** Comparison
792      *
793      * Strong comparison: If either (or both) tag is weak, they
794      *  are not equal.
795      */
796     function equals($that, $strong_match=false) {
797         if ($this->_val != $that->_val)
798             return false;
799         if ($strong_match and ($this->_weak or $that->_weak))
800             return false;
801         return true;
802     }
803
804
805     function asString() {
806         $quoted = '"' . addslashes($this->_val) . '"';
807         return $this->_weak ? "W/$quoted" : $quoted;
808     }
809
810     /** Parse tag from header.
811      *
812      * This is a static member function.
813      */
814     function parse($strval) {
815         if (!preg_match(':^(W/)?"(.+)"$:i', trim($strval), $m))
816             return false;       // parse failed
817         list(,$weak,$str) = $m;
818         return new HTTP_ETag(stripslashes($str), $weak);
819     }
820
821     function matches($taglist, $strong_match=false) {
822         $taglist = trim($taglist);
823
824         if ($taglist == '*') {
825             if ($strong_match)
826                 return ! $this->_weak;
827             else
828                 return true;
829         }
830
831         while (preg_match('@^(W/)?"((?:\\\\.|[^"])*)"\s*,?\s*@i',
832                           $taglist, $m)) {
833             list($match, $weak, $str) = $m;
834             $taglist = substr($taglist, strlen($match));
835             $tag = new HTTP_ETag(stripslashes($str), $weak);
836             if ($this->equals($tag, $strong_match)) {
837                 return true;
838             }
839         }
840         return false;
841     }
842 }
843
844 // Possible results from the HTTP_ValidatorSet::_check*() methods.
845 // (Higher numerical values take precedence.)
846 define ('_HTTP_VAL_PASS', 0);   // Test is irrelevant
847 define ('_HTTP_VAL_NOT_MODIFIED', 1); // Test passed, content not changed
848 define ('_HTTP_VAL_MODIFIED', 2); // Test failed, content changed
849 define ('_HTTP_VAL_FAILED', 3); // Precondition failed.
850
851 class HTTP_ValidatorSet {
852     function HTTP_ValidatorSet($validators) {
853         $this->_mtime = $this->_weak = false;
854         $this->_tag = array();
855         
856         foreach ($validators as $key => $val) {
857             if ($key == '%mtime') {
858                 $this->_mtime = $val;
859             }
860             elseif ($key == '%weak') {
861                 if ($val)
862                     $this->_weak = true;
863             }
864             else {
865                 $this->_tag[$key] = $val;
866             }
867         }
868     }
869
870     function append($that) {
871         if (is_array($that))
872             $that = new HTTP_ValidatorSet($that);
873
874         // Pick the most recent mtime
875         if (isset($that->_mtime))
876             if (!isset($this->_mtime) || $that->_mtime > $this->_mtime)
877                 $this->_mtime = $that->_mtime;
878
879         // If either is weak, we're weak
880         if (!empty($that->_weak))
881             $this->_weak = true;
882
883         $this->_tag = array_merge($this->_tag, $that->_tag);
884     }
885
886     function getETag() {
887         if (! $this->_tag)
888             return false;
889         return new HTTP_ETag($this->_tag, $this->_weak);
890     }
891
892     function getModificationTime() {
893         return $this->_mtime;
894     }
895     
896     function checkConditionalRequest (&$request) {
897         $result = max($this->_checkIfUnmodifiedSince($request),
898                       $this->_checkIfModifiedSince($request),
899                       $this->_checkIfMatch($request),
900                       $this->_checkIfNoneMatch($request));
901
902         if ($result == _HTTP_VAL_PASS || $result == _HTTP_VAL_MODIFIED)
903             return false;       // "please proceed with normal processing"
904         elseif ($result == _HTTP_VAL_FAILED)
905             return 412;         // "412 Precondition Failed"
906         elseif ($result == _HTTP_VAL_NOT_MODIFIED)
907             return 304;         // "304 Not Modified"
908
909         trigger_error("Ack, shouldn't get here", E_USER_ERROR);
910         return false;
911     }
912
913     function _checkIfUnmodifiedSince(&$request) {
914         if ($this->_mtime !== false) {
915             $since = ParseRfc1123DateTime($request->get("HTTP_IF_UNMODIFIED_SINCE"));
916             if ($since !== false && $this->_mtime > $since)
917                 return _HTTP_VAL_FAILED;
918         }
919         return _HTTP_VAL_PASS;
920     }
921
922     function _checkIfModifiedSince(&$request) {
923         if ($this->_mtime !== false and $request->isGetOrHead()) {
924             $since = ParseRfc1123DateTime($request->get("HTTP_IF_MODIFIED_SINCE"));
925             if ($since !== false) {
926                 if ($this->_mtime <= $since)
927                     return _HTTP_VAL_NOT_MODIFIED;
928                 return _HTTP_VAL_MODIFIED;
929             }
930         }
931         return _HTTP_VAL_PASS;
932     }
933
934     function _checkIfMatch(&$request) {
935         if ($this->_tag && ($taglist = $request->get("HTTP_IF_MATCH"))) {
936             $tag = $this->getETag();
937             if (!$tag->matches($taglist, 'strong'))
938                 return _HTTP_VAL_FAILED;
939         }
940         return _HTTP_VAL_PASS;
941     }
942
943     function _checkIfNoneMatch(&$request) {
944         if ($this->_tag && ($taglist = $request->get("HTTP_IF_NONE_MATCH"))) {
945             $tag = $this->getETag();
946             $strong_compare = ! $request->isGetOrHead();
947             if ($taglist) {
948                 if ($tag->matches($taglist, $strong_compare)) {
949                     if ($request->isGetOrHead())
950                         return _HTTP_VAL_NOT_MODIFIED;
951                     else
952                         return _HTTP_VAL_FAILED;
953                 }
954                 return _HTTP_VAL_MODIFIED;
955             }
956         }
957         return _HTTP_VAL_PASS;
958     }
959 }
960
961
962 // $Log: not supported by cvs2svn $
963 // Revision 1.49  2004/04/26 20:44:34  rurban
964 // locking table specific for better databases
965 //
966 // Revision 1.48  2004/04/13 09:13:50  rurban
967 // sf.net bug #933183 and http://bugs.php.net/17557
968 // disable ob_gzhandler if apache_note cannot be used.
969 //   (conservative until we find why)
970 //
971 // Revision 1.47  2004/04/02 15:06:55  rurban
972 // fixed a nasty ADODB_mysql session update bug
973 // improved UserPreferences layout (tabled hints)
974 // fixed UserPreferences auth handling
975 // improved auth stability
976 // improved old cookie handling: fixed deletion of old cookies with paths
977 //
978 // Revision 1.46  2004/03/30 02:14:03  rurban
979 // fixed yet another Prefs bug
980 // added generic PearDb_iter
981 // $request->appendValidators no so strict as before
982 // added some box plugin methods
983 // PageList commalist for condensed output
984 //
985 // Revision 1.45  2004/03/24 19:39:02  rurban
986 // php5 workaround code (plus some interim debugging code in XmlElement)
987 //   php5 doesn't work yet with the current XmlElement class constructors,
988 //   WikiUserNew does work better than php4.
989 // rewrote WikiUserNew user upgrading to ease php5 update
990 // fixed pref handling in WikiUserNew
991 // added Email Notification
992 // added simple Email verification
993 // removed emailVerify userpref subclass: just a email property
994 // changed pref binary storage layout: numarray => hash of non default values
995 // print optimize message only if really done.
996 // forced new cookie policy: delete pref cookies, use only WIKI_ID as plain string.
997 //   prefs should be stored in db or homepage, besides the current session.
998 //
999 // Revision 1.44  2004/03/14 16:26:22  rurban
1000 // copyright line
1001 //
1002 // Revision 1.43  2004/03/12 20:59:17  rurban
1003 // important cookie fix by Konstantin Zadorozhny
1004 // new editpage feature: JS_SEARCHREPLACE
1005 //
1006 // Revision 1.42  2004/03/10 15:38:48  rurban
1007 // store current user->page and ->action in session for WhoIsOnline
1008 // better WhoIsOnline icon
1009 // fixed WhoIsOnline warnings
1010 //
1011 // Revision 1.41  2004/02/27 01:25:14  rurban
1012 // Workarounds for upload handling
1013 //
1014 // Revision 1.40  2004/02/26 01:39:51  rurban
1015 // safer code
1016 //
1017 // Revision 1.39  2004/02/24 15:14:57  rurban
1018 // fixed action=upload problems on Win32, and remove Merge Edit buttons: file does not exist anymore
1019 //
1020 // Revision 1.38  2004/01/25 10:26:02  rurban
1021 // fixed bug [ 541193 ] HTTP_SERVER_VARS are Apache specific
1022 // http://sourceforge.net/tracker/index.php?func=detail&aid=541193&group_id=6121&atid=106121
1023 // CGI and other servers than apache populate _ENV and not _SERVER
1024 //
1025 // Revision 1.37  2003/12/26 06:41:16  carstenklapp
1026 // Bugfix: Try to defer OS errors about session.save_path and ACCESS_LOG,
1027 // so they don't prevent IE from partially (or not at all) rendering the
1028 // page. This should help a little for the IE user who encounters trouble
1029 // when setting up a new PhpWiki for the first time.
1030 //
1031
1032 // Local Variables:
1033 // mode: php
1034 // tab-width: 8
1035 // c-basic-offset: 4
1036 // c-hanging-comment-ender-p: nil
1037 // indent-tabs-mode: nil
1038 // End:   
1039 ?>