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