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