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