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