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