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