]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/Request.php
Let's assume PHP >= 4.2
[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 class Request {
24         
25     function Request() {
26         $this->_fix_magic_quotes_gpc();
27         $this->_fix_multipart_form_data();
28         
29         switch($this->get('REQUEST_METHOD')) {
30         case 'GET':
31         case 'HEAD':
32             $this->args = &$GLOBALS['HTTP_GET_VARS'];
33             break;
34         case 'POST':
35             $this->args = &$GLOBALS['HTTP_POST_VARS'];
36             break;
37         default:
38             $this->args = array();
39             break;
40         }
41         
42         $this->session = new Request_SessionVars;
43         $this->cookies = new Request_CookieVars;
44         
45         if (ACCESS_LOG or ACCESS_LOG_SQL) {
46             $this->_accesslog = new Request_AccessLog(ACCESS_LOG, ACCESS_LOG_SQL);
47         }
48         
49         $GLOBALS['request'] = $this;
50     }
51
52     function get($key) {
53         if (!empty($GLOBALS['HTTP_SERVER_VARS']))
54             $vars = &$GLOBALS['HTTP_SERVER_VARS'];
55         elseif (!empty($GLOBALS['HTTP_ENV_VARS']))
56             $vars = &$GLOBALS['HTTP_ENV_VARS']; // cgi or other servers than Apache
57         else
58             trigger_error("Serious php configuration error!"
59                           ." No HTTP_SERVER_VARS and HTTP_ENV_VARS vars available."
60                           ." These should get defined in lib/prepend.php",
61                           E_USER_WARNING);
62
63         if (isset($vars[$key]))
64             return $vars[$key];
65
66         switch ($key) {
67         case 'REMOTE_HOST':
68             $addr = $vars['REMOTE_ADDR'];
69             if (defined('ENABLE_REVERSE_DNS') && ENABLE_REVERSE_DNS)
70                 return $vars[$key] = gethostbyaddr($addr);
71             else
72                 return $addr;
73         default:
74             return false;
75         }
76     }
77
78     function getArg($key) {
79         if (isset($this->args[$key]))
80             return $this->args[$key];
81         return false;
82     }
83
84     function getArgs () {
85         return $this->args;
86     }
87     
88     function setArg($key, $val) {
89         if ($val === false)
90             unset($this->args[$key]);
91         else
92             $this->args[$key] = $val;
93     }
94     
95     // Well oh well. Do we really want to pass POST params back as GET?
96     function getURLtoSelf($args = false, $exclude = array()) {
97         $get_args = $this->args;
98         if ($args)
99             $get_args = array_merge($get_args, $args);
100
101         // leave out empty arg values
102         foreach ($get_args as $g => $v) {
103             if ($v === false or $v === '') unset($get_args[$g]);
104         }
105
106         // Err... good point...
107         // sortby buttons
108         if ($this->isPost()) {
109             $exclude = array_merge($exclude, array('action','auth'));
110             //$get_args = $args; // or only the provided
111             /*
112             trigger_error("Request::getURLtoSelf() should probably not be from POST",
113                           E_USER_NOTICE);
114             */
115         }
116
117         foreach ($exclude as $ex) {
118             if (!empty($get_args[$ex])) unset($get_args[$ex]);
119         }
120
121         $pagename = $get_args['pagename'];
122         unset ($get_args['pagename']);
123         if (!empty($get_args['action']) and $get_args['action'] == 'browse')
124             unset($get_args['action']);
125
126         return WikiURL($pagename, $get_args);
127     }
128
129     function isPost () {
130         return $this->get("REQUEST_METHOD") == "POST";
131     }
132
133     function isGetOrHead () {
134         return in_array($this->get('REQUEST_METHOD'),
135                         array('GET', 'HEAD'));
136     }
137
138     function httpVersion() {
139         if (!preg_match('@HTTP\s*/\s*(\d+.\d+)@', $this->get('SERVER_PROTOCOL'), $m))
140             return false;
141         return (float) $m[1];
142     }
143     
144     /* Redirects after edit may fail if no theme signature image is defined. 
145      * Set DISABLE_HTTP_REDIRECT = true then.
146      */
147     function redirect($url, $noreturn = true) {
148         $bogus = defined('DISABLE_HTTP_REDIRECT') && DISABLE_HTTP_REDIRECT;
149         
150         if (!$bogus) {
151             header("Location: $url");
152             /*
153              * "302 Found" is not really meant to be sent in response
154              * to a POST.  Worse still, according to (both HTTP 1.0
155              * and 1.1) spec, the user, if it is sent, the user agent
156              * is supposed to use the same method to fetch the
157              * redirected URI as the original.
158              *
159              * That means if we redirect from a POST, the user-agent
160              * supposed to generate another POST.  Not what we want.
161              * (We do this after a page save after all.)
162              *
163              * Fortunately, most/all browsers don't do that.
164              *
165              * "303 See Other" is what we really want.  But it only
166              * exists in HTTP/1.1
167              *
168              * FIXME: this is still not spec compliant for HTTP
169              * version < 1.1.
170              */
171             $status = $this->httpVersion() >= 1.1 ? 303 : 302;
172             $this->setStatus($status);
173         }
174
175         if ($noreturn) {
176             $this->discardOutput(); // This might print the gzip headers. Not good.
177             $this->buffer_output(false);
178             
179             include_once('lib/Template.php');
180             $tmpl = new Template('redirect', $this, array('REDIRECT_URL' => $url));
181             $tmpl->printXML();
182             $this->finish();
183         }
184         elseif ($bogus) {
185             // Safari needs window.location.href = targeturl
186             return JavaScript("
187               function redirect(url) {
188                 if (typeof location.replace == 'function')
189                   location.replace(url);
190                 else if (typeof location.assign == 'function')
191                   location.assign(url);
192                 else if (self.location.href)
193                   self.location.href = url;
194                 else
195                   window.location = url;
196               }
197               redirect('" . addslashes($url) . "')");
198         }
199     }
200
201     /** Set validators for this response.
202      *
203      * This sets a (possibly incomplete) set of validators
204      * for this response.
205      *
206      * The validator set can be extended using appendValidators().
207      *
208      * When you're all done setting and appending validators, you
209      * must call checkValidators() to check them and set the
210      * appropriate headers in the HTTP response.
211      *
212      * Example Usage:
213      *  ...
214      *  $request->setValidators(array('pagename' => $pagename,
215      *                                '%mtime' => $rev->get('mtime')));
216      *  ...
217      *  // Wups... response content depends on $otherpage, too...
218      *  $request->appendValidators(array('otherpage' => $otherpagerev->getPageName(),
219      *                                   '%mtime' => $otherpagerev->get('mtime')));
220      *  ...
221      *  // After all validators have been set:
222      *  $request->checkValidators();
223      */
224     function setValidators($validator_set) {
225         if (is_array($validator_set))
226             $validator_set = new HTTP_ValidatorSet($validator_set);
227         $this->_validators = $validator_set;
228     }
229     
230     /** Append more validators for this response. 
231      *  i.e dependencies on other pages mtimes
232      *  now it may be called in init also to simplify client code.
233      */ 
234     function appendValidators($validator_set) {
235         if (!isset($this->_validators)) {
236             $this->setValidators($validator_set);
237             return;
238         }
239         $this->_validators->append($validator_set);
240     }
241     
242     /** Check validators and set headers in HTTP response
243      *
244      * This sets the appropriate "Last-Modified" and "ETag"
245      * headers in the HTTP response.
246      *
247      * Additionally, if the validators match any(all) conditional
248      * headers in the HTTP request, this method will not return, but
249      * instead will send "304 Not Modified" or "412 Precondition
250      * Failed" (as appropriate) back to the client.
251      */
252     function checkValidators() {
253         $validators = &$this->_validators;
254         
255         // Set validator headers
256         if (!empty($this->_is_buffering_output) or !headers_sent()) {
257             if (($etag = $validators->getETag()) !== false)
258                 header("ETag: " . $etag->asString());
259             if (($mtime = $validators->getModificationTime()) !== false)
260                 header("Last-Modified: " . Rfc1123DateTime($mtime));
261
262             // Set cache control headers
263             $this->cacheControl();
264         }
265
266         if (CACHE_CONTROL == 'NO_CACHE')
267             return;             // don't check conditionals...
268         
269         // Check conditional headers in request
270         $status = $validators->checkConditionalRequest($this);
271         if ($status) {
272             // Return short response due to failed conditionals
273             $this->setStatus($status);
274             echo "\n\n";
275             $this->discardOutput();
276             $this->finish();
277             exit();
278         }
279     }
280
281     /** Set the cache control headers in the HTTP response.
282      */
283     function cacheControl($strategy=CACHE_CONTROL, $max_age=CACHE_CONTROL_MAX_AGE) {
284         if ($strategy == 'NO_CACHE') {
285             $cache_control = "no-cache"; // better set private. See Pear HTTP_Header
286             $max_age = -20;
287         }
288         elseif ($strategy == 'ALLOW_STALE' && $max_age > 0) {
289             $cache_control = sprintf("max-age=%d", $max_age);
290         }
291         else {
292             $cache_control = "must-revalidate";
293             $max_age = -20;
294         }
295         header("Cache-Control: $cache_control");
296         header("Expires: " . Rfc1123DateTime(time() + $max_age));
297         header("Vary: Cookie"); // FIXME: add more here?
298     }
299     
300     function setStatus($status) {
301         if (preg_match('|^HTTP/.*?\s(\d+)|i', $status, $m)) {
302             header($status);
303             $status = $m[1];
304         }
305         else {
306             $status = (integer) $status;
307             $reason = array('200' => 'OK',
308                             '302' => 'Found',
309                             '303' => 'See Other',
310                             '304' => 'Not Modified',
311                             '400' => 'Bad Request',
312                             '401' => 'Unauthorized',
313                             '403' => 'Forbidden',
314                             '404' => 'Not Found',
315                             '412' => 'Precondition Failed');
316             // FIXME: is it always okay to send HTTP/1.1 here, even for older clients?
317             header(sprintf("HTTP/1.1 %d %s", $status, $reason[$status]));
318         }
319
320         if (isset($this->_log_entry))
321             $this->_log_entry->setStatus($status);
322     }
323
324     function buffer_output($compress = true) {
325         // FIXME: disables sessions (some byte before all headers_sent())
326         /*if (defined('USECACHE') and !USECACHE) {
327             $this->_is_buffering_output = false;
328             return;
329         }*/
330         if (defined('COMPRESS_OUTPUT')) {
331             if (!COMPRESS_OUTPUT)
332                 $compress = false;
333         }
334         elseif (isCGI()) // necessary?
335             $compress = false;
336             
337         if ($this->getArg('start_debug')) $compress = false;
338         if ($this->getArg('nocache'))
339             $compress = false;
340         
341         // Should we compress even when apache_note is not available?
342         // sf.net bug #933183 and http://bugs.php.net/17557
343         // This effectively eliminates CGI, but all other servers also. hmm.
344         if ($compress 
345             and (!function_exists('ob_gzhandler') 
346                  or !function_exists('apache_note'))) 
347             $compress = false;
348             
349         // "output handler 'ob_gzhandler' cannot be used twice"
350         // http://www.php.net/ob_gzhandler
351         if ($compress and ini_get("zlib.output_compression"))
352             $compress = false;
353
354         // New: we check for the client Accept-Encoding: "gzip" presence also
355         // This should eliminate a lot or reported problems.
356         if ($compress
357             and (!$this->get("HTTP_ACCEPT_ENCODING")
358                  or !strstr($this->get("HTTP_ACCEPT_ENCODING"), "gzip")))
359             $compress = false;
360
361         // Most RSS clients are NOT(!) application/xml gzip compatible yet. 
362         // Even if they are sending the accept-encoding gzip header!
363         // wget is, Mozilla, and MSIE no.
364         // Of the RSS readers only MagpieRSS 0.5.2 is. http://www.rssgov.com/rssparsers.html
365         // See also http://phpwiki.sourceforge.net/phpwiki/KnownBugs
366         if ($compress 
367             and $this->getArg('format') 
368             and strstr($this->getArg('format'), 'rss'))
369             $compress = false;
370
371         if ($compress) {
372             ob_start('phpwiki_gzhandler');
373             
374             // TODO: dont send a length or get the gzip'ed data length.
375             $this->_is_compressing_output = true; 
376             header("Content-Encoding: gzip");
377             /*
378              * Attempt to prevent Apache from doing the dreaded double-gzip.
379              *
380              * It would be better if we could detect when apache was going
381              * to zip for us, and then let it ... but I have yet to figure
382              * out how to do that.
383              */
384             if (function_exists('apache_note'))
385                 @apache_note('no-gzip', 1);
386         }
387         else {
388             // Now we alway buffer output.
389             // This is so we can set HTTP headers (e.g. for redirect)
390             // at any point.
391             // FIXME: change the name of this method.
392             ob_start();
393             $this->_is_compressing_output = false;
394         }
395         $this->_is_buffering_output = true;
396         $this->_ob_get_length = 0;
397     }
398
399     function discardOutput() {
400         if (!empty($this->_is_buffering_output)) {
401             if (ob_get_length()) ob_clean();
402             $this->_is_buffering_output = false;
403         } else {
404             trigger_error("Not buffering output", E_USER_NOTICE);
405         }
406     }
407
408     /** 
409      * Longer texts need too much memory on tiny or memory-limit=8MB systems.
410      * We might want to flush our buffer and restart again.
411      * (This would be fine if php would release its memory)
412      * Note that this must not be called inside Template expansion or other 
413      * sections with ob_buffering.
414      */
415     function chunkOutput() {
416         if (!empty($this->_is_buffering_output) 
417             or 
418             (function_exists('ob_get_level') and @ob_get_level())) 
419         {
420             $this->_do_chunked_output = true;
421             if (empty($this->_ob_get_length)) $this->_ob_get_length = 0;
422             $this->_ob_get_length += ob_get_length();
423             while (@ob_end_flush());
424             @ob_end_clean();
425             ob_start();
426         }
427     }
428
429     function finish() {
430         $this->_finishing = true;
431         if (!empty($this->_accesslog)) {
432             $this->_accesslog->push($this);
433             if (empty($this->_do_chunked_output) and empty($this->_ob_get_length))
434                 $this->_ob_get_length = ob_get_length();
435             $this->_accesslog->setSize($this->_ob_get_length);
436             global $RUNTIMER;
437             if ($RUNTIMER) $this->_accesslog->setDuration($RUNTIMER->getTime());
438             // sql logging must be done before the db is closed.
439             if (isset($this->_accesslog->logtable))
440                 $this->_accesslog->write_sql();
441         }
442         
443         if (!empty($this->_is_buffering_output)) {
444             // if _is_compressing_output then ob_get_length() returns 
445             // the uncompressed length, not the gzip'ed as required.
446             if (!headers_sent() and !$this->_is_compressing_output) {
447                 // php url-rewriting miscalculates the ob length. fixes bug #1376007
448                 if (ini_get('use_trans_sid') == 'off') {
449                     if (empty($this->_do_chunked_output)) {
450                         $this->_ob_get_length = ob_get_length();
451                     }
452                     header(sprintf("Content-Length: %d", $this->_ob_get_length));
453                 }
454             }
455             $this->_is_buffering_output = false;
456             ob_end_flush();
457         } elseif (function_exists('ob_get_level') and @ob_get_level()) {
458             ob_end_flush();
459         }
460         session_write_close();
461         if (!empty($this->_dbi)) {
462             $this->_dbi->close();
463             unset($this->_dbi);
464         }
465
466         exit;
467     }
468
469     function getSessionVar($key) {
470         return $this->session->get($key);
471     }
472     function setSessionVar($key, $val) {
473         if ($key == 'wiki_user') {
474             if (empty($val->page))
475                 $val->page = $this->getArg('pagename');
476             if (empty($val->action))
477                 $val->action = $this->getArg('action');
478             // avoid recursive objects and session resource handles
479             // avoid overlarge session data (max 4000 byte!)
480             if (isset($val->_group)) {
481                 unset($val->_group->_request);
482                 unset($val->_group->user);
483             }
484             if (ENABLE_USER_NEW) {
485                 unset($val->_HomePagehandle);
486                 unset($val->_auth_dbi);
487             } else {
488                 unset($val->_dbi);
489                 unset($val->_authdbi);
490                 unset($val->_homepage);
491                 unset($val->_request);
492             }
493         }
494         return $this->session->set($key, $val);
495     }
496     function deleteSessionVar($key) {
497         return $this->session->delete($key);
498     }
499
500     function getCookieVar($key) {
501         return $this->cookies->get($key);
502     }
503     function setCookieVar($key, $val, $lifetime_in_days = false, $path = false) {
504         return $this->cookies->set($key, $val, $lifetime_in_days, $path);
505     }
506     function deleteCookieVar($key) {
507         return $this->cookies->delete($key);
508     }
509     
510     function getUploadedFile($key) {
511         return Request_UploadedFile::getUploadedFile($key);
512     }
513     
514
515     function _fix_magic_quotes_gpc() {
516         $needs_fix = array('HTTP_POST_VARS',
517                            'HTTP_GET_VARS',
518                            'HTTP_COOKIE_VARS',
519                            'HTTP_SERVER_VARS',
520                            'HTTP_POST_FILES');
521         
522         // Fix magic quotes.
523         if (get_magic_quotes_gpc()) {
524             foreach ($needs_fix as $vars)
525                 $this->_stripslashes($GLOBALS[$vars]);
526         }
527     }
528
529     function _stripslashes(&$var) {
530         if (is_array($var)) {
531             foreach ($var as $key => $val)
532                 $this->_stripslashes($var[$key]);
533         }
534         elseif (is_string($var))
535             $var = stripslashes($var);
536     }
537     
538     function _fix_multipart_form_data () {
539         if (preg_match('|^multipart/form-data|', $this->get('CONTENT_TYPE')))
540             $this->_strip_leading_nl($GLOBALS['HTTP_POST_VARS']);
541     }
542     
543     function _strip_leading_nl(&$var) {
544         if (is_array($var)) {
545             foreach ($var as $key => $val)
546                 $this->_strip_leading_nl($var[$key]);
547         }
548         elseif (is_string($var))
549             $var = preg_replace('|^\r?\n?|', '', $var);
550     }
551 }
552
553 class Request_SessionVars {
554     function Request_SessionVars() {
555         // Prevent cacheing problems with IE 5
556         session_cache_limiter('none');
557                                         
558         // Avoid to get a notice if session is already started,
559         // for example if session.auto_start is activated
560         if (!session_id())
561             session_start();
562     }
563     
564     function get($key) {
565         $vars = &$GLOBALS['HTTP_SESSION_VARS'];
566         if (isset($vars[$key]))
567             return $vars[$key];
568         if (isset($_SESSION) and isset($_SESSION[$key])) // php-5.2
569             return $_SESSION[$key];
570         return false;
571     }
572     
573     function set($key, $val) {
574         $vars = &$GLOBALS['HTTP_SESSION_VARS'];
575         if (!function_usable('get_cfg_var') or get_cfg_var('register_globals')) {
576             // This is funky but necessary, at least in some PHP's
577             $GLOBALS[$key] = $val;
578         }
579         $vars[$key] = $val;
580         if (isset($_SESSION)) // php-5.2
581             $_SESSION[$key] = $val;
582         session_register($key);
583     }
584     
585     function delete($key) {
586         $vars = &$GLOBALS['HTTP_SESSION_VARS'];
587         if (!function_usable('ini_get') or ini_get('register_globals'))
588             unset($GLOBALS[$key]);
589         if (DEBUG) trigger_error("delete session $key", E_USER_WARNING);
590         unset($vars[$key]);
591         session_unregister($key);
592     }
593 }
594
595 class Request_CookieVars {
596     
597     function get($key) {
598         $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
599         if (isset($vars[$key])) {
600             @$decode = base64_decode($vars[$key]);
601             if (strlen($decode) > 3 and substr($decode,1,1) == ':') {
602               @$val = unserialize($decode);
603               if (!empty($val))
604                   return $val;
605             }
606             @$val = urldecode($vars[$key]);
607             if (!empty($val))
608                 return $val;
609         }
610         return false;
611     }
612
613     function get_old($key) {
614         $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
615         if (isset($vars[$key])) {
616             @$decode = base64_decode($vars[$key]);
617             if (strlen($decode) > 3 and substr($decode,1,1) == ':') {
618               @$val = unserialize($decode);
619               if (!empty($val))
620                 return $val;
621             }
622             @$val = unserialize($vars[$key]);
623             if (!empty($val))
624                 return $val;
625             @$val = $vars[$key];
626             if (!empty($val))
627                 return $val;
628         }
629         return false;
630     }
631
632     function set($key, $val, $persist_days = false, $path = false) {
633         // if already defined, ignore
634         if (defined('MAIN_setUser') and $key = getCookieName()) return;
635         if (defined('WIKI_XMLRPC') and WIKI_XMLRPC) return;
636
637         $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
638         if (is_numeric($persist_days)) {
639             $expires = time() + (24 * 3600) * $persist_days;
640         }
641         else {
642             $expires = 0;
643         }
644         if (is_array($val) or is_object($val))
645             $packedval = base64_encode(serialize($val));
646         else
647             $packedval = urlencode($val);
648         $vars[$key] = $packedval;
649         @$_COOKIE[$key] = $packedval;
650         if ($path)
651             @setcookie($key, $packedval, $expires, $path);
652         else
653             @setcookie($key, $packedval, $expires);
654     }
655     
656     function delete($key) {
657         static $deleted = array();
658         if (isset($deleted[$key])) return;
659         if (defined('WIKI_XMLRPC') and WIKI_XMLRPC) return;
660         
661         $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
662         if (!defined('COOKIE_DOMAIN'))
663             @setcookie($key, '', 0);
664         else    
665             @setcookie($key, '', 0, COOKIE_DOMAIN);
666         unset($GLOBALS['HTTP_COOKIE_VARS'][$key]);
667         unset($_COOKIE[$key]);
668         $deleted[$key] = 1;
669     }
670 }
671
672 /* Win32 Note:
673    [\winnt\php.ini]
674    You must set "upload_tmp_dir" = "/tmp/" or "C:/tmp/"
675    Best on the same drive as apache, with forward slashes 
676    and with ending slash!
677    Otherwise "\\" => "" and the uploaded file will not be found.
678 */
679 class Request_UploadedFile {
680     function getUploadedFile($postname) {
681         global $HTTP_POST_FILES;
682
683         // Against php5 with !ini_get('register-long-arrays'). See Bug #1180115
684         if (empty($HTTP_POST_FILES) and !empty($_FILES))
685             $HTTP_POST_FILES =& $_FILES;
686         if (!isset($HTTP_POST_FILES[$postname]))
687             return false;
688         
689         $fileinfo =& $HTTP_POST_FILES[$postname];
690         if ($fileinfo['error']) {
691             // See https://sourceforge.net/forum/message.php?msg_id=3093651
692             $err = (int) $fileinfo['error'];
693             // errmsgs by Shilad Sen
694             switch ($err) {
695             case 1:
696                 trigger_error(_("Upload error: file too big"), E_USER_WARNING);
697                 break;
698             case 2:
699                 trigger_error(_("Upload error: file too big"), E_USER_WARNING);
700                 break;
701             case 3:
702                 trigger_error(_("Upload error: file only partially received"), E_USER_WARNING);
703                 break;
704             case 4:
705                 trigger_error(_("Upload error: no file selected"), E_USER_WARNING);
706                 break;
707             default:
708                 trigger_error(_("Upload error: unknown error #") . $err, E_USER_WARNING);
709             }
710             return false;
711         }
712
713         // With windows/php 4.2.1 is_uploaded_file() always returns false.
714         // Be sure that upload_tmp_dir ends with a slash!
715         if (!is_uploaded_file($fileinfo['tmp_name'])) {
716             if (isWindows()) {
717                 if (!$tmp_file = get_cfg_var('upload_tmp_dir')) {
718                     $tmp_file = dirname(tempnam('', ''));
719                 }
720                 $tmp_file .= '/' . basename($fileinfo['tmp_name']);
721                 /* ending slash in php.ini upload_tmp_dir is required. */
722                 if (realpath(ereg_replace('/+', '/', $tmp_file)) != realpath($fileinfo['tmp_name'])) {
723                     trigger_error(sprintf("Uploaded tmpfile illegal: %s != %s.",$tmp_file, $fileinfo['tmp_name']).
724                                   "\n".
725                                   "Probably illegal TEMP environment or upload_tmp_dir setting. ".
726                                   "Esp. on WINDOWS be sure to set upload_tmp_dir in php.ini to use forward slashes and ".
727                                   "end with a slash. upload_tmp_dir = \"C:/WINDOWS/TEMP/\" is good suggestion.",
728                                   E_USER_ERROR);
729                     return false;
730                 } else {
731                     /*
732                     trigger_error(sprintf("Workaround for PHP/Windows is_uploaded_file() problem for %s.",
733                                           $fileinfo['tmp_name'])."\n".
734                                   "Probably illegal TEMP environment or upload_tmp_dir setting.", 
735                                   E_USER_NOTICE);
736                     */
737                     ;
738                 }
739             } else {
740               trigger_error(sprintf("Uploaded tmpfile %s not found.", $fileinfo['tmp_name'])."\n".
741                            " Probably illegal TEMP environment or upload_tmp_dir setting.",
742                           E_USER_WARNING);
743             }
744         }
745         return new Request_UploadedFile($fileinfo);
746     }
747     
748     function Request_UploadedFile($fileinfo) {
749         $this->_info = $fileinfo;
750     }
751
752     function getSize() {
753         return $this->_info['size'];
754     }
755
756     function getName() {
757         return $this->_info['name'];
758     }
759
760     function getType() {
761         return $this->_info['type'];
762     }
763
764     function getTmpName() {
765         return $this->_info['tmp_name'];
766     }
767
768     function open() {
769         if ( ($fd = fopen($this->_info['tmp_name'], "rb")) ) {
770             if ($this->getSize() < filesize($this->_info['tmp_name'])) {
771                 // FIXME: Some PHP's (or is it some browsers?) put
772                 //    HTTP/MIME headers in the file body, some don't.
773                 //
774                 // At least, I think that's the case.  I know I used
775                 // to need this code, now I don't.
776                 //
777                 // This code is more-or-less untested currently.
778                 //
779                 // Dump HTTP headers.
780                 while ( ($header = fgets($fd, 4096)) ) {
781                     if (trim($header) == '') {
782                         break;
783                     }
784                     else if (!preg_match('/^content-(length|type):/i', $header)) {
785                         rewind($fd);
786                         break;
787                     }
788                 }
789             }
790         }
791         return $fd;
792     }
793
794     function getContents() {
795         $fd = $this->open();
796         $data = fread($fd, $this->getSize());
797         fclose($fd);
798         return $data;
799     }
800 }
801
802 /**
803  * Create NCSA "combined" log entry for current request.
804  * Also needed for advanced spam prevention.
805  * global object holding global state (sql or file, entries, to dump)
806  */
807 class Request_AccessLog {
808     /**
809      * @param $logfile string  Log file name.
810      */
811     function Request_AccessLog ($logfile, $do_sql = false) {
812         //global $request; // request not yet initialized!
813
814         $this->logfile = $logfile;
815         if ($logfile and !is_writeable($logfile)) {
816             trigger_error
817                 (sprintf(_("%s is not writable."), _("The PhpWiki access log file"))
818                  . "\n"
819                  . sprintf(_("Please ensure that %s is writable, or redefine %s in config/config.ini."),
820                            sprintf(_("the file '%s'"), ACCESS_LOG),
821                            'ACCESS_LOG')
822                  , E_USER_NOTICE);
823         }
824         //$request->_accesslog =& $this;
825         //if (empty($request->_accesslog->entries))
826         register_shutdown_function("Request_AccessLogEntry_shutdown_function");
827         
828         if ($do_sql) {
829             global $DBParams;
830             if (!in_array($DBParams['dbtype'], array('SQL','ADODB'))) {
831                 trigger_error("Unsupported database backend for ACCESS_LOG_SQL.\nNeed DATABASE_TYPE=SQL or ADODB");
832             } else {
833                 //$this->_dbi =& $request->_dbi;
834                 $this->logtable = (!empty($DBParams['prefix']) ? $DBParams['prefix'] : '')."accesslog";
835             }
836         }
837         $this->entries = array();
838         $this->entries[] = new Request_AccessLogEntry($this);
839     }
840
841     function _do($cmd, &$arg) {
842         if ($this->entries)
843             for ($i=0; $i < count($this->entries);$i++)
844                 $this->entries[$i]->$cmd($arg);
845     }
846     function push(&$request)   { $this->_do('push',$request); }
847     function setSize($arg)     { $this->_do('setSize',$arg); }
848     function setStatus($arg)   { $this->_do('setStatus',$arg); }
849     function setDuration($arg) { $this->_do('setDuration',$arg); }
850
851     /**
852      * Read sequentially all previous entries from the beginning.
853      * while ($logentry = Request_AccessLogEntry::read()) ;
854      * For internal log analyzers: RecentReferrers, WikiAccessRestrictions
855      */
856     function read() {
857         return $this->logtable ? $this->read_sql() : $this->read_file();
858     }
859
860     /**
861      * Return iterator of referer items reverse sorted (latest first).
862      */
863     function get_referer($limit=15, $external_only=false) {
864         if ($external_only) { // see stdlin.php:isExternalReferrer()
865             $base = SERVER_URL;
866             $blen = strlen($base);
867         }
868         if (!empty($this->_dbi)) {
869             // check same hosts in referer and request and remove them
870             $ext_where = " AND LEFT(referer,$blen) <> ".$this->_dbi->quote($base)
871                 ." AND LEFT(referer,$blen) <> LEFT(CONCAT(".$this->_dbi->quote(SERVER_URL).",request_uri),$blen)";
872             return $this->_read_sql_query("(referer <>'' AND NOT(ISNULL(referer)))"
873                                           .($external_only ? $ext_where : '')
874                                           ." ORDER BY time_stamp DESC"
875                                           .($limit ? " LIMIT $limit" : ""));
876         } else {
877             $iter = new WikiDB_Array_generic_iter(0);
878             $logs =& $iter->_array;
879             while ($logentry = $this->read_file()) {
880                 if (!empty($logentry->referer)
881                     and (!$external_only or (substr($logentry->referer,0,$blen) != $base)))
882                 {
883                     $iter->_array[] = $logentry;
884                     if ($limit and count($logs) > $limit)
885                         array_shift($logs);
886                 }
887             }
888             $logs = array_reverse($logs);
889             $logs = array_slice($logs,0,min($limit,count($logs)));
890             return $iter;
891         }
892     }
893
894     /**
895      * Return iterator of matching host items reverse sorted (latest first).
896      */
897     function get_host($host, $since_minutes=20) {
898         if ($this->logtable) {
899             // mysql specific only:
900             return $this->read_sql("request_host=".$this->_dbi->quote($host)." AND time_stamp > ". (time()-$since_minutes*60) 
901                             ." ORDER BY time_stamp DESC");
902         } else {
903             $iter = new WikiDB_Array_generic_iter();
904             $logs =& $iter->_array;
905             $logentry = new Request_AccessLogEntry($this);
906             while ($logentry->read_file()) {
907                 if (!empty($logentry->referer)) {
908                     $iter->_array[] = $logentry;
909                     if ($limit and count($logs) > $limit)
910                         array_shift($logs);
911                     $logentry = new Request_AccessLogEntry($this);
912                 }
913             }
914             $logs = array_reverse($logs);
915             $logs = array_slice($logs,0,min($limit,count($logs)));
916             return $iter;
917         }
918     }
919
920     /**
921      * Read sequentially all previous entries from log file.
922      */
923     function read_file() {
924         global $request;
925         if ($this->logfile) $this->logfile = ACCESS_LOG; // support Request_AccessLog::read
926
927         if (empty($this->reader))       // start at the beginning
928             $this->reader = fopen($this->logfile, "r");
929         if ($s = fgets($this->reader)) {
930             $entry = new Request_AccessLogEntry($this);
931             if (preg_match('/^(\S+)\s(\S+)\s(\S+)\s\[(.+?)\] "([^"]+)" (\d+) (\d+) "([^"]*)" "([^"]*)"$/',$s,$m)) {
932                 list(,$entry->host, $entry->ident, $entry->user, $entry->time,
933                      $entry->request, $entry->status, $entry->size,
934                      $entry->referer, $entry->user_agent) = $m;
935             }
936             return $entry;
937         } else { // until the end
938             fclose($this->reader);
939             return false;
940         }
941     }
942     function _read_sql_query($where='') {
943         $dbh =& $GLOBALS['request']->_dbi;
944         $log_tbl =& $this->logtable;
945         return $dbh->genericSqlIter("SELECT *,request_uri as request,request_time as time,remote_user as user,"
946                                     ."remote_host as host,agent as user_agent"
947                                     ." FROM $log_tbl"
948                                     . ($where ? " WHERE $where" : ""));
949     }
950     function read_sql($where='') {
951         if (empty($this->sqliter))
952             $this->sqliter = $this->_read_sql_query($where);
953         return $this->sqliter->next();
954     }
955
956     /* done in request->finish() before the db is closed */
957     function write_sql() {
958         $dbh =& $GLOBALS['request']->_dbi;
959         if (isset($this->entries) and $dbh and $dbh->isOpen())
960             foreach ($this->entries as $entry) {
961                 $entry->write_sql();
962             }
963     }
964     /* done in the shutdown callback */
965     function write_file() {
966         if (isset($this->entries) and $this->logfile)
967             foreach ($this->entries as $entry) {
968                 $entry->write_file();
969             }
970         unset($this->entries);
971     }
972     /* in an ideal world... */
973     function write() {
974         if ($this->logfile) $this->write_file();
975         if ($this->logtable) $this->write_sql();
976         unset($this->entries);
977     }
978 }
979
980 class Request_AccessLogEntry
981 {
982     /**
983      * Constructor.
984      *
985      * The log entry will be automatically appended to the log file or 
986      * SQL table when the current request terminates.
987      *
988      * If you want to modify a Request_AccessLogEntry before it gets
989      * written (e.g. via the setStatus and setSize methods) you should
990      * use an '&' on the constructor, so that you're working with the
991      * original (rather than a copy) object.
992      *
993      * <pre>
994      *    $log_entry = & new Request_AccessLogEntry("/tmp/wiki_access_log");
995      *    $log_entry->setStatus(401);
996      *    $log_entry->push($request);
997      * </pre>
998      *
999      *
1000      */
1001     function Request_AccessLogEntry (&$accesslog) {
1002         $this->_accesslog = $accesslog;
1003         $this->logfile = $accesslog->logfile;
1004         $this->time = time();
1005         $this->status = 200;    // see setStatus()
1006         $this->size = 0;        // see setSize()
1007     }
1008
1009     /**
1010      * @param $request object  Request object for current request.
1011      */
1012     function push(&$request) {
1013         $this->host  = $request->get('REMOTE_HOST');
1014         $this->ident = $request->get('REMOTE_IDENT');
1015         if (!$this->ident)
1016             $this->ident = '-';
1017         $user = $request->getUser();
1018         if ($user->isAuthenticated())
1019             $this->user = $user->UserName();
1020         else
1021             $this->user = '-';
1022         $this->request = join(' ', array($request->get('REQUEST_METHOD'),
1023                                          $request->get('REQUEST_URI'),
1024                                          $request->get('SERVER_PROTOCOL')));
1025         $this->referer = (string) $request->get('HTTP_REFERER');
1026         $this->user_agent = (string) $request->get('HTTP_USER_AGENT');
1027     }
1028
1029     /**
1030      * Set result status code.
1031      *
1032      * @param $status integer  HTTP status code.
1033      */
1034     function setStatus ($status) {
1035         $this->status = $status;
1036     }
1037     
1038     /**
1039      * Set response size.
1040      *
1041      * @param $size integer
1042      */
1043     function setSize ($size=0) {
1044         $this->size = (int)$size;
1045     }
1046     function setDuration ($seconds) {
1047         // Pear DB does not correctly quote , in floats using ?. e.g. in european locales.
1048         // Workaround:
1049         $this->duration = strtr(sprintf("%f", $seconds),",",".");
1050     }
1051     
1052     /**
1053      * Get time zone offset.
1054      *
1055      * This is a static member function.
1056      *
1057      * @param $time integer Unix timestamp (defaults to current time).
1058      * @return string Zone offset, e.g. "-0800" for PST.
1059      */
1060     function _zone_offset ($time = false) {
1061         if (!$time)
1062             $time = time();
1063         $offset = date("Z", $time);
1064         $negoffset = "";
1065         if ($offset < 0) {
1066             $negoffset = "-";
1067             $offset = -$offset;
1068         }
1069         $offhours = floor($offset / 3600);
1070         $offmins  = $offset / 60 - $offhours * 60;
1071         return sprintf("%s%02d%02d", $negoffset, $offhours, $offmins);
1072     }
1073
1074     /**
1075      * Format time in NCSA format.
1076      *
1077      * This is a static member function.
1078      *
1079      * @param $time integer Unix timestamp (defaults to current time).
1080      * @return string Formatted date & time.
1081      */
1082     function _ncsa_time($time = false) {
1083         if (!$time)
1084             $time = time();
1085         return date("d/M/Y:H:i:s", $time) .
1086             " " . $this->_zone_offset();
1087     }
1088
1089     function write() {
1090         if ($this->_accesslog->logfile) $this->write_file();
1091         if ($this->_accesslog->logtable) $this->write_sql();
1092     }
1093
1094     /**
1095      * Write entry to log file.
1096      */
1097     function write_file() {
1098         $entry = sprintf('%s %s %s [%s] "%s" %d %d "%s" "%s"',
1099                          $this->host, $this->ident, $this->user,
1100                          $this->_ncsa_time($this->time),
1101                          $this->request, $this->status, $this->size,
1102                          $this->referer, $this->user_agent);
1103         if (!empty($this->_accesslog->reader)) {
1104             fclose($this->_accesslog->reader);
1105             unset($this->_accesslog->reader);
1106         }
1107         //Error log doesn't provide locking.
1108         //error_log("$entry\n", 3, $this->logfile);
1109         // Alternate method
1110         if (($fp = fopen($this->logfile, "a"))) {
1111             flock($fp, LOCK_EX);
1112             fputs($fp, "$entry\n");
1113             fclose($fp);
1114         }
1115     }
1116
1117     /* This is better been done by apache mod_log_sql */
1118     /* If ACCESS_LOG_SQL & 2 we do write it by our own */
1119     function write_sql() {
1120         global $request;
1121         
1122         $dbh =& $request->_dbi;
1123         if ($dbh and $dbh->isOpen() and $this->_accesslog->logtable) {
1124             //$log_tbl =& $this->_accesslog->logtable;
1125             if ($request->get('REQUEST_METHOD') == "POST") {
1126                 // strangely HTTP_POST_VARS doesn't contain all posted vars.
1127                 $args = $_POST; // copy not ref. clone not needed on hashes
1128                 // garble passwords
1129                 if (!empty($args['auth']['passwd']))    $args['auth']['passwd'] = '<not displayed>';
1130                 if (!empty($args['dbadmin']['passwd'])) $args['dbadmin']['passwd'] = '<not displayed>';
1131                 if (!empty($args['pref']['passwd']))    $args['pref']['passwd'] = '<not displayed>';
1132                 if (!empty($args['pref']['passwd2']))   $args['pref']['passwd2'] = '<not displayed>';
1133                 $this->request_args = substr(serialize($args),0,254); // if VARCHAR(255) is used.
1134             } else {
1135                 $this->request_args = $request->get('QUERY_STRING'); 
1136             }
1137             $this->request_method = $request->get('REQUEST_METHOD');
1138             $this->request_uri = $request->get('REQUEST_URI');
1139             // duration problem: sprintf "%f" might use comma e.g. "100,201" in european locales
1140             $dbh->_backend->write_accesslog($this);
1141         }
1142     }
1143 }
1144
1145 /**
1146  * Shutdown callback.
1147  *
1148  * @access private
1149  * @see Request_AccessLogEntry
1150  */
1151 function Request_AccessLogEntry_shutdown_function () {
1152     global $request;
1153     
1154     if (isset($request->_accesslog->entries) and $request->_accesslog->logfile)
1155         foreach ($request->_accesslog->entries as $entry) {
1156             $entry->write_file();
1157         }
1158     unset($request->_accesslog->entries);
1159 }
1160
1161
1162 class HTTP_ETag {
1163     function HTTP_ETag($val, $is_weak=false) {
1164         $this->_val = wikihash($val);
1165         $this->_weak = $is_weak;
1166     }
1167
1168     /** Comparison
1169      *
1170      * Strong comparison: If either (or both) tag is weak, they
1171      *  are not equal.
1172      */
1173     function equals($that, $strong_match=false) {
1174         if ($this->_val != $that->_val)
1175             return false;
1176         if ($strong_match and ($this->_weak or $that->_weak))
1177             return false;
1178         return true;
1179     }
1180
1181
1182     function asString() {
1183         $quoted = '"' . addslashes($this->_val) . '"';
1184         return $this->_weak ? "W/$quoted" : $quoted;
1185     }
1186
1187     /** Parse tag from header.
1188      *
1189      * This is a static member function.
1190      */
1191     function parse($strval) {
1192         if (!preg_match(':^(W/)?"(.+)"$:i', trim($strval), $m))
1193             return false;       // parse failed
1194         list(,$weak,$str) = $m;
1195         return new HTTP_ETag(stripslashes($str), $weak);
1196     }
1197
1198     function matches($taglist, $strong_match=false) {
1199         $taglist = trim($taglist);
1200
1201         if ($taglist == '*') {
1202             if ($strong_match)
1203                 return ! $this->_weak;
1204             else
1205                 return true;
1206         }
1207
1208         while (preg_match('@^(W/)?"((?:\\\\.|[^"])*)"\s*,?\s*@i',
1209                           $taglist, $m)) {
1210             list($match, $weak, $str) = $m;
1211             $taglist = substr($taglist, strlen($match));
1212             $tag = new HTTP_ETag(stripslashes($str), $weak);
1213             if ($this->equals($tag, $strong_match)) {
1214                 return true;
1215             }
1216         }
1217         return false;
1218     }
1219 }
1220
1221 // Possible results from the HTTP_ValidatorSet::_check*() methods.
1222 // (Higher numerical values take precedence.)
1223 define ('_HTTP_VAL_PASS', 0);           // Test is irrelevant
1224 define ('_HTTP_VAL_NOT_MODIFIED', 1);   // Test passed, content not changed
1225 define ('_HTTP_VAL_MODIFIED', 2);       // Test failed, content changed
1226 define ('_HTTP_VAL_FAILED', 3);         // Precondition failed.
1227
1228 class HTTP_ValidatorSet {
1229     function HTTP_ValidatorSet($validators) {
1230         $this->_mtime = $this->_weak = false;
1231         $this->_tag = array();
1232         
1233         foreach ($validators as $key => $val) {
1234             if ($key == '%mtime') {
1235                 $this->_mtime = $val;
1236             }
1237             elseif ($key == '%weak') {
1238                 if ($val)
1239                     $this->_weak = true;
1240             }
1241             else {
1242                 $this->_tag[$key] = $val;
1243             }
1244         }
1245     }
1246
1247     function append($that) {
1248         if (is_array($that))
1249             $that = new HTTP_ValidatorSet($that);
1250
1251         // Pick the most recent mtime
1252         if (isset($that->_mtime))
1253             if (!isset($this->_mtime) || $that->_mtime > $this->_mtime)
1254                 $this->_mtime = $that->_mtime;
1255
1256         // If either is weak, we're weak
1257         if (!empty($that->_weak))
1258             $this->_weak = true;
1259         if (is_array($this->_tag))
1260             $this->_tag = array_merge($this->_tag, $that->_tag);
1261         else
1262             $this->_tag = $that->_tag;
1263     }
1264
1265     function getETag() {
1266         if (! $this->_tag)
1267             return false;
1268         return new HTTP_ETag($this->_tag, $this->_weak);
1269     }
1270
1271     function getModificationTime() {
1272         return $this->_mtime;
1273     }
1274     
1275     function checkConditionalRequest (&$request) {
1276         $result = max($this->_checkIfUnmodifiedSince($request),
1277                       $this->_checkIfModifiedSince($request),
1278                       $this->_checkIfMatch($request),
1279                       $this->_checkIfNoneMatch($request));
1280
1281         if ($result == _HTTP_VAL_PASS || $result == _HTTP_VAL_MODIFIED)
1282             return false;       // "please proceed with normal processing"
1283         elseif ($result == _HTTP_VAL_FAILED)
1284             return 412;         // "412 Precondition Failed"
1285         elseif ($result == _HTTP_VAL_NOT_MODIFIED)
1286             return 304;         // "304 Not Modified"
1287
1288         trigger_error("Ack, shouldn't get here", E_USER_ERROR);
1289         return false;
1290     }
1291
1292     function _checkIfUnmodifiedSince(&$request) {
1293         if ($this->_mtime !== false) {
1294             $since = ParseRfc1123DateTime($request->get("HTTP_IF_UNMODIFIED_SINCE"));
1295             if ($since !== false && $this->_mtime > $since)
1296                 return _HTTP_VAL_FAILED;
1297         }
1298         return _HTTP_VAL_PASS;
1299     }
1300
1301     function _checkIfModifiedSince(&$request) {
1302         if ($this->_mtime !== false and $request->isGetOrHead()) {
1303             $since = ParseRfc1123DateTime($request->get("HTTP_IF_MODIFIED_SINCE"));
1304             if ($since !== false) {
1305                 if ($this->_mtime <= $since)
1306                     return _HTTP_VAL_NOT_MODIFIED;
1307                 return _HTTP_VAL_MODIFIED;
1308             }
1309         }
1310         return _HTTP_VAL_PASS;
1311     }
1312
1313     function _checkIfMatch(&$request) {
1314         if ($this->_tag && ($taglist = $request->get("HTTP_IF_MATCH"))) {
1315             $tag = $this->getETag();
1316             if (!$tag->matches($taglist, 'strong'))
1317                 return _HTTP_VAL_FAILED;
1318         }
1319         return _HTTP_VAL_PASS;
1320     }
1321
1322     function _checkIfNoneMatch(&$request) {
1323         if ($this->_tag && ($taglist = $request->get("HTTP_IF_NONE_MATCH"))) {
1324             $tag = $this->getETag();
1325             $strong_compare = ! $request->isGetOrHead();
1326             if ($taglist) {
1327                 if ($tag->matches($taglist, $strong_compare)) {
1328                     if ($request->isGetOrHead())
1329                         return _HTTP_VAL_NOT_MODIFIED;
1330                     else
1331                         return _HTTP_VAL_FAILED;
1332                 }
1333                 return _HTTP_VAL_MODIFIED;
1334             }
1335         }
1336         return _HTTP_VAL_PASS;
1337     }
1338 }
1339
1340 // Local Variables:
1341 // mode: php
1342 // tab-width: 8
1343 // c-basic-offset: 4
1344 // c-hanging-comment-ender-p: nil
1345 // indent-tabs-mode: nil
1346 // End:   
1347 ?>