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