]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/Request.php
rcs_id no longer makes sense with Subversion global version number
[SourceForge/phpwiki.git] / lib / Request.php
1 <?php // -*-php-*-
2 // rcs_id('$Id$');
3 /*
4  * Copyright (C) 2002,2004,2005,2006,2009 $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')) $compress = false;
348         if ($this->getArg('nocache'))
349             $compress = false;
350         
351         // Should we compress even when apache_note is not available?
352         // sf.net bug #933183 and http://bugs.php.net/17557
353         // This effectively eliminates CGI, but all other servers also. hmm.
354         if ($compress 
355             and (!function_exists('ob_gzhandler') 
356                  or !function_exists('apache_note'))) 
357             $compress = false;
358             
359         // "output handler 'ob_gzhandler' cannot be used twice"
360         // http://www.php.net/ob_gzhandler
361         if ($compress and ini_get("zlib.output_compression"))
362             $compress = false;
363
364         // New: we check for the client Accept-Encoding: "gzip" presence also
365         // This should eliminate a lot or reported problems.
366         if ($compress
367             and (!$this->get("HTTP_ACCEPT_ENCODING")
368                  or !strstr($this->get("HTTP_ACCEPT_ENCODING"), "gzip")))
369             $compress = false;
370
371         // Most RSS clients are NOT(!) application/xml gzip compatible yet. 
372         // Even if they are sending the accept-encoding gzip header!
373         // wget is, Mozilla, and MSIE no.
374         // Of the RSS readers only MagpieRSS 0.5.2 is. http://www.rssgov.com/rssparsers.html
375         // See also http://phpwiki.sourceforge.net/phpwiki/KnownBugs
376         if ($compress 
377             and $this->getArg('format') 
378             and strstr($this->getArg('format'), 'rss'))
379             $compress = false;
380
381         if ($compress) {
382             ob_start('phpwiki_gzhandler');
383             
384             // TODO: dont send a length or get the gzip'ed data length.
385             $this->_is_compressing_output = true; 
386             header("Content-Encoding: gzip");
387             /*
388              * Attempt to prevent Apache from doing the dreaded double-gzip.
389              *
390              * It would be better if we could detect when apache was going
391              * to zip for us, and then let it ... but I have yet to figure
392              * out how to do that.
393              */
394             if (function_exists('apache_note'))
395                 @apache_note('no-gzip', 1);
396         }
397         else {
398             // Now we alway buffer output.
399             // This is so we can set HTTP headers (e.g. for redirect)
400             // at any point.
401             // FIXME: change the name of this method.
402             ob_start();
403             $this->_is_compressing_output = false;
404         }
405         $this->_is_buffering_output = true;
406         $this->_ob_get_length = 0;
407     }
408
409     function discardOutput() {
410         if (!empty($this->_is_buffering_output)) {
411             if (ob_get_length()) ob_clean();
412             $this->_is_buffering_output = false;
413         } else {
414             trigger_error("Not buffering output", E_USER_NOTICE);
415         }
416     }
417
418     /** 
419      * Longer texts need too much memory on tiny or memory-limit=8MB systems.
420      * We might want to flush our buffer and restart again.
421      * (This would be fine if php would release its memory)
422      * Note that this must not be called inside Template expansion or other 
423      * sections with ob_buffering.
424      */
425     function chunkOutput() {
426         if (!empty($this->_is_buffering_output) 
427             or 
428             (function_exists('ob_get_level') and @ob_get_level())) 
429         {
430             $this->_do_chunked_output = true;
431             if (empty($this->_ob_get_length)) $this->_ob_get_length = 0;
432             $this->_ob_get_length += ob_get_length();
433             while (@ob_end_flush());
434             @ob_end_clean();
435             ob_start();
436         }
437     }
438
439     function finish() {
440         $this->_finishing = true;
441         if (!empty($this->_accesslog)) {
442             $this->_accesslog->push($this);
443             if (empty($this->_do_chunked_output) and empty($this->_ob_get_length))
444                 $this->_ob_get_length = ob_get_length();
445             $this->_accesslog->setSize($this->_ob_get_length);
446             global $RUNTIMER;
447             if ($RUNTIMER) $this->_accesslog->setDuration($RUNTIMER->getTime());
448             // sql logging must be done before the db is closed.
449             if (isset($this->_accesslog->logtable))
450                 $this->_accesslog->write_sql();
451         }
452         
453         if (!empty($this->_is_buffering_output)) {
454             /* This cannot work because it might destroy xml markup */
455             /*
456             if (0 and $GLOBALS['SearchHighLightQuery'] and check_php_version(4,2)) {
457                 $html = str_replace($GLOBALS['SearchHighLightQuery'],
458                                     '<span class="search-term">'.$GLOBALS['SearchHighLightQuery'].'</span>',
459                                     ob_get_contents());
460                 ob_clean();
461                 header(sprintf("Content-Length: %d", strlen($html)));
462                 echo $html;
463             } else {
464             */
465             // if _is_compressing_output then ob_get_length() returns 
466             // the uncompressed length, not the gzip'ed as required.
467             if (!headers_sent() and !$this->_is_compressing_output) {
468                 // php url-rewriting miscalculates the ob length. fixes bug #1376007
469                 if (ini_get('use_trans_sid') == 'off') {
470                     if (empty($this->_do_chunked_output)) {
471                         $this->_ob_get_length = ob_get_length();
472                     }
473                     header(sprintf("Content-Length: %d", $this->_ob_get_length));
474                 }
475             }
476             $this->_is_buffering_output = false;
477             ob_end_flush();
478         } elseif (function_exists('ob_get_level') and @ob_get_level()) {
479             ob_end_flush();
480         }
481         session_write_close();
482         if (!empty($this->_dbi)) {
483             $this->_dbi->close();
484             unset($this->_dbi);
485         }
486
487         exit;
488     }
489
490     function getSessionVar($key) {
491         return $this->session->get($key);
492     }
493     function setSessionVar($key, $val) {
494         if ($key == 'wiki_user') {
495             if (empty($val->page))
496                 $val->page = $this->getArg('pagename');
497             if (empty($val->action))
498                 $val->action = $this->getArg('action');
499             // avoid recursive objects and session resource handles
500             // avoid overlarge session data (max 4000 byte!)
501             if (isset($val->_group)) {
502                 unset($val->_group->_request);
503                 unset($val->_group->user);
504             }
505             if (ENABLE_USER_NEW) {
506                 unset($val->_HomePagehandle);
507                 unset($val->_auth_dbi);
508             } else {
509                 unset($val->_dbi);
510                 unset($val->_authdbi);
511                 unset($val->_homepage);
512                 unset($val->_request);
513             }
514         }
515         return $this->session->set($key, $val);
516     }
517     function deleteSessionVar($key) {
518         return $this->session->delete($key);
519     }
520
521     function getCookieVar($key) {
522         return $this->cookies->get($key);
523     }
524     function setCookieVar($key, $val, $lifetime_in_days = false, $path = false) {
525         return $this->cookies->set($key, $val, $lifetime_in_days, $path);
526     }
527     function deleteCookieVar($key) {
528         return $this->cookies->delete($key);
529     }
530     
531     function getUploadedFile($key) {
532         return Request_UploadedFile::getUploadedFile($key);
533     }
534     
535
536     function _fix_magic_quotes_gpc() {
537         $needs_fix = array('HTTP_POST_VARS',
538                            'HTTP_GET_VARS',
539                            'HTTP_COOKIE_VARS',
540                            'HTTP_SERVER_VARS',
541                            'HTTP_POST_FILES');
542         
543         // Fix magic quotes.
544         if (get_magic_quotes_gpc()) {
545             foreach ($needs_fix as $vars)
546                 $this->_stripslashes($GLOBALS[$vars]);
547         }
548     }
549
550     function _stripslashes(&$var) {
551         if (is_array($var)) {
552             foreach ($var as $key => $val)
553                 $this->_stripslashes($var[$key]);
554         }
555         elseif (is_string($var))
556             $var = stripslashes($var);
557     }
558     
559     function _fix_multipart_form_data () {
560         if (preg_match('|^multipart/form-data|', $this->get('CONTENT_TYPE')))
561             $this->_strip_leading_nl($GLOBALS['HTTP_POST_VARS']);
562     }
563     
564     function _strip_leading_nl(&$var) {
565         if (is_array($var)) {
566             foreach ($var as $key => $val)
567                 $this->_strip_leading_nl($var[$key]);
568         }
569         elseif (is_string($var))
570             $var = preg_replace('|^\r?\n?|', '', $var);
571     }
572 }
573
574 class Request_SessionVars {
575     function Request_SessionVars() {
576         // Prevent cacheing problems with IE 5
577         session_cache_limiter('none');
578                                         
579         // Avoid to get a notice if session is already started,
580         // for example if session.auto_start is activated
581         if (!session_id())
582             session_start();
583     }
584     
585     function get($key) {
586         $vars = &$GLOBALS['HTTP_SESSION_VARS'];
587         if (isset($vars[$key]))
588             return $vars[$key];
589         if (isset($_SESSION) and isset($_SESSION[$key])) // php-5.2
590             return $_SESSION[$key];
591         return false;
592     }
593     
594     function set($key, $val) {
595         $vars = &$GLOBALS['HTTP_SESSION_VARS'];
596         if (!function_usable('get_cfg_var') or get_cfg_var('register_globals')) {
597             // This is funky but necessary, at least in some PHP's
598             $GLOBALS[$key] = $val;
599         }
600         $vars[$key] = $val;
601         if (isset($_SESSION)) // php-5.2
602             $_SESSION[$key] = $val;
603         session_register($key);
604     }
605     
606     function delete($key) {
607         $vars = &$GLOBALS['HTTP_SESSION_VARS'];
608         if (!function_usable('ini_get') or ini_get('register_globals'))
609             unset($GLOBALS[$key]);
610         if (DEBUG) trigger_error("delete session $key", E_USER_WARNING);
611         unset($vars[$key]);
612         session_unregister($key);
613     }
614 }
615
616 class Request_CookieVars {
617     
618     function get($key) {
619         $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
620         if (isset($vars[$key])) {
621             @$decode = base64_decode($vars[$key]);
622             if (strlen($decode) > 3 and substr($decode,1,1) == ':') {
623               @$val = unserialize($decode);
624               if (!empty($val))
625                   return $val;
626             }
627             @$val = urldecode($vars[$key]);
628             if (!empty($val))
629                 return $val;
630         }
631         return false;
632     }
633
634     function get_old($key) {
635         $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
636         if (isset($vars[$key])) {
637             @$decode = base64_decode($vars[$key]);
638             if (strlen($decode) > 3 and substr($decode,1,1) == ':') {
639               @$val = unserialize($decode);
640               if (!empty($val))
641                 return $val;
642             }
643             @$val = unserialize($vars[$key]);
644             if (!empty($val))
645                 return $val;
646             @$val = $vars[$key];
647             if (!empty($val))
648                 return $val;
649         }
650         return false;
651     }
652
653     function set($key, $val, $persist_days = false, $path = false) {
654         // if already defined, ignore
655         if (defined('MAIN_setUser') and $key = getCookieName()) return;
656         if (defined('WIKI_XMLRPC') and WIKI_XMLRPC) return;
657
658         $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
659         if (is_numeric($persist_days)) {
660             $expires = time() + (24 * 3600) * $persist_days;
661         }
662         else {
663             $expires = 0;
664         }
665         if (is_array($val) or is_object($val))
666             $packedval = base64_encode(serialize($val));
667         else
668             $packedval = urlencode($val);
669         $vars[$key] = $packedval;
670         @$_COOKIE[$key] = $packedval;
671         if ($path)
672             @setcookie($key, $packedval, $expires, $path);
673         else
674             @setcookie($key, $packedval, $expires);
675     }
676     
677     function delete($key) {
678         static $deleted = array();
679         if (isset($deleted[$key])) return;
680         if (defined('WIKI_XMLRPC') and WIKI_XMLRPC) return;
681         
682         $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
683         if (!defined('COOKIE_DOMAIN'))
684             @setcookie($key, '', 0);
685         else    
686             @setcookie($key, '', 0, COOKIE_DOMAIN);
687         unset($GLOBALS['HTTP_COOKIE_VARS'][$key]);
688         unset($_COOKIE[$key]);
689         $deleted[$key] = 1;
690     }
691 }
692
693 /* Win32 Note:
694    [\winnt\php.ini]
695    You must set "upload_tmp_dir" = "/tmp/" or "C:/tmp/"
696    Best on the same drive as apache, with forward slashes 
697    and with ending slash!
698    Otherwise "\\" => "" and the uploaded file will not be found.
699 */
700 class Request_UploadedFile {
701     function getUploadedFile($postname) {
702         global $HTTP_POST_FILES;
703
704         // Against php5 with !ini_get('register-long-arrays'). See Bug #1180115
705         if (empty($HTTP_POST_FILES) and !empty($_FILES))
706             $HTTP_POST_FILES =& $_FILES;
707         if (!isset($HTTP_POST_FILES[$postname]))
708             return false;
709         
710         $fileinfo =& $HTTP_POST_FILES[$postname];
711         if ($fileinfo['error']) {
712             // See https://sourceforge.net/forum/message.php?msg_id=3093651
713             $err = (int) $fileinfo['error'];
714             // errmsgs by Shilad Sen
715             switch ($err) {
716             case 1:
717                 trigger_error(_("Upload error: file too big"), E_USER_WARNING);
718                 break;
719             case 2:
720                 trigger_error(_("Upload error: file too big"), E_USER_WARNING);
721                 break;
722             case 3:
723                 trigger_error(_("Upload error: file only partially received"), E_USER_WARNING);
724                 break;
725             case 4:
726                 trigger_error(_("Upload error: no file selected"), E_USER_WARNING);
727                 break;
728             default:
729                 trigger_error(_("Upload error: unknown error #") . $err, E_USER_WARNING);
730             }
731             return false;
732         }
733
734         // With windows/php 4.2.1 is_uploaded_file() always returns false.
735         // Be sure that upload_tmp_dir ends with a slash!
736         if (!is_uploaded_file($fileinfo['tmp_name'])) {
737             if (isWindows()) {
738                 if (!$tmp_file = get_cfg_var('upload_tmp_dir')) {
739                     $tmp_file = dirname(tempnam('', ''));
740                 }
741                 $tmp_file .= '/' . basename($fileinfo['tmp_name']);
742                 /* ending slash in php.ini upload_tmp_dir is required. */
743                 if (realpath(ereg_replace('/+', '/', $tmp_file)) != realpath($fileinfo['tmp_name'])) {
744                     trigger_error(sprintf("Uploaded tmpfile illegal: %s != %s.",$tmp_file, $fileinfo['tmp_name']).
745                                   "\n".
746                                   "Probably illegal TEMP environment or upload_tmp_dir setting. ".
747                                   "Esp. on WINDOWS be sure to set upload_tmp_dir in php.ini to use forward slashes and ".
748                                   "end with a slash. upload_tmp_dir = \"C:/WINDOWS/TEMP/\" is good suggestion.",
749                                   E_USER_ERROR);
750                     return false;
751                 } else {
752                     /*
753                     trigger_error(sprintf("Workaround for PHP/Windows is_uploaded_file() problem for %s.",
754                                           $fileinfo['tmp_name'])."\n".
755                                   "Probably illegal TEMP environment or upload_tmp_dir setting.", 
756                                   E_USER_NOTICE);
757                     */
758                     ;
759                 }
760             } else {
761               trigger_error(sprintf("Uploaded tmpfile %s not found.", $fileinfo['tmp_name'])."\n".
762                            " Probably illegal TEMP environment or upload_tmp_dir setting.",
763                           E_USER_WARNING);
764             }
765         }
766         return new Request_UploadedFile($fileinfo);
767     }
768     
769     function Request_UploadedFile($fileinfo) {
770         $this->_info = $fileinfo;
771     }
772
773     function getSize() {
774         return $this->_info['size'];
775     }
776
777     function getName() {
778         return $this->_info['name'];
779     }
780
781     function getType() {
782         return $this->_info['type'];
783     }
784
785     function getTmpName() {
786         return $this->_info['tmp_name'];
787     }
788
789     function open() {
790         if ( ($fd = fopen($this->_info['tmp_name'], "rb")) ) {
791             if ($this->getSize() < filesize($this->_info['tmp_name'])) {
792                 // FIXME: Some PHP's (or is it some browsers?) put
793                 //    HTTP/MIME headers in the file body, some don't.
794                 //
795                 // At least, I think that's the case.  I know I used
796                 // to need this code, now I don't.
797                 //
798                 // This code is more-or-less untested currently.
799                 //
800                 // Dump HTTP headers.
801                 while ( ($header = fgets($fd, 4096)) ) {
802                     if (trim($header) == '') {
803                         break;
804                     }
805                     else if (!preg_match('/^content-(length|type):/i', $header)) {
806                         rewind($fd);
807                         break;
808                     }
809                 }
810             }
811         }
812         return $fd;
813     }
814
815     function getContents() {
816         $fd = $this->open();
817         $data = fread($fd, $this->getSize());
818         fclose($fd);
819         return $data;
820     }
821 }
822
823 /**
824  * Create NCSA "combined" log entry for current request.
825  * Also needed for advanced spam prevention.
826  * global object holding global state (sql or file, entries, to dump)
827  */
828 class Request_AccessLog {
829     /**
830      * @param $logfile string  Log file name.
831      */
832     function Request_AccessLog ($logfile, $do_sql = false) {
833         //global $request; // request not yet initialized!
834
835         $this->logfile = $logfile;
836         if ($logfile and !is_writeable($logfile)) {
837             trigger_error
838                 (sprintf(_("%s is not writable."), _("The PhpWiki access log file"))
839                  . "\n"
840                  . sprintf(_("Please ensure that %s is writable, or redefine %s in config/config.ini."),
841                            sprintf(_("the file '%s'"), ACCESS_LOG),
842                            'ACCESS_LOG')
843                  , E_USER_NOTICE);
844         }
845         //$request->_accesslog =& $this;
846         //if (empty($request->_accesslog->entries))
847         register_shutdown_function("Request_AccessLogEntry_shutdown_function");
848         
849         if ($do_sql) {
850             global $DBParams;
851             if (!in_array($DBParams['dbtype'], array('SQL','ADODB'))) {
852                 trigger_error("Unsupported database backend for ACCESS_LOG_SQL.\nNeed DATABASE_TYPE=SQL or ADODB");
853             } else {
854                 //$this->_dbi =& $request->_dbi;
855                 $this->logtable = (!empty($DBParams['prefix']) ? $DBParams['prefix'] : '')."accesslog";
856             }
857         }
858         $this->entries = array();
859         $this->entries[] = new Request_AccessLogEntry($this);
860     }
861
862     function _do($cmd, &$arg) {
863         if ($this->entries)
864             for ($i=0; $i < count($this->entries);$i++)
865                 $this->entries[$i]->$cmd($arg);
866     }
867     function push(&$request)   { $this->_do('push',$request); }
868     function setSize($arg)     { $this->_do('setSize',$arg); }
869     function setStatus($arg)   { $this->_do('setStatus',$arg); }
870     function setDuration($arg) { $this->_do('setDuration',$arg); }
871
872     /**
873      * Read sequentially all previous entries from the beginning.
874      * while ($logentry = Request_AccessLogEntry::read()) ;
875      * For internal log analyzers: RecentReferrers, WikiAccessRestrictions
876      */
877     function read() {
878         return $this->logtable ? $this->read_sql() : $this->read_file();
879     }
880
881     /**
882      * Return iterator of referer items reverse sorted (latest first).
883      */
884     function get_referer($limit=15, $external_only=false) {
885         if ($external_only) { // see stdlin.php:isExternalReferrer()
886             $base = SERVER_URL;
887             $blen = strlen($base);
888         }
889         if (!empty($this->_dbi)) {
890             // check same hosts in referer and request and remove them
891             $ext_where = " AND LEFT(referer,$blen) <> ".$this->_dbi->quote($base)
892                 ." AND LEFT(referer,$blen) <> LEFT(CONCAT(".$this->_dbi->quote(SERVER_URL).",request_uri),$blen)";
893             return $this->_read_sql_query("(referer <>'' AND NOT(ISNULL(referer)))"
894                                           .($external_only ? $ext_where : '')
895                                           ." ORDER BY time_stamp DESC"
896                                           .($limit ? " LIMIT $limit" : ""));
897         } else {
898             $iter = new WikiDB_Array_generic_iter(0);
899             $logs =& $iter->_array;
900             while ($logentry = $this->read_file()) {
901                 if (!empty($logentry->referer)
902                     and (!$external_only or (substr($logentry->referer,0,$blen) != $base)))
903                 {
904                     $iter->_array[] = $logentry;
905                     if ($limit and count($logs) > $limit)
906                         array_shift($logs);
907                 }
908             }
909             $logs = array_reverse($logs);
910             $logs = array_slice($logs,0,min($limit,count($logs)));
911             return $iter;
912         }
913     }
914
915     /**
916      * Return iterator of matching host items reverse sorted (latest first).
917      */
918     function get_host($host, $since_minutes=20) {
919         if ($this->logtable) {
920             // mysql specific only:
921             return $this->read_sql("request_host=".$this->_dbi->quote($host)." AND time_stamp > ". (time()-$since_minutes*60) 
922                             ." ORDER BY time_stamp DESC");
923         } else {
924             $iter = new WikiDB_Array_generic_iter();
925             $logs =& $iter->_array;
926             $logentry = new Request_AccessLogEntry($this);
927             while ($logentry->read_file()) {
928                 if (!empty($logentry->referer)) {
929                     $iter->_array[] = $logentry;
930                     if ($limit and count($logs) > $limit)
931                         array_shift($logs);
932                     $logentry = new Request_AccessLogEntry($this);
933                 }
934             }
935             $logs = array_reverse($logs);
936             $logs = array_slice($logs,0,min($limit,count($logs)));
937             return $iter;
938         }
939     }
940
941     /**
942      * Read sequentially all previous entries from log file.
943      */
944     function read_file() {
945         global $request;
946         if ($this->logfile) $this->logfile = ACCESS_LOG; // support Request_AccessLog::read
947
948         if (empty($this->reader))       // start at the beginning
949             $this->reader = fopen($this->logfile, "r");
950         if ($s = fgets($this->reader)) {
951             $entry = new Request_AccessLogEntry($this);
952             if (preg_match('/^(\S+)\s(\S+)\s(\S+)\s\[(.+?)\] "([^"]+)" (\d+) (\d+) "([^"]*)" "([^"]*)"$/',$s,$m)) {
953                 list(,$entry->host, $entry->ident, $entry->user, $entry->time,
954                      $entry->request, $entry->status, $entry->size,
955                      $entry->referer, $entry->user_agent) = $m;
956             }
957             return $entry;
958         } else { // until the end
959             fclose($this->reader);
960             return false;
961         }
962     }
963     function _read_sql_query($where='') {
964         $dbh =& $GLOBALS['request']->_dbi;
965         $log_tbl =& $this->logtable;
966         return $dbh->genericSqlIter("SELECT *,request_uri as request,request_time as time,remote_user as user,"
967                                     ."remote_host as host,agent as user_agent"
968                                     ." FROM $log_tbl"
969                                     . ($where ? " WHERE $where" : ""));
970     }
971     function read_sql($where='') {
972         if (empty($this->sqliter))
973             $this->sqliter = $this->_read_sql_query($where);
974         return $this->sqliter->next();
975     }
976
977     /* done in request->finish() before the db is closed */
978     function write_sql() {
979         $dbh =& $GLOBALS['request']->_dbi;
980         if (isset($this->entries) and $dbh and $dbh->isOpen())
981             foreach ($this->entries as $entry) {
982                 $entry->write_sql();
983             }
984     }
985     /* done in the shutdown callback */
986     function write_file() {
987         if (isset($this->entries) and $this->logfile)
988             foreach ($this->entries as $entry) {
989                 $entry->write_file();
990             }
991         unset($this->entries);
992     }
993     /* in an ideal world... */
994     function write() {
995         if ($this->logfile) $this->write_file();
996         if ($this->logtable) $this->write_sql();
997         unset($this->entries);
998     }
999 }
1000
1001 class Request_AccessLogEntry
1002 {
1003     /**
1004      * Constructor.
1005      *
1006      * The log entry will be automatically appended to the log file or 
1007      * SQL table when the current request terminates.
1008      *
1009      * If you want to modify a Request_AccessLogEntry before it gets
1010      * written (e.g. via the setStatus and setSize methods) you should
1011      * use an '&' on the constructor, so that you're working with the
1012      * original (rather than a copy) object.
1013      *
1014      * <pre>
1015      *    $log_entry = & new Request_AccessLogEntry("/tmp/wiki_access_log");
1016      *    $log_entry->setStatus(401);
1017      *    $log_entry->push($request);
1018      * </pre>
1019      *
1020      *
1021      */
1022     function Request_AccessLogEntry (&$accesslog) {
1023         $this->_accesslog = $accesslog;
1024         $this->logfile = $accesslog->logfile;
1025         $this->time = time();
1026         $this->status = 200;    // see setStatus()
1027         $this->size = 0;        // see setSize()
1028     }
1029
1030     /**
1031      * @param $request object  Request object for current request.
1032      */
1033     function push(&$request) {
1034         $this->host  = $request->get('REMOTE_HOST');
1035         $this->ident = $request->get('REMOTE_IDENT');
1036         if (!$this->ident)
1037             $this->ident = '-';
1038         $user = $request->getUser();
1039         if ($user->isAuthenticated())
1040             $this->user = $user->UserName();
1041         else
1042             $this->user = '-';
1043         $this->request = join(' ', array($request->get('REQUEST_METHOD'),
1044                                          $request->get('REQUEST_URI'),
1045                                          $request->get('SERVER_PROTOCOL')));
1046         $this->referer = (string) $request->get('HTTP_REFERER');
1047         $this->user_agent = (string) $request->get('HTTP_USER_AGENT');
1048     }
1049
1050     /**
1051      * Set result status code.
1052      *
1053      * @param $status integer  HTTP status code.
1054      */
1055     function setStatus ($status) {
1056         $this->status = $status;
1057     }
1058     
1059     /**
1060      * Set response size.
1061      *
1062      * @param $size integer
1063      */
1064     function setSize ($size=0) {
1065         $this->size = (int)$size;
1066     }
1067     function setDuration ($seconds) {
1068         // Pear DB does not correctly quote , in floats using ?. e.g. in european locales.
1069         // Workaround:
1070         $this->duration = strtr(sprintf("%f", $seconds),",",".");
1071     }
1072     
1073     /**
1074      * Get time zone offset.
1075      *
1076      * This is a static member function.
1077      *
1078      * @param $time integer Unix timestamp (defaults to current time).
1079      * @return string Zone offset, e.g. "-0800" for PST.
1080      */
1081     function _zone_offset ($time = false) {
1082         if (!$time)
1083             $time = time();
1084         $offset = date("Z", $time);
1085         $negoffset = "";
1086         if ($offset < 0) {
1087             $negoffset = "-";
1088             $offset = -$offset;
1089         }
1090         $offhours = floor($offset / 3600);
1091         $offmins  = $offset / 60 - $offhours * 60;
1092         return sprintf("%s%02d%02d", $negoffset, $offhours, $offmins);
1093     }
1094
1095     /**
1096      * Format time in NCSA format.
1097      *
1098      * This is a static member function.
1099      *
1100      * @param $time integer Unix timestamp (defaults to current time).
1101      * @return string Formatted date & time.
1102      */
1103     function _ncsa_time($time = false) {
1104         if (!$time)
1105             $time = time();
1106         return date("d/M/Y:H:i:s", $time) .
1107             " " . $this->_zone_offset();
1108     }
1109
1110     function write() {
1111         if ($this->_accesslog->logfile) $this->write_file();
1112         if ($this->_accesslog->logtable) $this->write_sql();
1113     }
1114
1115     /**
1116      * Write entry to log file.
1117      */
1118     function write_file() {
1119         $entry = sprintf('%s %s %s [%s] "%s" %d %d "%s" "%s"',
1120                          $this->host, $this->ident, $this->user,
1121                          $this->_ncsa_time($this->time),
1122                          $this->request, $this->status, $this->size,
1123                          $this->referer, $this->user_agent);
1124         if (!empty($this->_accesslog->reader)) {
1125             fclose($this->_accesslog->reader);
1126             unset($this->_accesslog->reader);
1127         }
1128         //Error log doesn't provide locking.
1129         //error_log("$entry\n", 3, $this->logfile);
1130         // Alternate method
1131         if (($fp = fopen($this->logfile, "a"))) {
1132             flock($fp, LOCK_EX);
1133             fputs($fp, "$entry\n");
1134             fclose($fp);
1135         }
1136     }
1137
1138     /* This is better been done by apache mod_log_sql */
1139     /* If ACCESS_LOG_SQL & 2 we do write it by our own */
1140     function write_sql() {
1141         global $request;
1142         
1143         $dbh =& $request->_dbi;
1144         if ($dbh and $dbh->isOpen() and $this->_accesslog->logtable) {
1145             //$log_tbl =& $this->_accesslog->logtable;
1146             if ($request->get('REQUEST_METHOD') == "POST") {
1147                 // strangely HTTP_POST_VARS doesn't contain all posted vars.
1148                 if (check_php_version(4,2))
1149                     $args = $_POST; // copy not ref. clone not needed on hashes
1150                 else
1151                     $args = $GLOBALS['HTTP_POST_VARS'];
1152                 // garble passwords
1153                 if (!empty($args['auth']['passwd']))    $args['auth']['passwd'] = '<not displayed>';
1154                 if (!empty($args['dbadmin']['passwd'])) $args['dbadmin']['passwd'] = '<not displayed>';
1155                 if (!empty($args['pref']['passwd']))    $args['pref']['passwd'] = '<not displayed>';
1156                 if (!empty($args['pref']['passwd2']))   $args['pref']['passwd2'] = '<not displayed>';
1157                 $this->request_args = substr(serialize($args),0,254); // if VARCHAR(255) is used.
1158             } else {
1159                 $this->request_args = $request->get('QUERY_STRING'); 
1160             }
1161             $this->request_method = $request->get('REQUEST_METHOD');
1162             $this->request_uri = $request->get('REQUEST_URI');
1163             // duration problem: sprintf "%f" might use comma e.g. "100,201" in european locales
1164             $dbh->_backend->write_accesslog($this);
1165         }
1166     }
1167 }
1168
1169 /**
1170  * Shutdown callback.
1171  *
1172  * @access private
1173  * @see Request_AccessLogEntry
1174  */
1175 function Request_AccessLogEntry_shutdown_function () {
1176     global $request;
1177     
1178     if (isset($request->_accesslog->entries) and $request->_accesslog->logfile)
1179         foreach ($request->_accesslog->entries as $entry) {
1180             $entry->write_file();
1181         }
1182     unset($request->_accesslog->entries);
1183 }
1184
1185
1186 class HTTP_ETag {
1187     function HTTP_ETag($val, $is_weak=false) {
1188         $this->_val = wikihash($val);
1189         $this->_weak = $is_weak;
1190     }
1191
1192     /** Comparison
1193      *
1194      * Strong comparison: If either (or both) tag is weak, they
1195      *  are not equal.
1196      */
1197     function equals($that, $strong_match=false) {
1198         if ($this->_val != $that->_val)
1199             return false;
1200         if ($strong_match and ($this->_weak or $that->_weak))
1201             return false;
1202         return true;
1203     }
1204
1205
1206     function asString() {
1207         $quoted = '"' . addslashes($this->_val) . '"';
1208         return $this->_weak ? "W/$quoted" : $quoted;
1209     }
1210
1211     /** Parse tag from header.
1212      *
1213      * This is a static member function.
1214      */
1215     function parse($strval) {
1216         if (!preg_match(':^(W/)?"(.+)"$:i', trim($strval), $m))
1217             return false;       // parse failed
1218         list(,$weak,$str) = $m;
1219         return new HTTP_ETag(stripslashes($str), $weak);
1220     }
1221
1222     function matches($taglist, $strong_match=false) {
1223         $taglist = trim($taglist);
1224
1225         if ($taglist == '*') {
1226             if ($strong_match)
1227                 return ! $this->_weak;
1228             else
1229                 return true;
1230         }
1231
1232         while (preg_match('@^(W/)?"((?:\\\\.|[^"])*)"\s*,?\s*@i',
1233                           $taglist, $m)) {
1234             list($match, $weak, $str) = $m;
1235             $taglist = substr($taglist, strlen($match));
1236             $tag = new HTTP_ETag(stripslashes($str), $weak);
1237             if ($this->equals($tag, $strong_match)) {
1238                 return true;
1239             }
1240         }
1241         return false;
1242     }
1243 }
1244
1245 // Possible results from the HTTP_ValidatorSet::_check*() methods.
1246 // (Higher numerical values take precedence.)
1247 define ('_HTTP_VAL_PASS', 0);           // Test is irrelevant
1248 define ('_HTTP_VAL_NOT_MODIFIED', 1);   // Test passed, content not changed
1249 define ('_HTTP_VAL_MODIFIED', 2);       // Test failed, content changed
1250 define ('_HTTP_VAL_FAILED', 3);         // Precondition failed.
1251
1252 class HTTP_ValidatorSet {
1253     function HTTP_ValidatorSet($validators) {
1254         $this->_mtime = $this->_weak = false;
1255         $this->_tag = array();
1256         
1257         foreach ($validators as $key => $val) {
1258             if ($key == '%mtime') {
1259                 $this->_mtime = $val;
1260             }
1261             elseif ($key == '%weak') {
1262                 if ($val)
1263                     $this->_weak = true;
1264             }
1265             else {
1266                 $this->_tag[$key] = $val;
1267             }
1268         }
1269     }
1270
1271     function append($that) {
1272         if (is_array($that))
1273             $that = new HTTP_ValidatorSet($that);
1274
1275         // Pick the most recent mtime
1276         if (isset($that->_mtime))
1277             if (!isset($this->_mtime) || $that->_mtime > $this->_mtime)
1278                 $this->_mtime = $that->_mtime;
1279
1280         // If either is weak, we're weak
1281         if (!empty($that->_weak))
1282             $this->_weak = true;
1283         if (is_array($this->_tag))
1284             $this->_tag = array_merge($this->_tag, $that->_tag);
1285         else
1286             $this->_tag = $that->_tag;
1287     }
1288
1289     function getETag() {
1290         if (! $this->_tag)
1291             return false;
1292         return new HTTP_ETag($this->_tag, $this->_weak);
1293     }
1294
1295     function getModificationTime() {
1296         return $this->_mtime;
1297     }
1298     
1299     function checkConditionalRequest (&$request) {
1300         $result = max($this->_checkIfUnmodifiedSince($request),
1301                       $this->_checkIfModifiedSince($request),
1302                       $this->_checkIfMatch($request),
1303                       $this->_checkIfNoneMatch($request));
1304
1305         if ($result == _HTTP_VAL_PASS || $result == _HTTP_VAL_MODIFIED)
1306             return false;       // "please proceed with normal processing"
1307         elseif ($result == _HTTP_VAL_FAILED)
1308             return 412;         // "412 Precondition Failed"
1309         elseif ($result == _HTTP_VAL_NOT_MODIFIED)
1310             return 304;         // "304 Not Modified"
1311
1312         trigger_error("Ack, shouldn't get here", E_USER_ERROR);
1313         return false;
1314     }
1315
1316     function _checkIfUnmodifiedSince(&$request) {
1317         if ($this->_mtime !== false) {
1318             $since = ParseRfc1123DateTime($request->get("HTTP_IF_UNMODIFIED_SINCE"));
1319             if ($since !== false && $this->_mtime > $since)
1320                 return _HTTP_VAL_FAILED;
1321         }
1322         return _HTTP_VAL_PASS;
1323     }
1324
1325     function _checkIfModifiedSince(&$request) {
1326         if ($this->_mtime !== false and $request->isGetOrHead()) {
1327             $since = ParseRfc1123DateTime($request->get("HTTP_IF_MODIFIED_SINCE"));
1328             if ($since !== false) {
1329                 if ($this->_mtime <= $since)
1330                     return _HTTP_VAL_NOT_MODIFIED;
1331                 return _HTTP_VAL_MODIFIED;
1332             }
1333         }
1334         return _HTTP_VAL_PASS;
1335     }
1336
1337     function _checkIfMatch(&$request) {
1338         if ($this->_tag && ($taglist = $request->get("HTTP_IF_MATCH"))) {
1339             $tag = $this->getETag();
1340             if (!$tag->matches($taglist, 'strong'))
1341                 return _HTTP_VAL_FAILED;
1342         }
1343         return _HTTP_VAL_PASS;
1344     }
1345
1346     function _checkIfNoneMatch(&$request) {
1347         if ($this->_tag && ($taglist = $request->get("HTTP_IF_NONE_MATCH"))) {
1348             $tag = $this->getETag();
1349             $strong_compare = ! $request->isGetOrHead();
1350             if ($taglist) {
1351                 if ($tag->matches($taglist, $strong_compare)) {
1352                     if ($request->isGetOrHead())
1353                         return _HTTP_VAL_NOT_MODIFIED;
1354                     else
1355                         return _HTTP_VAL_FAILED;
1356                 }
1357                 return _HTTP_VAL_MODIFIED;
1358             }
1359         }
1360         return _HTTP_VAL_PASS;
1361     }
1362 }
1363
1364 // Local Variables:
1365 // mode: php
1366 // tab-width: 8
1367 // c-basic-offset: 4
1368 // c-hanging-comment-ender-p: nil
1369 // indent-tabs-mode: nil
1370 // End:   
1371 ?>