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