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