]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/Request.php
php url-rewriting miscalculates the ob length. fixes bug #1376007
[SourceForge/phpwiki.git] / lib / Request.php
1 <?php // -*-php-*-
2 rcs_id('$Id: Request.php,v 1.104 2006-04-16 11:42:16 rurban Exp $');
3 /*
4  Copyright (C) 2002,2004,2005 $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 class Request {
32         
33     function Request() {
34         $this->_fix_magic_quotes_gpc();
35         $this->_fix_multipart_form_data();
36         
37         switch($this->get('REQUEST_METHOD')) {
38         case 'GET':
39         case 'HEAD':
40             $this->args = &$GLOBALS['HTTP_GET_VARS'];
41             break;
42         case 'POST':
43             $this->args = &$GLOBALS['HTTP_POST_VARS'];
44             break;
45         default:
46             $this->args = array();
47             break;
48         }
49         
50         $this->session = new Request_SessionVars; 
51         $this->cookies = new Request_CookieVars;
52         
53         if (ACCESS_LOG or ACCESS_LOG_SQL) {
54             $this->_accesslog = new Request_AccessLog(ACCESS_LOG, ACCESS_LOG_SQL);
55         }
56         
57         $GLOBALS['request'] = $this;
58     }
59
60     function get($key) {
61         if (!empty($GLOBALS['HTTP_SERVER_VARS']))
62             $vars = &$GLOBALS['HTTP_SERVER_VARS'];
63         else // cgi or other servers than Apache
64             $vars = &$GLOBALS['HTTP_ENV_VARS'];
65
66         if (isset($vars[$key]))
67             return $vars[$key];
68
69         switch ($key) {
70         case 'REMOTE_HOST':
71             $addr = $vars['REMOTE_ADDR'];
72             if (defined('ENABLE_REVERSE_DNS') && ENABLE_REVERSE_DNS)
73                 return $vars[$key] = gethostbyaddr($addr);
74             else
75                 return $addr;
76         default:
77             return false;
78         }
79     }
80
81     function getArg($key) {
82         if (isset($this->args[$key]))
83             return $this->args[$key];
84         return false;
85     }
86
87     function getArgs () {
88         return $this->args;
89     }
90     
91     function setArg($key, $val) {
92         if ($val === false)
93             unset($this->args[$key]);
94         else
95             $this->args[$key] = $val;
96     }
97     
98     // Well oh well. Do we really want to pass POST params back as GET?
99     function getURLtoSelf($args = false, $exclude = array()) {
100         $get_args = $this->args;
101         if ($args)
102             $get_args = array_merge($get_args, $args);
103
104         // Err... good point...
105         // sortby buttons
106         if ($this->isPost()) {
107             $exclude = array_merge($exclude, array('action','auth'));
108             //$get_args = $args; // or only the provided
109             /*
110             trigger_error("Request::getURLtoSelf() should probably not be from POST",
111                           E_USER_NOTICE);
112             */
113         }
114
115         foreach ($exclude as $ex) {
116             if (!empty($get_args[$ex])) unset($get_args[$ex]);
117         }
118
119         $pagename = $get_args['pagename'];
120         unset ($get_args['pagename']);
121         if (!empty($get_args['action']) and $get_args['action'] == 'browse')
122             unset($get_args['action']);
123
124         return WikiURL($pagename, $get_args);
125     }
126
127     function isPost () {
128         return $this->get("REQUEST_METHOD") == "POST";
129     }
130
131     function isGetOrHead () {
132         return in_array($this->get('REQUEST_METHOD'),
133                         array('GET', 'HEAD'));
134     }
135
136     function httpVersion() {
137         if (!preg_match('@HTTP\s*/\s*(\d+.\d+)@', $this->get('SERVER_PROTOCOL'), $m))
138             return false;
139         return (float) $m[1];
140     }
141     
142     /* Redirects after edit may fail if no theme signature image is defined. 
143      * Set DISABLE_HTTP_REDIRECT = true then.
144      */
145     function redirect($url, $noreturn = true) {
146         $bogus = defined('DISABLE_HTTP_REDIRECT') && DISABLE_HTTP_REDIRECT;
147         
148         if (!$bogus) {
149             header("Location: $url");
150             /*
151              * "302 Found" is not really meant to be sent in response
152              * to a POST.  Worse still, according to (both HTTP 1.0
153              * and 1.1) spec, the user, if it is sent, the user agent
154              * is supposed to use the same method to fetch the
155              * redirected URI as the original.
156              *
157              * That means if we redirect from a POST, the user-agent
158              * supposed to generate another POST.  Not what we want.
159              * (We do this after a page save after all.)
160              *
161              * Fortunately, most/all browsers don't do that.
162              *
163              * "303 See Other" is what we really want.  But it only
164              * exists in HTTP/1.1
165              *
166              * FIXME: this is still not spec compliant for HTTP
167              * version < 1.1.
168              */
169             $status = $this->httpVersion() >= 1.1 ? 303 : 302;
170             $this->setStatus($status);
171         }
172
173         if ($noreturn) {
174             $this->discardOutput(); // This might print the gzip headers. Not good.
175             $this->buffer_output(false);
176             
177             include_once('lib/Template.php');
178             $tmpl = new Template('redirect', $this, array('REDIRECT_URL' => $url));
179             $tmpl->printXML();
180             $this->finish();
181         }
182         elseif ($bogus) {
183             // Safari needs window.location.href = targeturl
184             return JavaScript("
185               function redirect(url) {
186                 if (typeof location.replace == 'function')
187                   location.replace(url);
188                 else if (typeof location.assign == 'function')
189                   location.assign(url);
190                 else if (self.location.href)
191                   self.location.href = url;
192                 else
193                   window.location = url;
194               }
195               redirect('" . addslashes($url) . "')");
196         }
197     }
198
199     /** Set validators for this response.
200      *
201      * This sets a (possibly incomplete) set of validators
202      * for this response.
203      *
204      * The validator set can be extended using appendValidators().
205      *
206      * When you're all done setting and appending validators, you
207      * must call checkValidators() to check them and set the
208      * appropriate headers in the HTTP response.
209      *
210      * Example Usage:
211      *  ...
212      *  $request->setValidators(array('pagename' => $pagename,
213      *                                '%mtime' => $rev->get('mtime')));
214      *  ...
215      *  // Wups... response content depends on $otherpage, too...
216      *  $request->appendValidators(array('otherpage' => $otherpagerev->getPageName(),
217      *                                   '%mtime' => $otherpagerev->get('mtime')));
218      *  ...
219      *  // After all validators have been set:
220      *  $request->checkValidators();
221      */
222     function setValidators($validator_set) {
223         if (is_array($validator_set))
224             $validator_set = new HTTP_ValidatorSet($validator_set);
225         $this->_validators = $validator_set;
226     }
227     
228     /** Append more validators for this response. 
229      *  i.e dependencies on other pages mtimes
230      *  now it may be called in init also to simplify client code.
231      */ 
232     function appendValidators($validator_set) {
233         if (!isset($this->_validators)) {
234             $this->setValidators($validator_set);
235             return;
236         }
237         $this->_validators->append($validator_set);
238     }
239     
240     /** Check validators and set headers in HTTP response
241      *
242      * This sets the appropriate "Last-Modified" and "ETag"
243      * headers in the HTTP response.
244      *
245      * Additionally, if the validators match any(all) conditional
246      * headers in the HTTP request, this method will not return, but
247      * instead will send "304 Not Modified" or "412 Precondition
248      * Failed" (as appropriate) back to the client.
249      */
250     function checkValidators() {
251         $validators = &$this->_validators;
252         
253         // Set validator headers
254         if (!empty($this->_is_buffering_output) or !headers_sent()) {
255             if (($etag = $validators->getETag()) !== false)
256                 header("ETag: " . $etag->asString());
257             if (($mtime = $validators->getModificationTime()) !== false)
258                 header("Last-Modified: " . Rfc1123DateTime($mtime));
259
260             // Set cache control headers
261             $this->cacheControl();
262         }
263
264         if (CACHE_CONTROL == 'NO_CACHE')
265             return;             // don't check conditionals...
266         
267         // Check conditional headers in request
268         $status = $validators->checkConditionalRequest($this);
269         if ($status) {
270             // Return short response due to failed conditionals
271             $this->setStatus($status);
272             echo "\n\n";
273             $this->discardOutput();
274             $this->finish();
275             exit();
276         }
277     }
278
279     /** Set the cache control headers in the HTTP response.
280      */
281     function cacheControl($strategy=CACHE_CONTROL, $max_age=CACHE_CONTROL_MAX_AGE) {
282         if ($strategy == 'NO_CACHE') {
283             $cache_control = "no-cache"; // better set private. See Pear HTTP_Header
284             $max_age = -20;
285         }
286         elseif ($strategy == 'ALLOW_STALE' && $max_age > 0) {
287             $cache_control = sprintf("max-age=%d", $max_age);
288         }
289         else {
290             $cache_control = "must-revalidate";
291             $max_age = -20;
292         }
293         header("Cache-Control: $cache_control");
294         header("Expires: " . Rfc1123DateTime(time() + $max_age));
295         header("Vary: Cookie"); // FIXME: add more here?
296     }
297     
298     function setStatus($status) {
299         if (preg_match('|^HTTP/.*?\s(\d+)|i', $status, $m)) {
300             header($status);
301             $status = $m[1];
302         }
303         else {
304             $status = (integer) $status;
305             $reason = array('200' => 'OK',
306                             '302' => 'Found',
307                             '303' => 'See Other',
308                             '304' => 'Not Modified',
309                             '400' => 'Bad Request',
310                             '401' => 'Unauthorized',
311                             '403' => 'Forbidden',
312                             '404' => 'Not Found',
313                             '412' => 'Precondition Failed');
314             // FIXME: is it always okay to send HTTP/1.1 here, even for older clients?
315             header(sprintf("HTTP/1.1 %d %s", $status, $reason[$status]));
316         }
317
318         if (isset($this->_log_entry))
319             $this->_log_entry->setStatus($status);
320     }
321
322     function buffer_output($compress = true) {
323         // FIXME: disables sessions (some byte before all headers_sent())
324         /*if (defined('USECACHE') and !USECACHE) {
325             $this->_is_buffering_output = false;
326             return;
327         }*/
328         if (defined('COMPRESS_OUTPUT')) {
329             if (!COMPRESS_OUTPUT)
330                 $compress = false;
331         }
332         elseif (!check_php_version(4,2,3))
333             $compress = false;
334         elseif (isCGI()) // necessary?
335             $compress = false;
336             
337         if ($this->getArg('start_debug'))
338             $compress = false;
339         
340         // Should we compress even when apache_note is not available?
341         // sf.net bug #933183 and http://bugs.php.net/17557
342         // This effectively eliminates CGI, but all other servers also. hmm.
343         if ($compress 
344             and (!function_exists('ob_gzhandler') 
345                  or !function_exists('apache_note'))) 
346             $compress = false;
347             
348         // "output handler 'ob_gzhandler' cannot be used twice"
349         // http://www.php.net/ob_gzhandler
350         if ($compress and ini_get("zlib.output_compression"))
351             $compress = false;
352
353         // New: we check for the client Accept-Encoding: "gzip" presence also
354         // This should eliminate a lot or reported problems.
355         if ($compress
356             and (!$this->get("HTTP_ACCEPT_ENCODING")
357                  or !strstr($this->get("HTTP_ACCEPT_ENCODING"), "gzip")))
358             $compress = false;
359
360         // Most RSS clients are NOT(!) application/xml gzip compatible yet. 
361         // Even if they are sending the accept-encoding gzip header!
362         // wget is, Mozilla, and MSIE no.
363         // Of the RSS readers only MagpieRSS 0.5.2 is. http://www.rssgov.com/rssparsers.html
364         // See also http://phpwiki.sourceforge.net/phpwiki/KnownBugs
365         if ($compress 
366             and $this->getArg('format') 
367             and strstr($this->getArg('format'), 'rss'))
368             $compress = false;
369
370         if ($compress) {
371             ob_start('phpwiki_gzhandler');
372             
373             // TODO: dont send a length or get the gzip'ed data length.
374             $this->_is_compressing_output = true; 
375             header("Content-Encoding: gzip");
376             /*
377              * Attempt to prevent Apache from doing the dreaded double-gzip.
378              *
379              * It would be better if we could detect when apache was going
380              * to zip for us, and then let it ... but I have yet to figure
381              * out how to do that.
382              */
383             if (function_exists('apache_note'))
384                 @apache_note('no-gzip', 1);
385         }
386         else {
387             // Now we alway buffer output.
388             // This is so we can set HTTP headers (e.g. for redirect)
389             // at any point.
390             // FIXME: change the name of this method.
391             ob_start();
392             $this->_is_compressing_output = false;
393         }
394         $this->_is_buffering_output = true;
395         $this->_ob_get_length = 0;
396     }
397
398     function discardOutput() {
399         if (!empty($this->_is_buffering_output)) {
400             ob_clean();
401             $this->_is_buffering_output = false;
402         } else {
403             trigger_error("Not buffering output", E_USER_NOTICE);
404         }
405     }
406
407     /** 
408      * Longer texts need too much memory on tiny or memory-limit=8MB systems.
409      * We might want to flush our buffer and restart again.
410      * (This would be fine if php would release its memory)
411      * Note that this must not be called inside Template expansion or other 
412      * sections with ob_buffering.
413      */
414     function chunkOutput() {
415         if (!empty($this->_is_buffering_output) or 
416             (function_exists('ob_get_level') and @ob_get_level())) {
417             $this->_do_chunked_output = true;
418             if (empty($this->_ob_get_length)) $this->_ob_get_length = 0;
419             $this->_ob_get_length += ob_get_length();
420             while (@ob_end_flush());
421             ob_end_clean();
422             ob_start();
423         }
424     }
425
426     function finish() {
427         $this->_finishing = true;
428         if (!empty($this->_accesslog)) {
429             $this->_accesslog->push($this);
430             if (empty($this->_do_chunked_output) and empty($this->_ob_get_length))
431                 $this->_ob_get_length = ob_get_length();
432             $this->_accesslog->setSize($this->_ob_get_length);
433             global $RUNTIMER;
434             if ($RUNTIMER) $this->_accesslog->setDuration($RUNTIMER->getTime());
435             // sql logging must be done before the db is closed.
436             if (isset($this->_accesslog->logtable))
437                 $this->_accesslog->write_sql();
438         }
439         
440         if (!empty($this->_is_buffering_output)) {
441             /* This cannot work because it might destroy xml markup */
442             /*
443             if (0 and $GLOBALS['SearchHighLightQuery'] and check_php_version(4,2)) {
444                 $html = str_replace($GLOBALS['SearchHighLightQuery'],
445                                     '<span class="search-term">'.$GLOBALS['SearchHighLightQuery'].'</span>',
446                                     ob_get_contents());
447                 ob_clean();
448                 header(sprintf("Content-Length: %d", strlen($html)));
449                 echo $html;
450             } else {
451             */
452             // if _is_compressing_output then ob_get_length() returns 
453             // the uncompressed length, not the gzip'ed as required.
454             if (!headers_sent() and !$this->_is_compressing_output) {
455                 // php url-rewriting miscalculates the ob length. fixes bug #1376007
456                 if (ini_get('use_trans_sid') == 'off') {
457                     if (empty($this->_do_chunked_output)) {
458                         $this->_ob_get_length = ob_get_length();
459                     }
460                     header(sprintf("Content-Length: %d", $this->_ob_get_length));
461                 }
462             }
463             $this->_is_buffering_output = false;
464             while (@ob_end_flush());
465         } elseif (function_exists('ob_get_level') and @ob_get_level()) {
466             while (@ob_end_flush());
467         }
468         session_write_close();
469         if (!empty($this->_dbi)) {
470             $this->_dbi->close();
471             unset($this->_dbi);
472         }
473
474         exit;
475     }
476
477     function getSessionVar($key) {
478         return $this->session->get($key);
479     }
480     function setSessionVar($key, $val) {
481         if ($key == 'wiki_user') {
482             if (empty($val->page))
483                 $val->page = $this->getArg('pagename');
484             if (empty($val->action))
485                 $val->action = $this->getArg('action');
486             // avoid recursive objects and session resource handles
487             // avoid overlarge session data (max 4000 byte!)
488             if (isset($val->_group)) {
489                 unset($val->_group->_request);
490                 unset($val->_group->user);
491             }
492             if (ENABLE_USER_NEW) {
493                 unset($val->_HomePagehandle);
494                 unset($val->_auth_dbi);
495             } else {
496                 unset($val->_dbi);
497                 unset($val->_authdbi);
498                 unset($val->_homepage);
499                 unset($val->_request);
500             }
501         }
502         return $this->session->set($key, $val);
503     }
504     function deleteSessionVar($key) {
505         return $this->session->delete($key);
506     }
507
508     function getCookieVar($key) {
509         return $this->cookies->get($key);
510     }
511     function setCookieVar($key, $val, $lifetime_in_days = false, $path = false) {
512         return $this->cookies->set($key, $val, $lifetime_in_days, $path);
513     }
514     function deleteCookieVar($key) {
515         return $this->cookies->delete($key);
516     }
517     
518     function getUploadedFile($key) {
519         return Request_UploadedFile::getUploadedFile($key);
520     }
521     
522
523     function _fix_magic_quotes_gpc() {
524         $needs_fix = array('HTTP_POST_VARS',
525                            'HTTP_GET_VARS',
526                            'HTTP_COOKIE_VARS',
527                            'HTTP_SERVER_VARS',
528                            'HTTP_POST_FILES');
529         
530         // Fix magic quotes.
531         if (get_magic_quotes_gpc()) {
532             foreach ($needs_fix as $vars)
533                 $this->_stripslashes($GLOBALS[$vars]);
534         }
535     }
536
537     function _stripslashes(&$var) {
538         if (is_array($var)) {
539             foreach ($var as $key => $val)
540                 $this->_stripslashes($var[$key]);
541         }
542         elseif (is_string($var))
543             $var = stripslashes($var);
544     }
545     
546     function _fix_multipart_form_data () {
547         if (preg_match('|^multipart/form-data|', $this->get('CONTENT_TYPE')))
548             $this->_strip_leading_nl($GLOBALS['HTTP_POST_VARS']);
549     }
550     
551     function _strip_leading_nl(&$var) {
552         if (is_array($var)) {
553             foreach ($var as $key => $val)
554                 $this->_strip_leading_nl($var[$key]);
555         }
556         elseif (is_string($var))
557             $var = preg_replace('|^\r?\n?|', '', $var);
558     }
559 }
560
561 class Request_SessionVars {
562     function Request_SessionVars() {
563         // Prevent cacheing problems with IE 5
564         session_cache_limiter('none');
565                                         
566         // Avoid to get a notice if session is already started,
567         // for example if session.auto_start is activated
568         if (!session_id())
569             session_start();
570     }
571     
572     function get($key) {
573         $vars = &$GLOBALS['HTTP_SESSION_VARS'];
574         if (isset($vars[$key]))
575             return $vars[$key];
576         return false;
577     }
578     
579     function set($key, $val) {
580         $vars = &$GLOBALS['HTTP_SESSION_VARS'];
581         if (!function_usable('get_cfg_var') or get_cfg_var('register_globals')) {
582             // This is funky but necessary, at least in some PHP's
583             $GLOBALS[$key] = $val;
584         }
585         $vars[$key] = $val;
586         if (isset($_SESSION))
587             $_SESSION[$key] = $val;
588         session_register($key);
589     }
590     
591     function delete($key) {
592         $vars = &$GLOBALS['HTTP_SESSION_VARS'];
593         if (!function_usable('ini_get') or ini_get('register_globals'))
594             unset($GLOBALS[$key]);
595         if (DEBUG) trigger_error("delete session $key", E_USER_WARNING);
596         unset($vars[$key]);
597         session_unregister($key);
598     }
599 }
600
601 class Request_CookieVars {
602     
603     function get($key) {
604         $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
605         if (isset($vars[$key])) {
606             @$val = unserialize(base64_decode($vars[$key]));
607             if (!empty($val))
608                 return $val;
609             @$val = urldecode($vars[$key]);
610             if (!empty($val))
611                 return $val;
612         }
613         return false;
614     }
615
616     function get_old($key) {
617         $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
618         if (isset($vars[$key])) {
619             @$val = unserialize(base64_decode($vars[$key]));
620             if (!empty($val))
621                 return $val;
622             @$val = unserialize($vars[$key]);
623             if (!empty($val))
624                 return $val;
625             @$val = $vars[$key];
626             if (!empty($val))
627                 return $val;
628         }
629         return false;
630     }
631
632     function set($key, $val, $persist_days = false, $path = false) {
633         // if already defined, ignore
634         if (defined('MAIN_setUser') and $key = getCookieName()) return;
635         if (defined('WIKI_XMLRPC') and WIKI_XMLRPC) return;
636
637         $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
638         if (is_numeric($persist_days)) {
639             $expires = time() + (24 * 3600) * $persist_days;
640         }
641         else {
642             $expires = 0;
643         }
644         if (is_array($val) or is_object($val))
645             $packedval = base64_encode(serialize($val));
646         else
647             $packedval = urlencode($val);
648         $vars[$key] = $packedval;
649         @$_COOKIE[$key] = $packedval;
650         if ($path)
651             @setcookie($key, $packedval, $expires, $path);
652         else
653             @setcookie($key, $packedval, $expires);
654     }
655     
656     function delete($key) {
657         static $deleted = array();
658         if (isset($deleted[$key])) return;
659         if (defined('WIKI_XMLRPC') and WIKI_XMLRPC) return;
660         
661         $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
662         if (!defined('COOKIE_DOMAIN'))
663             @setcookie($key, '', 0);
664         else    
665             @setcookie($key, '', 0, COOKIE_DOMAIN);
666         unset($GLOBALS['HTTP_COOKIE_VARS'][$key]);
667         unset($_COOKIE[$key]);
668         $deleted[$key] = 1;
669     }
670 }
671
672 /* Win32 Note:
673    [\winnt\php.ini]
674    You must set "upload_tmp_dir" = "/tmp/" or "C:/tmp/"
675    Best on the same drive as apache, with forward slashes 
676    and with ending slash!
677    Otherwise "\\" => "" and the uploaded file will not be found.
678 */
679 class Request_UploadedFile {
680     function getUploadedFile($postname) {
681         global $HTTP_POST_FILES;
682
683         // Against php5 with !ini_get('register-long-arrays'). See Bug #1180115
684         if (empty($HTTP_POST_FILES) and !empty($_FILES))
685             $HTTP_POST_FILES =& $_FILES;
686         if (!isset($HTTP_POST_FILES[$postname]))
687             return false;
688         
689         $fileinfo =& $HTTP_POST_FILES[$postname];
690         if ($fileinfo['error']) {
691             // See https://sourceforge.net/forum/message.php?msg_id=3093651
692             $err = (int) $fileinfo['error'];
693             // errmsgs by Shilad Sen
694             switch ($err) {
695             case 1:
696                 trigger_error(_("Upload error: file too big"), E_USER_WARNING);
697                 break;
698             case 2:
699                 trigger_error(_("Upload error: file too big"), E_USER_WARNING);
700                 break;
701             case 3:
702                 trigger_error(_("Upload error: file only partially recieved"), E_USER_WARNING);
703                 break;
704             case 4:
705                 trigger_error(_("Upload error: no file selected"), E_USER_WARNING);
706                 break;
707             default:
708                 trigger_error(_("Upload error: unknown error #") . $err, E_USER_WARNING);
709             }
710             return false;
711         }
712
713         // With windows/php 4.2.1 is_uploaded_file() always returns false.
714         // Be sure that upload_tmp_dir ends with a slash!
715         if (!is_uploaded_file($fileinfo['tmp_name'])) {
716             if (isWindows()) {
717                 if (!$tmp_file = get_cfg_var('upload_tmp_dir')) {
718                     $tmp_file = dirname(tempnam('', ''));
719                 }
720                 $tmp_file .= '/' . basename($fileinfo['tmp_name']);
721                 /* but ending slash in php.ini upload_tmp_dir is required. */
722                 if (realpath(ereg_replace('/+', '/', $tmp_file)) != realpath($fileinfo['tmp_name'])) {
723                     trigger_error(sprintf("Uploaded tmpfile illegal: %s != %s.",$tmp_file, $fileinfo['tmp_name']).
724                                   "\n".
725                                   "Probably illegal TEMP environment or upload_tmp_dir setting.",
726                                   E_USER_ERROR);
727                     return false;
728                 } else {
729                     /*
730                     trigger_error(sprintf("Workaround for PHP/Windows is_uploaded_file() problem for %s.",
731                                           $fileinfo['tmp_name'])."\n".
732                                   "Probably illegal TEMP environment or upload_tmp_dir setting.", 
733                                   E_USER_NOTICE);
734                     */
735                     ;
736                 }
737             } else {
738               trigger_error(sprintf("Uploaded tmpfile %s not found.", $fileinfo['tmp_name'])."\n".
739                            " Probably illegal TEMP environment or upload_tmp_dir setting.",
740                           E_USER_WARNING);
741             }
742         }
743         return new Request_UploadedFile($fileinfo);
744     }
745     
746     function Request_UploadedFile($fileinfo) {
747         $this->_info = $fileinfo;
748     }
749
750     function getSize() {
751         return $this->_info['size'];
752     }
753
754     function getName() {
755         return $this->_info['name'];
756     }
757
758     function getType() {
759         return $this->_info['type'];
760     }
761
762     function getTmpName() {
763         return $this->_info['tmp_name'];
764     }
765
766     function open() {
767         if ( ($fd = fopen($this->_info['tmp_name'], "rb")) ) {
768             if ($this->getSize() < filesize($this->_info['tmp_name'])) {
769                 // FIXME: Some PHP's (or is it some browsers?) put
770                 //    HTTP/MIME headers in the file body, some don't.
771                 //
772                 // At least, I think that's the case.  I know I used
773                 // to need this code, now I don't.
774                 //
775                 // This code is more-or-less untested currently.
776                 //
777                 // Dump HTTP headers.
778                 while ( ($header = fgets($fd, 4096)) ) {
779                     if (trim($header) == '') {
780                         break;
781                     }
782                     else if (!preg_match('/^content-(length|type):/i', $header)) {
783                         rewind($fd);
784                         break;
785                     }
786                 }
787             }
788         }
789         return $fd;
790     }
791
792     function getContents() {
793         $fd = $this->open();
794         $data = fread($fd, $this->getSize());
795         fclose($fd);
796         return $data;
797     }
798 }
799
800 /**
801  * Create NCSA "combined" log entry for current request.
802  * Also needed for advanced spam prevention.
803  * global object holding global state (sql or file, entries, to dump)
804  */
805 class Request_AccessLog {
806     /**
807      * @param $logfile string  Log file name.
808      */
809     function Request_AccessLog ($logfile, $do_sql = false) {
810         //global $request; // request not yet initialized!
811
812         $this->logfile = $logfile;
813         if ($logfile and !is_writeable($logfile)) {
814             trigger_error
815                 (sprintf(_("%s is not writable."), _("The PhpWiki access log file"))
816                  . "\n"
817                  . sprintf(_("Please ensure that %s is writable, or redefine %s in config/config.ini."),
818                            sprintf(_("the file '%s'"), ACCESS_LOG),
819                            'ACCESS_LOG')
820                  , E_USER_NOTICE);
821         }
822         //$request->_accesslog =& $this;
823         //if (empty($request->_accesslog->entries))
824         register_shutdown_function("Request_AccessLogEntry_shutdown_function");
825         
826         if ($do_sql) {
827             global $DBParams;
828             if (!in_array($DBParams['dbtype'], array('SQL','ADODB'))) {
829                 trigger_error("Unsupported database backend for ACCESS_LOG_SQL.\nNeed DATABASE_TYPE=SQL or ADODB");
830             } else {
831                 //$this->_dbi =& $request->_dbi;
832                 $this->logtable = (!empty($DBParams['prefix']) ? $DBParams['prefix'] : '')."accesslog";
833             }
834         }
835         $this->entries = array();
836         $this->entries[] = new Request_AccessLogEntry($this);
837     }
838
839     function _do($cmd, &$arg) {
840         if ($this->entries)
841             for ($i=0; $i < count($this->entries);$i++)
842                 $this->entries[$i]->$cmd($arg);
843     }
844     function push(&$request)   { $this->_do('push',$request); }
845     function setSize($arg)     { $this->_do('setSize',$arg); }
846     function setStatus($arg)   { $this->_do('setStatus',$arg); }
847     function setDuration($arg) { $this->_do('setDuration',$arg); }
848
849     /**
850      * Read sequentially all previous entries from the beginning.
851      * while ($logentry = Request_AccessLogEntry::read()) ;
852      * For internal log analyzers: RecentReferrers, WikiAccessRestrictions
853      */
854     function read() {
855         return $this->logtable ? $this->read_sql() : $this->read_file();
856     }
857
858     /**
859      * Return iterator of referer items reverse sorted (latest first).
860      */
861     function get_referer($limit=15, $external_only=false) {
862         if ($external_only) { // see stdlin.php:isExternalReferrer()
863             $base = SERVER_URL;
864             $blen = strlen($base);
865         }
866         if (!empty($this->_dbi)) {
867             // check same hosts in referer and request and remove them
868             $ext_where = " AND LEFT(referer,$blen) <> ".$this->_dbi->quote($base)
869                 ." AND LEFT(referer,$blen) <> LEFT(CONCAT(".$this->_dbi->quote(SERVER_URL).",request_uri),$blen)";
870             return $this->_read_sql_query("(referer <>'' AND NOT(ISNULL(referer)))"
871                                           .($external_only ? $ext_where : '')
872                                           ." ORDER BY time_stamp DESC"
873                                           .($limit ? " LIMIT $limit" : ""));
874         } else {
875             $iter = new WikiDB_Array_generic_iter(0);
876             $logs =& $iter->_array;
877             while ($logentry = $this->read_file()) {
878                 if (!empty($logentry->referer)
879                     and (!$external_only or (substr($logentry->referer,0,$blen) != $base)))
880                 {
881                     $iter->_array[] = $logentry;
882                     if ($limit and count($logs) > $limit)
883                         array_shift($logs);
884                 }
885             }
886             $logs = array_reverse($logs);
887             $logs = array_slice($logs,0,min($limit,count($logs)));
888             return $iter;
889         }
890     }
891
892     /**
893      * Return iterator of matching host items reverse sorted (latest first).
894      */
895     function get_host($host, $since_minutes=20) {
896         if ($this->logtable) {
897             // mysql specific only:
898             return $this->read_sql("request_host=".$this->_dbi->quote($host)." AND time_stamp > ". (time()-$since_minutes*60) 
899                             ." ORDER BY time_stamp DESC");
900         } else {
901             $iter = new WikiDB_Array_generic_iter();
902             $logs =& $iter->_array;
903             $logentry = new Request_AccessLogEntry($this);
904             while ($logentry->read_file()) {
905                 if (!empty($logentry->referer)) {
906                     $iter->_array[] = $logentry;
907                     if ($limit and count($logs) > $limit)
908                         array_shift($logs);
909                     $logentry = new Request_AccessLogEntry($this);
910                 }
911             }
912             $logs = array_reverse($logs);
913             $logs = array_slice($logs,0,min($limit,count($logs)));
914             return $iter;
915         }
916     }
917
918     /**
919      * Read sequentially all previous entries from log file.
920      */
921     function read_file() {
922         global $request;
923         if ($this->logfile) $this->logfile = ACCESS_LOG; // support Request_AccessLog::read
924
925         if (empty($this->reader))       // start at the beginning
926             $this->reader = fopen($this->logfile, "r");
927         if ($s = fgets($this->reader)) {
928             $entry = new Request_AccessLogEntry($this);
929             if (preg_match('/^(\S+)\s(\S+)\s(\S+)\s\[(.+?)\] "([^"]+)" (\d+) (\d+) "([^"]*)" "([^"]*)"$/',$s,$m)) {
930                 list(,$entry->host, $entry->ident, $entry->user, $entry->time,
931                      $entry->request, $entry->status, $entry->size,
932                      $entry->referer, $entry->user_agent) = $m;
933             }
934             return $entry;
935         } else { // until the end
936             fclose($this->reader);
937             return false;
938         }
939     }
940     function _read_sql_query($where='') {
941         $dbh =& $GLOBALS['request']->_dbi;
942         $log_tbl =& $this->logtable;
943         return $dbh->genericSqlIter("SELECT *,request_uri as request,request_time as time,remote_user as user,"
944                                     ."remote_host as host,agent as user_agent"
945                                     ." FROM $log_tbl"
946                                     . ($where ? " WHERE $where" : ""));
947     }
948     function read_sql($where='') {
949         if (empty($this->sqliter))
950             $this->sqliter = $this->_read_sql_query($where);
951         return $this->sqliter->next();
952     }
953
954     /* done in request->finish() before the db is closed */
955     function write_sql() {
956         $dbh =& $GLOBALS['request']->_dbi;
957         if (isset($this->entries) and $dbh and $dbh->isOpen())
958             foreach ($this->entries as $entry) {
959                 $entry->write_sql();
960             }
961     }
962     /* done in the shutdown callback */
963     function write_file() {
964         if (isset($this->entries) and $this->logfile)
965             foreach ($this->entries as $entry) {
966                 $entry->write_file();
967             }
968         unset($this->entries);
969     }
970     /* in an ideal world... */
971     function write() {
972         if ($this->logfile) $this->write_file();
973         if ($this->logtable) $this->write_sql();
974         unset($this->entries);
975     }
976 }
977
978 class Request_AccessLogEntry
979 {
980     /**
981      * Constructor.
982      *
983      * The log entry will be automatically appended to the log file or 
984      * SQL table when the current request terminates.
985      *
986      * If you want to modify a Request_AccessLogEntry before it gets
987      * written (e.g. via the setStatus and setSize methods) you should
988      * use an '&' on the constructor, so that you're working with the
989      * original (rather than a copy) object.
990      *
991      * <pre>
992      *    $log_entry = & new Request_AccessLogEntry("/tmp/wiki_access_log");
993      *    $log_entry->setStatus(401);
994      *    $log_entry->push($request);
995      * </pre>
996      *
997      *
998      */
999     function Request_AccessLogEntry (&$accesslog) {
1000         $this->_accesslog = $accesslog;
1001         $this->logfile = $accesslog->logfile;
1002         $this->time = time();
1003         $this->status = 200;    // see setStatus()
1004         $this->size = 0;        // see setSize()
1005     }
1006
1007     /**
1008      * @param $request object  Request object for current request.
1009      */
1010     function push(&$request) {
1011         $this->host  = $request->get('REMOTE_HOST');
1012         $this->ident = $request->get('REMOTE_IDENT');
1013         if (!$this->ident)
1014             $this->ident = '-';
1015         $user = $request->getUser();
1016         if ($user->isAuthenticated())
1017             $this->user = $user->UserName();
1018         else
1019             $this->user = '-';
1020         $this->request = join(' ', array($request->get('REQUEST_METHOD'),
1021                                          $request->get('REQUEST_URI'),
1022                                          $request->get('SERVER_PROTOCOL')));
1023         $this->referer = (string) $request->get('HTTP_REFERER');
1024         $this->user_agent = (string) $request->get('HTTP_USER_AGENT');
1025     }
1026
1027     /**
1028      * Set result status code.
1029      *
1030      * @param $status integer  HTTP status code.
1031      */
1032     function setStatus ($status) {
1033         $this->status = $status;
1034     }
1035     
1036     /**
1037      * Set response size.
1038      *
1039      * @param $size integer
1040      */
1041     function setSize ($size=0) {
1042         $this->size = $size;
1043     }
1044     function setDuration ($seconds) {
1045         $this->duration = $seconds;
1046     }
1047     
1048     /**
1049      * Get time zone offset.
1050      *
1051      * This is a static member function.
1052      *
1053      * @param $time integer Unix timestamp (defaults to current time).
1054      * @return string Zone offset, e.g. "-0800" for PST.
1055      */
1056     function _zone_offset ($time = false) {
1057         if (!$time)
1058             $time = time();
1059         $offset = date("Z", $time);
1060         $negoffset = "";
1061         if ($offset < 0) {
1062             $negoffset = "-";
1063             $offset = -$offset;
1064         }
1065         $offhours = floor($offset / 3600);
1066         $offmins  = $offset / 60 - $offhours * 60;
1067         return sprintf("%s%02d%02d", $negoffset, $offhours, $offmins);
1068     }
1069
1070     /**
1071      * Format time in NCSA format.
1072      *
1073      * This is a static member function.
1074      *
1075      * @param $time integer Unix timestamp (defaults to current time).
1076      * @return string Formatted date & time.
1077      */
1078     function _ncsa_time($time = false) {
1079         if (!$time)
1080             $time = time();
1081         return date("d/M/Y:H:i:s", $time) .
1082             " " . $this->_zone_offset();
1083     }
1084
1085     function write() {
1086         if ($this->_accesslog->logfile) $this->write_file();
1087         if ($this->_accesslog->logtable) $this->write_sql();
1088     }
1089
1090     /**
1091      * Write entry to log file.
1092      */
1093     function write_file() {
1094         $entry = sprintf('%s %s %s [%s] "%s" %d %d "%s" "%s"',
1095                          $this->host, $this->ident, $this->user,
1096                          $this->_ncsa_time($this->time),
1097                          $this->request, $this->status, $this->size,
1098                          $this->referer, $this->user_agent);
1099         if (!empty($this->_accesslog->reader)) {
1100             fclose($this->_accesslog->reader);
1101             unset($this->_accesslog->reader);
1102         }
1103         //Error log doesn't provide locking.
1104         //error_log("$entry\n", 3, $this->logfile);
1105         // Alternate method
1106         if (($fp = fopen($this->logfile, "a"))) {
1107             flock($fp, LOCK_EX);
1108             fputs($fp, "$entry\n");
1109             fclose($fp);
1110         }
1111     }
1112
1113     /* This is better been done by apache mod_log_sql */
1114     /* If ACCESS_LOG_SQL & 2 we do write it by our own */
1115     function write_sql() {
1116         global $request;
1117         
1118         $dbh =& $request->_dbi;
1119         if ($dbh and $dbh->isOpen() and $this->_accesslog->logtable) {
1120             $log_tbl =& $this->_accesslog->logtable;
1121             if ($request->get('REQUEST_METHOD') == "POST") {
1122                 // strangely HTTP_POST_VARS doesn't contain all posted vars.
1123                 if (check_php_version(4,2))
1124                     $args = $_POST; // copy not ref. clone not needed on hashes
1125                 else
1126                     $args = $GLOBALS['HTTP_POST_VARS'];
1127                 // garble passwords
1128                 if (!empty($args['auth']['passwd']))    $args['auth']['passwd'] = '<not displayed>';
1129                 if (!empty($args['dbadmin']['passwd'])) $args['dbadmin']['passwd'] = '<not displayed>';
1130                 if (!empty($args['pref']['passwd']))    $args['pref']['passwd'] = '<not displayed>';
1131                 if (!empty($args['pref']['passwd2']))   $args['pref']['passwd2'] = '<not displayed>';
1132                 $this->request_args = substr(serialize($args),0,254); // if VARCHAR(255) is used.
1133             } else {
1134                 $this->request_args = $request->get('QUERY_STRING'); 
1135             }
1136             // duration problem: sprintf "%f" might use comma e.g. "100,201" in european locales
1137             $dbh->genericSqlQuery
1138                 (
1139                  sprintf("INSERT INTO $log_tbl"
1140                          . " (time_stamp,remote_host,remote_user,request_method,request_line,request_uri,"
1141                          .   "request_args,request_time,status,bytes_sent,referer,agent,request_duration)"
1142                          . " VALUES(%d,%s,%s,%s,%s,%s,%s,%s,%d,%d,%s,%s,'%s')",
1143                      $this->time,
1144                      $dbh->quote($this->host), $dbh->quote($this->user),
1145                      $dbh->quote($request->get('REQUEST_METHOD')), $dbh->quote($this->request), 
1146                      $dbh->quote($request->get('REQUEST_URI')), $dbh->quote($this->request_args),
1147                      $dbh->quote($this->_ncsa_time($this->time)), $this->status, $this->size,
1148                      $dbh->quote($this->referer),
1149                      $dbh->quote($this->user_agent),
1150                      $this->duration));
1151         }
1152     }
1153
1154 }
1155
1156 /**
1157  * Shutdown callback.
1158  *
1159  * @access private
1160  * @see Request_AccessLogEntry
1161  */
1162 function Request_AccessLogEntry_shutdown_function () {
1163     global $request;
1164     
1165     if (isset($request->_accesslog->entries) and $request->_accesslog->logfile)
1166         foreach ($request->_accesslog->entries as $entry) {
1167             $entry->write_file();
1168         }
1169     unset($request->_accesslog->entries);
1170 }
1171
1172
1173 class HTTP_ETag {
1174     function HTTP_ETag($val, $is_weak=false) {
1175         $this->_val = wikihash($val);
1176         $this->_weak = $is_weak;
1177     }
1178
1179     /** Comparison
1180      *
1181      * Strong comparison: If either (or both) tag is weak, they
1182      *  are not equal.
1183      */
1184     function equals($that, $strong_match=false) {
1185         if ($this->_val != $that->_val)
1186             return false;
1187         if ($strong_match and ($this->_weak or $that->_weak))
1188             return false;
1189         return true;
1190     }
1191
1192
1193     function asString() {
1194         $quoted = '"' . addslashes($this->_val) . '"';
1195         return $this->_weak ? "W/$quoted" : $quoted;
1196     }
1197
1198     /** Parse tag from header.
1199      *
1200      * This is a static member function.
1201      */
1202     function parse($strval) {
1203         if (!preg_match(':^(W/)?"(.+)"$:i', trim($strval), $m))
1204             return false;       // parse failed
1205         list(,$weak,$str) = $m;
1206         return new HTTP_ETag(stripslashes($str), $weak);
1207     }
1208
1209     function matches($taglist, $strong_match=false) {
1210         $taglist = trim($taglist);
1211
1212         if ($taglist == '*') {
1213             if ($strong_match)
1214                 return ! $this->_weak;
1215             else
1216                 return true;
1217         }
1218
1219         while (preg_match('@^(W/)?"((?:\\\\.|[^"])*)"\s*,?\s*@i',
1220                           $taglist, $m)) {
1221             list($match, $weak, $str) = $m;
1222             $taglist = substr($taglist, strlen($match));
1223             $tag = new HTTP_ETag(stripslashes($str), $weak);
1224             if ($this->equals($tag, $strong_match)) {
1225                 return true;
1226             }
1227         }
1228         return false;
1229     }
1230 }
1231
1232 // Possible results from the HTTP_ValidatorSet::_check*() methods.
1233 // (Higher numerical values take precedence.)
1234 define ('_HTTP_VAL_PASS', 0);           // Test is irrelevant
1235 define ('_HTTP_VAL_NOT_MODIFIED', 1);   // Test passed, content not changed
1236 define ('_HTTP_VAL_MODIFIED', 2);       // Test failed, content changed
1237 define ('_HTTP_VAL_FAILED', 3);         // Precondition failed.
1238
1239 class HTTP_ValidatorSet {
1240     function HTTP_ValidatorSet($validators) {
1241         $this->_mtime = $this->_weak = false;
1242         $this->_tag = array();
1243         
1244         foreach ($validators as $key => $val) {
1245             if ($key == '%mtime') {
1246                 $this->_mtime = $val;
1247             }
1248             elseif ($key == '%weak') {
1249                 if ($val)
1250                     $this->_weak = true;
1251             }
1252             else {
1253                 $this->_tag[$key] = $val;
1254             }
1255         }
1256     }
1257
1258     function append($that) {
1259         if (is_array($that))
1260             $that = new HTTP_ValidatorSet($that);
1261
1262         // Pick the most recent mtime
1263         if (isset($that->_mtime))
1264             if (!isset($this->_mtime) || $that->_mtime > $this->_mtime)
1265                 $this->_mtime = $that->_mtime;
1266
1267         // If either is weak, we're weak
1268         if (!empty($that->_weak))
1269             $this->_weak = true;
1270         if (is_array($this->_tag))
1271             $this->_tag = array_merge($this->_tag, $that->_tag);
1272         else
1273             $this->_tag = $that->_tag;
1274     }
1275
1276     function getETag() {
1277         if (! $this->_tag)
1278             return false;
1279         return new HTTP_ETag($this->_tag, $this->_weak);
1280     }
1281
1282     function getModificationTime() {
1283         return $this->_mtime;
1284     }
1285     
1286     function checkConditionalRequest (&$request) {
1287         $result = max($this->_checkIfUnmodifiedSince($request),
1288                       $this->_checkIfModifiedSince($request),
1289                       $this->_checkIfMatch($request),
1290                       $this->_checkIfNoneMatch($request));
1291
1292         if ($result == _HTTP_VAL_PASS || $result == _HTTP_VAL_MODIFIED)
1293             return false;       // "please proceed with normal processing"
1294         elseif ($result == _HTTP_VAL_FAILED)
1295             return 412;         // "412 Precondition Failed"
1296         elseif ($result == _HTTP_VAL_NOT_MODIFIED)
1297             return 304;         // "304 Not Modified"
1298
1299         trigger_error("Ack, shouldn't get here", E_USER_ERROR);
1300         return false;
1301     }
1302
1303     function _checkIfUnmodifiedSince(&$request) {
1304         if ($this->_mtime !== false) {
1305             $since = ParseRfc1123DateTime($request->get("HTTP_IF_UNMODIFIED_SINCE"));
1306             if ($since !== false && $this->_mtime > $since)
1307                 return _HTTP_VAL_FAILED;
1308         }
1309         return _HTTP_VAL_PASS;
1310     }
1311
1312     function _checkIfModifiedSince(&$request) {
1313         if ($this->_mtime !== false and $request->isGetOrHead()) {
1314             $since = ParseRfc1123DateTime($request->get("HTTP_IF_MODIFIED_SINCE"));
1315             if ($since !== false) {
1316                 if ($this->_mtime <= $since)
1317                     return _HTTP_VAL_NOT_MODIFIED;
1318                 return _HTTP_VAL_MODIFIED;
1319             }
1320         }
1321         return _HTTP_VAL_PASS;
1322     }
1323
1324     function _checkIfMatch(&$request) {
1325         if ($this->_tag && ($taglist = $request->get("HTTP_IF_MATCH"))) {
1326             $tag = $this->getETag();
1327             if (!$tag->matches($taglist, 'strong'))
1328                 return _HTTP_VAL_FAILED;
1329         }
1330         return _HTTP_VAL_PASS;
1331     }
1332
1333     function _checkIfNoneMatch(&$request) {
1334         if ($this->_tag && ($taglist = $request->get("HTTP_IF_NONE_MATCH"))) {
1335             $tag = $this->getETag();
1336             $strong_compare = ! $request->isGetOrHead();
1337             if ($taglist) {
1338                 if ($tag->matches($taglist, $strong_compare)) {
1339                     if ($request->isGetOrHead())
1340                         return _HTTP_VAL_NOT_MODIFIED;
1341                     else
1342                         return _HTTP_VAL_FAILED;
1343                 }
1344                 return _HTTP_VAL_MODIFIED;
1345             }
1346         }
1347         return _HTTP_VAL_PASS;
1348     }
1349 }
1350
1351
1352 // $Log: not supported by cvs2svn $
1353 // Revision 1.103  2006/04/15 12:23:32  rurban
1354 // silence $this->_is_buffering_output warning
1355 //
1356 // Revision 1.102  2006/03/19 15:01:00  rurban
1357 // sf.net patch #1333957 by Matt Brown: Authentication cookie identical across all wikis on a host
1358 //
1359 // Revision 1.101  2006/03/07 20:45:43  rurban
1360 // wikihash for php-5.1
1361 //
1362 // Revision 1.100  2006/01/17 18:57:09  uckelman
1363 // _accesslog->logtable is not set when using non-SQL logging; check should
1364 //  be isset to avoid a PHP warning
1365 //
1366 // Revision 1.99  2005/09/18 16:01:09  rurban
1367 // trick to send the correct gzipped Content-Length
1368 //
1369 // Revision 1.98  2005/09/18 15:15:53  rurban
1370 // add a proper Content-Encoding: gzip if compressed, and omit Content-Length then.
1371 //
1372 // Revision 1.97  2005/09/14 05:58:17  rurban
1373 // protect against Content-Length if headers_sent(), fixed writing unwanted accesslog sql entries
1374 //
1375 // Revision 1.96  2005/08/07 10:52:43  rurban
1376 // stricter error handling: dba errors are fatal, display errors on Request->finish or session_close
1377 //
1378 // Revision 1.95  2005/08/07 10:09:33  rurban
1379 // set _COOKIE also
1380 //
1381 // Revision 1.94  2005/08/07 09:14:39  rurban
1382 // fix comments
1383 //
1384 // Revision 1.93  2005/08/06 14:31:10  rurban
1385 // ensure absolute uploads path
1386 //
1387 // Revision 1.92  2005/05/14 07:22:47  rurban
1388 // remove mysql specific INSERT DELAYED
1389 //
1390 // Revision 1.91  2005/04/11 19:40:14  rurban
1391 // Simplify upload. See https://sourceforge.net/forum/message.php?msg_id=3093651
1392 // Improve UpLoad warnings.
1393 // Move auth check before upload.
1394 //
1395 // Revision 1.90  2005/02/26 18:30:01  rurban
1396 // update (C)
1397 //
1398 // Revision 1.89  2005/02/04 10:38:36  rurban
1399 // do not log passwords! Thanks to Charles Corrigan
1400 //
1401 // Revision 1.88  2005/01/25 07:00:23  rurban
1402 // fix redirect,
1403 //
1404 // Revision 1.87  2005/01/08 21:27:45  rurban
1405 // Prevent from Overlarge session data crash
1406 //
1407 // Revision 1.86  2005/01/04 20:26:34  rurban
1408 // honor DISABLE_HTTP_REDIRECT, do not gzip the redirect template, flush it
1409 //
1410 // Revision 1.85  2004/12/26 17:08:36  rurban
1411 // php5 fixes: case-sensitivity, no & new
1412 //
1413 // Revision 1.84  2004/12/17 16:37:30  rurban
1414 // avoid warning
1415 //
1416 // Revision 1.83  2004/12/10 02:36:43  rurban
1417 // More help with the new native xmlrpc lib. no warnings, no user cookie on xmlrpc.
1418 //
1419 // Revision 1.82  2004/12/06 19:49:55  rurban
1420 // enable action=remove which is undoable and seeable in RecentChanges: ADODB ony for now.
1421 // renamed delete_page to purge_page.
1422 // enable action=edit&version=-1 to force creation of a new version.
1423 // added BABYCART_PATH config
1424 // fixed magiqc in adodb.inc.php
1425 // and some more docs
1426 //
1427 // Revision 1.81  2004/11/27 14:39:04  rurban
1428 // simpified regex search architecture:
1429 //   no db specific node methods anymore,
1430 //   new sql() method for each node
1431 //   parallel to regexp() (which returns pcre)
1432 //   regex types bitmasked (op's not yet)
1433 // new regex=sql
1434 // clarified WikiDB::quote() backend methods:
1435 //   ->quote() adds surrounsing quotes
1436 //   ->qstr() (new method) assumes strings and adds no quotes! (in contrast to ADODB)
1437 //   pear and adodb have now unified quote methods for all generic queries.
1438 //
1439 // Revision 1.80  2004/11/21 11:59:16  rurban
1440 // remove final \n to be ob_cache independent
1441 //
1442 // Revision 1.79  2004/11/11 18:29:44  rurban
1443 // (write_sql) isOpen really is useless in non-SQL, do more explicit check
1444 //
1445 // Revision 1.78  2004/11/10 15:29:20  rurban
1446 // * requires newer Pear_DB (as the internal one): quote() uses now escapeSimple for strings
1447 // * ACCESS_LOG_SQL: fix cause request not yet initialized
1448 // * WikiDB: moved SQL specific methods upwards
1449 // * new Pear_DB quoting: same as ADODB and as newer Pear_DB.
1450 //   fixes all around: WikiGroup, WikiUserNew SQL methods, SQL logging
1451 //
1452 // Revision 1.77  2004/11/09 17:11:04  rurban
1453 // * revert to the wikidb ref passing. there's no memory abuse there.
1454 // * use new wikidb->_cache->_id_cache[] instead of wikidb->_iwpcache, to effectively
1455 //   store page ids with getPageLinks (GleanDescription) of all existing pages, which
1456 //   are also needed at the rendering for linkExistingWikiWord().
1457 //   pass options to pageiterator.
1458 //   use this cache also for _get_pageid()
1459 //   This saves about 8 SELECT count per page (num all pagelinks).
1460 // * fix passing of all page fields to the pageiterator.
1461 // * fix overlarge session data which got broken with the latest ACCESS_LOG_SQL changes
1462 //
1463 // Revision 1.76  2004/11/09 08:15:18  rurban
1464 // fix ADODB quoting style
1465 //
1466 // Revision 1.75  2004/11/07 18:34:28  rurban
1467 // more logging fixes
1468 //
1469 // Revision 1.74  2004/11/07 16:02:51  rurban
1470 // new sql access log (for spam prevention), and restructured access log class
1471 // dbh->quote (generic)
1472 // pear_db: mysql specific parts seperated (using replace)
1473 //
1474 // Revision 1.73  2004/11/06 04:51:25  rurban
1475 // readable ACCESS_LOG support: RecentReferrers, WikiAccessRestrictions
1476 //
1477 // Revision 1.72  2004/11/01 10:43:55  rurban
1478 // seperate PassUser methods into seperate dir (memory usage)
1479 // fix WikiUser (old) overlarge data session
1480 // remove wikidb arg from various page class methods, use global ->_dbi instead
1481 // ...
1482 //
1483 // Revision 1.71  2004/10/22 09:20:36  rurban
1484 // fix for USECACHE=false
1485 //
1486 // Revision 1.70  2004/10/21 19:59:18  rurban
1487 // Patch #991494 (ppo): Avoid notice in PHP >= 4.3.3 if session already started
1488 //
1489 // Revision 1.69  2004/10/21 19:00:37  rurban
1490 // upload errmsgs by Shilad Sen.
1491 // chunkOutput support: flush the buffer piecewise (dumphtml, large pagelists)
1492 //   doesn't gain much because ob_end_clean() doesn't release its
1493 //   memory properly yet.
1494 //
1495 // Revision 1.68  2004/10/12 13:13:19  rurban
1496 // php5 compatibility (5.0.1 ok)
1497 //
1498 // Revision 1.67  2004/09/25 18:56:54  rurban
1499 // make start_debug logic work
1500 //
1501 // Revision 1.66  2004/09/25 16:24:52  rurban
1502 // dont compress on debugging
1503 //
1504 // Revision 1.65  2004/09/17 14:13:49  rurban
1505 // We check for the client Accept-Encoding: "gzip" presence also
1506 // This should eliminate a lot or reported problems.
1507 //
1508 // Note that this doesn#t fix RSS ssues:
1509 // Most RSS clients are NOT(!) application/xml gzip compatible yet.
1510 // Even if they are sending the accept-encoding gzip header!
1511 // wget is, Mozilla, and MSIE no.
1512 // Of the RSS readers only MagpieRSS 0.5.2 is. http://www.rssgov.com/rssparsers.html
1513 //
1514 // Revision 1.64  2004/09/17 13:32:36  rurban
1515 // Disable server-side gzip encoding for RSS (RDF encoding), even if the client says it
1516 // supports it. Mozilla has this error, wget works fine. IE not checked.
1517 //
1518 // Revision 1.63  2004/07/01 09:29:40  rurban
1519 // fixed another DbSession crash: wrong WikiGroup vars
1520 //
1521 // Revision 1.62  2004/06/27 10:26:02  rurban
1522 // oci8 patch by Philippe Vanhaesendonck + some ADODB notes+fixes
1523 //
1524 // Revision 1.61  2004/06/25 14:29:17  rurban
1525 // WikiGroup refactoring:
1526 //   global group attached to user, code for not_current user.
1527 //   improved helpers for special groups (avoid double invocations)
1528 // new experimental config option ENABLE_XHTML_XML (fails with IE, and document.write())
1529 // fixed a XHTML validation error on userprefs.tmpl
1530 //
1531 // Revision 1.60  2004/06/19 11:51:13  rurban
1532 // CACHE_CONTROL: NONE => NO_CACHE
1533 //
1534 // Revision 1.59  2004/06/13 11:34:22  rurban
1535 // fixed bug #969532 (space in uploaded filenames)
1536 // improved upload error messages
1537 //
1538 // Revision 1.58  2004/06/04 20:32:53  rurban
1539 // Several locale related improvements suggested by Pierrick Meignen
1540 // LDAP fix by John Cole
1541 // reanable admin check without ENABLE_PAGEPERM in the admin plugins
1542 //
1543 // Revision 1.57  2004/06/03 18:54:25  rurban
1544 // fixed "lost level in session" warning, now that signout sets level = 0 (before -1)
1545 //
1546 // Revision 1.56  2004/05/17 17:43:29  rurban
1547 // CGI: no PATH_INFO fix
1548 //
1549 // Revision 1.55  2004/05/15 18:31:00  rurban
1550 // some action=pdf Request fixes: With MSIE it works now. Now the work with the page formatting begins.
1551 //
1552 // Revision 1.54  2004/05/04 22:34:25  rurban
1553 // more pdf support
1554 //
1555 // Revision 1.53  2004/05/03 21:57:47  rurban
1556 // locale updates: we previously lost some words because of wrong strings in
1557 //   PhotoAlbum, german rewording.
1558 // fixed $_SESSION registering (lost session vars, esp. prefs)
1559 // fixed ending slash in listAvailableLanguages/Themes
1560 //
1561 // Revision 1.52  2004/05/03 13:16:47  rurban
1562 // fixed UserPreferences update, esp for boolean and int
1563 //
1564 // Revision 1.51  2004/05/02 21:26:38  rurban
1565 // limit user session data (HomePageHandle and auth_dbi have to invalidated anyway)
1566 //   because they will not survive db sessions, if too large.
1567 // extended action=upgrade
1568 // some WikiTranslation button work
1569 // revert WIKIAUTH_UNOBTAINABLE (need it for main.php)
1570 // some temp. session debug statements
1571 //
1572 // Revision 1.50  2004/04/29 19:39:44  rurban
1573 // special support for formatted plugins (one-liners)
1574 //   like <small><plugin BlaBla ></small>
1575 // iter->asArray() helper for PopularNearby
1576 // db_session for older php's (no &func() allowed)
1577 //
1578 // Revision 1.49  2004/04/26 20:44:34  rurban
1579 // locking table specific for better databases
1580 //
1581 // Revision 1.48  2004/04/13 09:13:50  rurban
1582 // sf.net bug #933183 and http://bugs.php.net/17557
1583 // disable ob_gzhandler if apache_note cannot be used.
1584 //   (conservative until we find why)
1585 //
1586 // Revision 1.47  2004/04/02 15:06:55  rurban
1587 // fixed a nasty ADODB_mysql session update bug
1588 // improved UserPreferences layout (tabled hints)
1589 // fixed UserPreferences auth handling
1590 // improved auth stability
1591 // improved old cookie handling: fixed deletion of old cookies with paths
1592 //
1593 // Revision 1.46  2004/03/30 02:14:03  rurban
1594 // fixed yet another Prefs bug
1595 // added generic PearDb_iter
1596 // $request->appendValidators no so strict as before
1597 // added some box plugin methods
1598 // PageList commalist for condensed output
1599 //
1600 // Revision 1.45  2004/03/24 19:39:02  rurban
1601 // php5 workaround code (plus some interim debugging code in XmlElement)
1602 //   php5 doesn't work yet with the current XmlElement class constructors,
1603 //   WikiUserNew does work better than php4.
1604 // rewrote WikiUserNew user upgrading to ease php5 update
1605 // fixed pref handling in WikiUserNew
1606 // added Email Notification
1607 // added simple Email verification
1608 // removed emailVerify userpref subclass: just a email property
1609 // changed pref binary storage layout: numarray => hash of non default values
1610 // print optimize message only if really done.
1611 // forced new cookie policy: delete pref cookies, use only WIKI_ID as plain string.
1612 //   prefs should be stored in db or homepage, besides the current session.
1613 //
1614 // Revision 1.44  2004/03/14 16:26:22  rurban
1615 // copyright line
1616 //
1617 // Revision 1.43  2004/03/12 20:59:17  rurban
1618 // important cookie fix by Konstantin Zadorozhny
1619 // new editpage feature: JS_SEARCHREPLACE
1620 //
1621 // Revision 1.42  2004/03/10 15:38:48  rurban
1622 // store current user->page and ->action in session for WhoIsOnline
1623 // better WhoIsOnline icon
1624 // fixed WhoIsOnline warnings
1625 //
1626 // Revision 1.41  2004/02/27 01:25:14  rurban
1627 // Workarounds for upload handling
1628 //
1629 // Revision 1.40  2004/02/26 01:39:51  rurban
1630 // safer code
1631 //
1632 // Revision 1.39  2004/02/24 15:14:57  rurban
1633 // fixed action=upload problems on Win32, and remove Merge Edit buttons: file does not exist anymore
1634 //
1635 // Revision 1.38  2004/01/25 10:26:02  rurban
1636 // fixed bug [ 541193 ] HTTP_SERVER_VARS are Apache specific
1637 // http://sourceforge.net/tracker/index.php?func=detail&aid=541193&group_id=6121&atid=106121
1638 // CGI and other servers than apache populate _ENV and not _SERVER
1639 //
1640 // Revision 1.37  2003/12/26 06:41:16  carstenklapp
1641 // Bugfix: Try to defer OS errors about session.save_path and ACCESS_LOG,
1642 // so they don't prevent IE from partially (or not at all) rendering the
1643 // page. This should help a little for the IE user who encounters trouble
1644 // when setting up a new PhpWiki for the first time.
1645 //
1646
1647 // Local Variables:
1648 // mode: php
1649 // tab-width: 8
1650 // c-basic-offset: 4
1651 // c-hanging-comment-ender-p: nil
1652 // indent-tabs-mode: nil
1653 // End:   
1654 ?>