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