]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/Request.php
upload errmsgs by Shilad Sen.
[SourceForge/phpwiki.git] / lib / Request.php
1 <?php // -*-php-*-
2 rcs_id('$Id: Request.php,v 1.69 2004-10-21 19:00:37 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 config/config.ini."),
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['HTTP_ENV_VARS'];
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 == 'NO_CACHE')
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 == 'NO_CACHE') {
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         // USECACHE = false turns off ob buffering also for now. (sf.net)
327         if (defined('USECACHE') and !USECACHE) {
328             $this->_is_buffering_output = false;
329             return;
330         }
331         if (defined('COMPRESS_OUTPUT')) {
332             if (!COMPRESS_OUTPUT)
333                 $compress = false;
334         }
335         elseif (!check_php_version(4,2,3))
336             $compress = false;
337         elseif (isCGI()) // necessary?
338             $compress = false;
339             
340         if ($GLOBALS['request']->getArg('start_debug'))
341             $compress = false;
342         // Should we compress even when apache_note is not available?
343         // sf.net bug #933183 and http://bugs.php.net/17557
344         // This effectively eliminates CGI, but all other servers also. hmm.
345         if ($compress 
346             and (!function_exists('ob_gzhandler') 
347                  or !function_exists('apache_note'))) 
348             $compress = false;
349
350         // New: we check for the client Accept-Encoding: "gzip" presence also
351         // This should eliminate a lot or reported problems.
352         if ($compress
353             and (!$this->get("HTTP_ACCEPT_ENCODING")
354                  or !strstr($this->get("HTTP_ACCEPT_ENCODING"), "gzip")))
355             $compress = false;
356
357         // Most RSS clients are NOT(!) application/xml gzip compatible yet. 
358         // Even if they are sending the accept-encoding gzip header!
359         // wget is, Mozilla, and MSIE no.
360         // Of the RSS readers only MagpieRSS 0.5.2 is. http://www.rssgov.com/rssparsers.html
361         // See also http://phpwiki.sourceforge.net/phpwiki/KnownBugs
362         if ($compress 
363             and $this->getArg('format') 
364             and strstr($this->getArg('format'), 'rss'))
365             $compress = false;
366
367         if ($compress) {
368             ob_start('ob_gzhandler');
369             /*
370              * Attempt to prevent Apache from doing the dreaded double-gzip.
371              *
372              * It would be better if we could detect when apache was going
373              * to zip for us, and then let it ... but I have yet to figure
374              * out how to do that.
375              */
376             if (function_exists('apache_note'))
377                 @apache_note('no-gzip', 1);
378         }
379         else {
380             // Now we alway buffer output.
381             // This is so we can set HTTP headers (e.g. for redirect)
382             // at any point.
383             // FIXME: change the name of this method.
384             ob_start();
385         }
386         $this->_is_buffering_output = true;
387         $this->_ob_get_length = 0;
388     }
389
390     function discardOutput() {
391         if (!empty($this->_is_buffering_output)) {
392             ob_clean();
393             $this->_is_buffering_output = false;
394         } else {
395             trigger_error("Not buffering output", E_USER_NOTICE);
396         }
397     }
398
399     /** 
400      * Longer texts need too much memory on tiny or memory-limit=8MB systems.
401      * We might want to flush our buffer and restart again.
402      * (This would be fine if php would release its memory)
403      * Note that this must not be called inside Template expansion or other 
404      * sections with ob_buffering.
405      */
406     function chunkOutput() {
407         if (!empty($this->_is_buffering_output)) {
408             $this->_do_chunked_output = true;
409             $this->_ob_get_length += ob_get_length();
410             while (@ob_end_flush());
411             ob_end_clean();
412             ob_start();
413         }
414     }
415
416     function finish() {
417         session_write_close();
418         if (!empty($this->_is_buffering_output)) {
419             /* This cannot work because it might destroy xml markup */
420             /*
421             if (0 and $GLOBALS['SearchHighLightQuery'] and check_php_version(4,2)) {
422                 $html = str_replace($GLOBALS['SearchHighLightQuery'],
423                                     '<span class="search-term">'.$GLOBALS['SearchHighLightQuery'].'</span>',
424                                     ob_get_contents());
425                 ob_clean();
426                 header(sprintf("Content-Length: %d", strlen($html)));
427                 echo $html;
428             } else {
429             */
430             if (empty($this->_do_chunked_output)) {
431                 header(sprintf("Content-Length: %d", ob_get_length()));
432             } else {
433                 header(sprintf("Content-Length: %d", $this->ob_get_length));
434             }
435             //}
436             while (@ob_end_flush());
437             $this->_is_buffering_output = false;
438         }
439         exit;
440     }
441
442     function getSessionVar($key) {
443         return $this->session->get($key);
444     }
445     function setSessionVar($key, $val) {
446         return $this->session->set($key, $val);
447     }
448     function deleteSessionVar($key) {
449         return $this->session->delete($key);
450     }
451
452     function getCookieVar($key) {
453         return $this->cookies->get($key);
454     }
455     function setCookieVar($key, $val, $lifetime_in_days = false, $path = false) {
456         return $this->cookies->set($key, $val, $lifetime_in_days, $path);
457     }
458     function deleteCookieVar($key) {
459         return $this->cookies->delete($key);
460     }
461     
462     function getUploadedFile($key) {
463         return Request_UploadedFile::getUploadedFile($key);
464     }
465     
466
467     function _fix_magic_quotes_gpc() {
468         $needs_fix = array('HTTP_POST_VARS',
469                            'HTTP_GET_VARS',
470                            'HTTP_COOKIE_VARS',
471                            'HTTP_SERVER_VARS',
472                            'HTTP_POST_FILES');
473         
474         // Fix magic quotes.
475         if (get_magic_quotes_gpc()) {
476             foreach ($needs_fix as $vars)
477                 $this->_stripslashes($GLOBALS[$vars]);
478         }
479     }
480
481     function _stripslashes(&$var) {
482         if (is_array($var)) {
483             foreach ($var as $key => $val)
484                 $this->_stripslashes($var[$key]);
485         }
486         elseif (is_string($var))
487             $var = stripslashes($var);
488     }
489     
490     function _fix_multipart_form_data () {
491         if (preg_match('|^multipart/form-data|', $this->get('CONTENT_TYPE')))
492             $this->_strip_leading_nl($GLOBALS['HTTP_POST_VARS']);
493     }
494     
495     function _strip_leading_nl(&$var) {
496         if (is_array($var)) {
497             foreach ($var as $key => $val)
498                 $this->_strip_leading_nl($var[$key]);
499         }
500         elseif (is_string($var))
501             $var = preg_replace('|^\r?\n?|', '', $var);
502     }
503 }
504
505 class Request_SessionVars {
506     function Request_SessionVars() {
507         // Prevent cacheing problems with IE 5
508         session_cache_limiter('none');
509                                         
510         session_start();
511     }
512     
513     function get($key) {
514         $vars = &$GLOBALS['HTTP_SESSION_VARS'];
515         if (isset($vars[$key]))
516             return $vars[$key];
517         return false;
518     }
519     
520     function set($key, $val) {
521         $vars = &$GLOBALS['HTTP_SESSION_VARS'];
522         if ($key == 'wiki_user') {
523             if (DEBUG) {
524               if (!$val) {
525                 trigger_error("delete user session", E_USER_WARNING);
526               } elseif (!isset($val->_level)) {
527                   trigger_error("lost level in session", E_USER_WARNING);
528               }
529             }
530             if (is_object($val)) {
531                 $val->page   = $GLOBALS['request']->getArg('pagename');
532                 $val->action = $GLOBALS['request']->getArg('action');
533                 // sessiondata may not exceed a certain size!
534                 // otherwise it will get lost.
535                 unset($val->_HomePagehandle);
536                 unset($val->_auth_dbi);
537                 unset($val->_HomePagehandle);
538                 if (isset($val->_group)) {
539                     unset($val->_group->request);
540                     unset($val->_group->user);
541                 }
542             }
543         }
544         if (!function_usable('get_cfg_var') or get_cfg_var('register_globals')) {
545             // This is funky but necessary, at least in some PHP's
546             $GLOBALS[$key] = $val;
547         }
548         $vars[$key] = $val;
549         if (isset($_SESSION))
550             $_SESSION[$key] = $val;
551         session_register($key);
552     }
553     
554     function delete($key) {
555         $vars = &$GLOBALS['HTTP_SESSION_VARS'];
556         if (!function_usable('ini_get') or ini_get('register_globals'))
557             unset($GLOBALS[$key]);
558         if (DEBUG) trigger_error("delete session $key",E_USER_WARNING);
559         unset($vars[$key]);
560         session_unregister($key);
561     }
562 }
563
564 class Request_CookieVars {
565     
566     function get($key) {
567         $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
568         if (isset($vars[$key])) {
569             @$val = unserialize(base64_decode($vars[$key]));
570             if (!empty($val))
571                 return $val;
572             @$val = urldecode($vars[$key]);
573             if (!empty($val))
574                 return $val;
575         }
576         return false;
577     }
578
579     function get_old($key) {
580         $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
581         if (isset($vars[$key])) {
582             @$val = unserialize(base64_decode($vars[$key]));
583             if (!empty($val))
584                 return $val;
585             @$val = unserialize($vars[$key]);
586             if (!empty($val))
587                 return $val;
588             @$val = $vars[$key];
589             if (!empty($val))
590                 return $val;
591         }
592         return false;
593     }
594
595     function set($key, $val, $persist_days = false, $path = false) {
596         // if already defined, ignore
597         if (defined('MAIN_setUser') and $key = 'WIKI_ID') return;
598         $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
599         if (is_numeric($persist_days)) {
600             $expires = time() + (24 * 3600) * $persist_days;
601         }
602         else {
603             $expires = 0;
604         }
605         if (is_array($val) or is_object($val))
606             $packedval = base64_encode(serialize($val));
607         else
608             $packedval = urlencode($val);
609         $vars[$key] = $packedval;
610         if ($path)
611             @setcookie($key, $packedval, $expires, $path);
612         else
613             @setcookie($key, $packedval, $expires);
614     }
615     
616     function delete($key) {
617         static $deleted = array();
618         if (isset($deleted[$key])) return;
619         $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
620         @setcookie($key,'',0);
621         @setcookie($key,'',0,defined('COOKIE_DOMAIN') ? COOKIE_DOMAIN : '/');
622         unset($vars[$key]);
623         unset($GLOBALS['HTTP_COOKIE_VARS'][$key]);
624         $deleted[$key] = 1;
625     }
626 }
627
628 /* Win32 Note:
629    [\winnt\php.ini]
630    You must set "upload_tmp_dir" = "/tmp/" or "C:/tmp/"
631    Best on the same drive as apache, with forward slashes 
632    and with ending slash!
633    Otherwise "\\" => "" and the uploaded file will not be found.
634 */
635 class Request_UploadedFile {
636     function getUploadedFile($postname) {
637         global $HTTP_POST_FILES;
638         
639         if (!isset($HTTP_POST_FILES[$postname]))
640             return false;
641         
642         $fileinfo = &$HTTP_POST_FILES[$postname];
643         if ($fileinfo['error']) {
644             // errmsgs by Shilad Sen
645             switch ($HTTP_POST_FILES['userfile']['error']) {
646             case 1:
647                 trigger_error(_("Upload error: file too big"), E_USER_ERROR);
648                 break;
649             case 2:
650                 trigger_error(_("Upload error: file too big"), E_USER_ERROR);
651                 break;
652             case 3:
653                 trigger_error(_("Upload error: file only partially recieved"), E_USER_ERROR);
654                 break;
655             case 4:
656                 trigger_error(_("Upload error: no file selected"), E_USER_ERROR);
657                 break;
658             default:
659                 trigger_error(_("Upload error: unknown error #") . $fileinfo['error'], E_USER_ERROR);
660                 break;
661             }
662             return false;
663         }
664
665         // With windows/php 4.2.1 is_uploaded_file() always returns false.
666         // Be sure that upload_tmp_dir ends with a slash!
667         if (!is_uploaded_file($fileinfo['tmp_name'])) {
668             if (isWindows()) {
669                 if (!$tmp_file = get_cfg_var('upload_tmp_dir')) {
670                     $tmp_file = dirname(tempnam('', ''));
671                 }
672                 $tmp_file .= '/' . basename($fileinfo['tmp_name']);
673                 /* but ending slash in php.ini upload_tmp_dir is required. */
674                 if (ereg_replace('/+', '/', $tmp_file) != $fileinfo['tmp_name']) {
675                     trigger_error(sprintf("Uploaded tmpfile illegal: %s != %s.",$tmp_file, $fileinfo['tmp_name']).
676                                   "\n".
677                                   "Probably illegal TEMP environment or upload_tmp_dir setting.",
678                                   E_USER_ERROR);
679                     return false;
680                 } else {
681                     /*
682                     trigger_error(sprintf("Workaround for PHP/Windows is_uploaded_file() problem for %s.",
683                                           $fileinfo['tmp_name'])."\n".
684                                   "Probably illegal TEMP environment or upload_tmp_dir setting.", 
685                                   E_USER_NOTICE);
686                     */
687                     ;
688                 }
689             } else {
690               trigger_error(sprintf("Uploaded tmpfile %s not found.",$fileinfo['tmp_name'])."\n".
691                            " Probably illegal TEMP environment or upload_tmp_dir setting.",
692                           E_USER_WARNING);
693             }
694         }
695         return new Request_UploadedFile($fileinfo);
696     }
697     
698     function Request_UploadedFile($fileinfo) {
699         $this->_info = $fileinfo;
700     }
701
702     function getSize() {
703         return $this->_info['size'];
704     }
705
706     function getName() {
707         return $this->_info['name'];
708     }
709
710     function getType() {
711         return $this->_info['type'];
712     }
713
714     function getTmpName() {
715         return $this->_info['tmp_name'];
716     }
717
718     function open() {
719         if ( ($fd = fopen($this->_info['tmp_name'], "rb")) ) {
720             if ($this->getSize() < filesize($this->_info['tmp_name'])) {
721                 // FIXME: Some PHP's (or is it some browsers?) put
722                 //    HTTP/MIME headers in the file body, some don't.
723                 //
724                 // At least, I think that's the case.  I know I used
725                 // to need this code, now I don't.
726                 //
727                 // This code is more-or-less untested currently.
728                 //
729                 // Dump HTTP headers.
730                 while ( ($header = fgets($fd, 4096)) ) {
731                     if (trim($header) == '') {
732                         break;
733                     }
734                     else if (!preg_match('/^content-(length|type):/i', $header)) {
735                         rewind($fd);
736                         break;
737                     }
738                 }
739             }
740         }
741         return $fd;
742     }
743
744     function getContents() {
745         $fd = $this->open();
746         $data = fread($fd, $this->getSize());
747         fclose($fd);
748         return $data;
749     }
750 }
751
752 /**
753  * Create NCSA "combined" log entry for current request.
754  */
755 class Request_AccessLogEntry
756 {
757     /**
758      * Constructor.
759      *
760      * The log entry will be automatically appended to the log file
761      * when the current request terminates.
762      *
763      * If you want to modify a Request_AccessLogEntry before it gets
764      * written (e.g. via the setStatus and setSize methods) you should
765      * use an '&' on the constructor, so that you're working with the
766      * original (rather than a copy) object.
767      *
768      * <pre>
769      *    $log_entry = & new Request_AccessLogEntry($req, "/tmp/wiki_access_log");
770      *    $log_entry->setStatus(401);
771      * </pre>
772      *
773      *
774      * @param $request object  Request object for current request.
775      * @param $logfile string  Log file name.
776      */
777     function Request_AccessLogEntry (&$request, $logfile) {
778         $this->logfile = $logfile;
779         
780         $this->host  = $request->get('REMOTE_HOST');
781         $this->ident = $request->get('REMOTE_IDENT');
782         if (!$this->ident)
783             $this->ident = '-';
784         $this->user = '-';        // FIXME: get logged-in user name
785         $this->time = time();
786         $this->request = join(' ', array($request->get('REQUEST_METHOD'),
787                                          $request->get('REQUEST_URI'),
788                                          $request->get('SERVER_PROTOCOL')));
789         $this->status = 200;
790         $this->size = 0;
791         $this->referer = (string) $request->get('HTTP_REFERER');
792         $this->user_agent = (string) $request->get('HTTP_USER_AGENT');
793
794         global $Request_AccessLogEntry_entries;
795         if (!isset($Request_AccessLogEntry_entries)) {
796             register_shutdown_function("Request_AccessLogEntry_shutdown_function");
797         }
798         $Request_AccessLogEntry_entries[] = &$this;
799     }
800
801     /**
802      * Set result status code.
803      *
804      * @param $status integer  HTTP status code.
805      */
806     function setStatus ($status) {
807         $this->status = $status;
808     }
809     
810     /**
811      * Set response size.
812      *
813      * @param $size integer
814      */
815     function setSize ($size) {
816         $this->size = $size;
817     }
818     
819     /**
820      * Get time zone offset.
821      *
822      * This is a static member function.
823      *
824      * @param $time integer Unix timestamp (defaults to current time).
825      * @return string Zone offset, e.g. "-0800" for PST.
826      */
827     function _zone_offset ($time = false) {
828         if (!$time)
829             $time = time();
830         $offset = date("Z", $time);
831         $negoffset = "";
832         if ($offset < 0) {
833             $negoffset = "-";
834             $offset = -$offset;
835         }
836         $offhours = floor($offset / 3600);
837         $offmins  = $offset / 60 - $offhours * 60;
838         return sprintf("%s%02d%02d", $negoffset, $offhours, $offmins);
839     }
840
841     /**
842      * Format time in NCSA format.
843      *
844      * This is a static member function.
845      *
846      * @param $time integer Unix timestamp (defaults to current time).
847      * @return string Formatted date & time.
848      */
849     function _ncsa_time($time = false) {
850         if (!$time)
851             $time = time();
852
853         return date("d/M/Y:H:i:s", $time) .
854             " " . $this->_zone_offset();
855     }
856
857     /**
858      * Write entry to log file.
859      */
860     function write() {
861         $entry = sprintf('%s %s %s [%s] "%s" %d %d "%s" "%s"',
862                          $this->host, $this->ident, $this->user,
863                          $this->_ncsa_time($this->time),
864                          $this->request, $this->status, $this->size,
865                          $this->referer, $this->user_agent);
866
867         //Error log doesn't provide locking.
868         //error_log("$entry\n", 3, $this->logfile);
869
870         // Alternate method
871         if (($fp = fopen($this->logfile, "a"))) {
872             flock($fp, LOCK_EX);
873             fputs($fp, "$entry\n");
874             fclose($fp);
875         }
876     }
877 }
878
879 /**
880  * Shutdown callback.
881  *
882  * @access private
883  * @see Request_AccessLogEntry
884  */
885 function Request_AccessLogEntry_shutdown_function ()
886 {
887     global $Request_AccessLogEntry_entries;
888     
889     foreach ($Request_AccessLogEntry_entries as $entry) {
890         $entry->write();
891     }
892     unset($Request_AccessLogEntry_entries);
893 }
894
895
896 class HTTP_ETag {
897     function HTTP_ETag($val, $is_weak=false) {
898         $this->_val = hash($val);
899         $this->_weak = $is_weak;
900     }
901
902     /** Comparison
903      *
904      * Strong comparison: If either (or both) tag is weak, they
905      *  are not equal.
906      */
907     function equals($that, $strong_match=false) {
908         if ($this->_val != $that->_val)
909             return false;
910         if ($strong_match and ($this->_weak or $that->_weak))
911             return false;
912         return true;
913     }
914
915
916     function asString() {
917         $quoted = '"' . addslashes($this->_val) . '"';
918         return $this->_weak ? "W/$quoted" : $quoted;
919     }
920
921     /** Parse tag from header.
922      *
923      * This is a static member function.
924      */
925     function parse($strval) {
926         if (!preg_match(':^(W/)?"(.+)"$:i', trim($strval), $m))
927             return false;       // parse failed
928         list(,$weak,$str) = $m;
929         return new HTTP_ETag(stripslashes($str), $weak);
930     }
931
932     function matches($taglist, $strong_match=false) {
933         $taglist = trim($taglist);
934
935         if ($taglist == '*') {
936             if ($strong_match)
937                 return ! $this->_weak;
938             else
939                 return true;
940         }
941
942         while (preg_match('@^(W/)?"((?:\\\\.|[^"])*)"\s*,?\s*@i',
943                           $taglist, $m)) {
944             list($match, $weak, $str) = $m;
945             $taglist = substr($taglist, strlen($match));
946             $tag = new HTTP_ETag(stripslashes($str), $weak);
947             if ($this->equals($tag, $strong_match)) {
948                 return true;
949             }
950         }
951         return false;
952     }
953 }
954
955 // Possible results from the HTTP_ValidatorSet::_check*() methods.
956 // (Higher numerical values take precedence.)
957 define ('_HTTP_VAL_PASS', 0);           // Test is irrelevant
958 define ('_HTTP_VAL_NOT_MODIFIED', 1);   // Test passed, content not changed
959 define ('_HTTP_VAL_MODIFIED', 2);       // Test failed, content changed
960 define ('_HTTP_VAL_FAILED', 3);         // Precondition failed.
961
962 class HTTP_ValidatorSet {
963     function HTTP_ValidatorSet($validators) {
964         $this->_mtime = $this->_weak = false;
965         $this->_tag = array();
966         
967         foreach ($validators as $key => $val) {
968             if ($key == '%mtime') {
969                 $this->_mtime = $val;
970             }
971             elseif ($key == '%weak') {
972                 if ($val)
973                     $this->_weak = true;
974             }
975             else {
976                 $this->_tag[$key] = $val;
977             }
978         }
979     }
980
981     function append($that) {
982         if (is_array($that))
983             $that = new HTTP_ValidatorSet($that);
984
985         // Pick the most recent mtime
986         if (isset($that->_mtime))
987             if (!isset($this->_mtime) || $that->_mtime > $this->_mtime)
988                 $this->_mtime = $that->_mtime;
989
990         // If either is weak, we're weak
991         if (!empty($that->_weak))
992             $this->_weak = true;
993         if (is_array($this->_tag))
994             $this->_tag = array_merge($this->_tag, $that->_tag);
995         else
996             $this->_tag = $that->_tag;
997     }
998
999     function getETag() {
1000         if (! $this->_tag)
1001             return false;
1002         return new HTTP_ETag($this->_tag, $this->_weak);
1003     }
1004
1005     function getModificationTime() {
1006         return $this->_mtime;
1007     }
1008     
1009     function checkConditionalRequest (&$request) {
1010         $result = max($this->_checkIfUnmodifiedSince($request),
1011                       $this->_checkIfModifiedSince($request),
1012                       $this->_checkIfMatch($request),
1013                       $this->_checkIfNoneMatch($request));
1014
1015         if ($result == _HTTP_VAL_PASS || $result == _HTTP_VAL_MODIFIED)
1016             return false;       // "please proceed with normal processing"
1017         elseif ($result == _HTTP_VAL_FAILED)
1018             return 412;         // "412 Precondition Failed"
1019         elseif ($result == _HTTP_VAL_NOT_MODIFIED)
1020             return 304;         // "304 Not Modified"
1021
1022         trigger_error("Ack, shouldn't get here", E_USER_ERROR);
1023         return false;
1024     }
1025
1026     function _checkIfUnmodifiedSince(&$request) {
1027         if ($this->_mtime !== false) {
1028             $since = ParseRfc1123DateTime($request->get("HTTP_IF_UNMODIFIED_SINCE"));
1029             if ($since !== false && $this->_mtime > $since)
1030                 return _HTTP_VAL_FAILED;
1031         }
1032         return _HTTP_VAL_PASS;
1033     }
1034
1035     function _checkIfModifiedSince(&$request) {
1036         if ($this->_mtime !== false and $request->isGetOrHead()) {
1037             $since = ParseRfc1123DateTime($request->get("HTTP_IF_MODIFIED_SINCE"));
1038             if ($since !== false) {
1039                 if ($this->_mtime <= $since)
1040                     return _HTTP_VAL_NOT_MODIFIED;
1041                 return _HTTP_VAL_MODIFIED;
1042             }
1043         }
1044         return _HTTP_VAL_PASS;
1045     }
1046
1047     function _checkIfMatch(&$request) {
1048         if ($this->_tag && ($taglist = $request->get("HTTP_IF_MATCH"))) {
1049             $tag = $this->getETag();
1050             if (!$tag->matches($taglist, 'strong'))
1051                 return _HTTP_VAL_FAILED;
1052         }
1053         return _HTTP_VAL_PASS;
1054     }
1055
1056     function _checkIfNoneMatch(&$request) {
1057         if ($this->_tag && ($taglist = $request->get("HTTP_IF_NONE_MATCH"))) {
1058             $tag = $this->getETag();
1059             $strong_compare = ! $request->isGetOrHead();
1060             if ($taglist) {
1061                 if ($tag->matches($taglist, $strong_compare)) {
1062                     if ($request->isGetOrHead())
1063                         return _HTTP_VAL_NOT_MODIFIED;
1064                     else
1065                         return _HTTP_VAL_FAILED;
1066                 }
1067                 return _HTTP_VAL_MODIFIED;
1068             }
1069         }
1070         return _HTTP_VAL_PASS;
1071     }
1072 }
1073
1074
1075 // $Log: not supported by cvs2svn $
1076 // Revision 1.68  2004/10/12 13:13:19  rurban
1077 // php5 compatibility (5.0.1 ok)
1078 //
1079 // Revision 1.67  2004/09/25 18:56:54  rurban
1080 // make start_debug logic work
1081 //
1082 // Revision 1.66  2004/09/25 16:24:52  rurban
1083 // dont compress on debugging
1084 //
1085 // Revision 1.65  2004/09/17 14:13:49  rurban
1086 // We check for the client Accept-Encoding: "gzip" presence also
1087 // This should eliminate a lot or reported problems.
1088 //
1089 // Note that this doesn#t fix RSS ssues:
1090 // Most RSS clients are NOT(!) application/xml gzip compatible yet.
1091 // Even if they are sending the accept-encoding gzip header!
1092 // wget is, Mozilla, and MSIE no.
1093 // Of the RSS readers only MagpieRSS 0.5.2 is. http://www.rssgov.com/rssparsers.html
1094 //
1095 // Revision 1.64  2004/09/17 13:32:36  rurban
1096 // Disable server-side gzip encoding for RSS (RDF encoding), even if the client says it
1097 // supports it. Mozilla has this error, wget works fine. IE not checked.
1098 //
1099 // Revision 1.63  2004/07/01 09:29:40  rurban
1100 // fixed another DbSession crash: wrong WikiGroup vars
1101 //
1102 // Revision 1.62  2004/06/27 10:26:02  rurban
1103 // oci8 patch by Philippe Vanhaesendonck + some ADODB notes+fixes
1104 //
1105 // Revision 1.61  2004/06/25 14:29:17  rurban
1106 // WikiGroup refactoring:
1107 //   global group attached to user, code for not_current user.
1108 //   improved helpers for special groups (avoid double invocations)
1109 // new experimental config option ENABLE_XHTML_XML (fails with IE, and document.write())
1110 // fixed a XHTML validation error on userprefs.tmpl
1111 //
1112 // Revision 1.60  2004/06/19 11:51:13  rurban
1113 // CACHE_CONTROL: NONE => NO_CACHE
1114 //
1115 // Revision 1.59  2004/06/13 11:34:22  rurban
1116 // fixed bug #969532 (space in uploaded filenames)
1117 // improved upload error messages
1118 //
1119 // Revision 1.58  2004/06/04 20:32:53  rurban
1120 // Several locale related improvements suggested by Pierrick Meignen
1121 // LDAP fix by John Cole
1122 // reanable admin check without ENABLE_PAGEPERM in the admin plugins
1123 //
1124 // Revision 1.57  2004/06/03 18:54:25  rurban
1125 // fixed "lost level in session" warning, now that signout sets level = 0 (before -1)
1126 //
1127 // Revision 1.56  2004/05/17 17:43:29  rurban
1128 // CGI: no PATH_INFO fix
1129 //
1130 // Revision 1.55  2004/05/15 18:31:00  rurban
1131 // some action=pdf Request fixes: With MSIE it works now. Now the work with the page formatting begins.
1132 //
1133 // Revision 1.54  2004/05/04 22:34:25  rurban
1134 // more pdf support
1135 //
1136 // Revision 1.53  2004/05/03 21:57:47  rurban
1137 // locale updates: we previously lost some words because of wrong strings in
1138 //   PhotoAlbum, german rewording.
1139 // fixed $_SESSION registering (lost session vars, esp. prefs)
1140 // fixed ending slash in listAvailableLanguages/Themes
1141 //
1142 // Revision 1.52  2004/05/03 13:16:47  rurban
1143 // fixed UserPreferences update, esp for boolean and int
1144 //
1145 // Revision 1.51  2004/05/02 21:26:38  rurban
1146 // limit user session data (HomePageHandle and auth_dbi have to invalidated anyway)
1147 //   because they will not survive db sessions, if too large.
1148 // extended action=upgrade
1149 // some WikiTranslation button work
1150 // revert WIKIAUTH_UNOBTAINABLE (need it for main.php)
1151 // some temp. session debug statements
1152 //
1153 // Revision 1.50  2004/04/29 19:39:44  rurban
1154 // special support for formatted plugins (one-liners)
1155 //   like <small><plugin BlaBla ></small>
1156 // iter->asArray() helper for PopularNearby
1157 // db_session for older php's (no &func() allowed)
1158 //
1159 // Revision 1.49  2004/04/26 20:44:34  rurban
1160 // locking table specific for better databases
1161 //
1162 // Revision 1.48  2004/04/13 09:13:50  rurban
1163 // sf.net bug #933183 and http://bugs.php.net/17557
1164 // disable ob_gzhandler if apache_note cannot be used.
1165 //   (conservative until we find why)
1166 //
1167 // Revision 1.47  2004/04/02 15:06:55  rurban
1168 // fixed a nasty ADODB_mysql session update bug
1169 // improved UserPreferences layout (tabled hints)
1170 // fixed UserPreferences auth handling
1171 // improved auth stability
1172 // improved old cookie handling: fixed deletion of old cookies with paths
1173 //
1174 // Revision 1.46  2004/03/30 02:14:03  rurban
1175 // fixed yet another Prefs bug
1176 // added generic PearDb_iter
1177 // $request->appendValidators no so strict as before
1178 // added some box plugin methods
1179 // PageList commalist for condensed output
1180 //
1181 // Revision 1.45  2004/03/24 19:39:02  rurban
1182 // php5 workaround code (plus some interim debugging code in XmlElement)
1183 //   php5 doesn't work yet with the current XmlElement class constructors,
1184 //   WikiUserNew does work better than php4.
1185 // rewrote WikiUserNew user upgrading to ease php5 update
1186 // fixed pref handling in WikiUserNew
1187 // added Email Notification
1188 // added simple Email verification
1189 // removed emailVerify userpref subclass: just a email property
1190 // changed pref binary storage layout: numarray => hash of non default values
1191 // print optimize message only if really done.
1192 // forced new cookie policy: delete pref cookies, use only WIKI_ID as plain string.
1193 //   prefs should be stored in db or homepage, besides the current session.
1194 //
1195 // Revision 1.44  2004/03/14 16:26:22  rurban
1196 // copyright line
1197 //
1198 // Revision 1.43  2004/03/12 20:59:17  rurban
1199 // important cookie fix by Konstantin Zadorozhny
1200 // new editpage feature: JS_SEARCHREPLACE
1201 //
1202 // Revision 1.42  2004/03/10 15:38:48  rurban
1203 // store current user->page and ->action in session for WhoIsOnline
1204 // better WhoIsOnline icon
1205 // fixed WhoIsOnline warnings
1206 //
1207 // Revision 1.41  2004/02/27 01:25:14  rurban
1208 // Workarounds for upload handling
1209 //
1210 // Revision 1.40  2004/02/26 01:39:51  rurban
1211 // safer code
1212 //
1213 // Revision 1.39  2004/02/24 15:14:57  rurban
1214 // fixed action=upload problems on Win32, and remove Merge Edit buttons: file does not exist anymore
1215 //
1216 // Revision 1.38  2004/01/25 10:26:02  rurban
1217 // fixed bug [ 541193 ] HTTP_SERVER_VARS are Apache specific
1218 // http://sourceforge.net/tracker/index.php?func=detail&aid=541193&group_id=6121&atid=106121
1219 // CGI and other servers than apache populate _ENV and not _SERVER
1220 //
1221 // Revision 1.37  2003/12/26 06:41:16  carstenklapp
1222 // Bugfix: Try to defer OS errors about session.save_path and ACCESS_LOG,
1223 // so they don't prevent IE from partially (or not at all) rendering the
1224 // page. This should help a little for the IE user who encounters trouble
1225 // when setting up a new PhpWiki for the first time.
1226 //
1227
1228 // Local Variables:
1229 // mode: php
1230 // tab-width: 8
1231 // c-basic-offset: 4
1232 // c-hanging-comment-ender-p: nil
1233 // indent-tabs-mode: nil
1234 // End:   
1235 ?>