4 * Copyright (C) 2002,2004,2005,2006,2009 $ThePhpWikiProgrammingTeam
6 * This file is part of PhpWiki.
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.
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.
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.
25 public $args = array();
29 $this->_fix_magic_quotes_gpc();
30 $this->_fix_multipart_form_data();
32 switch ($this->get('REQUEST_METHOD')) {
35 $this->args = &$GLOBALS['HTTP_GET_VARS'];
38 $this->args = &$GLOBALS['HTTP_POST_VARS'];
41 $this->args = array();
45 $this->session = new Request_SessionVars;
46 $this->cookies = new Request_CookieVars;
48 if (ACCESS_LOG or ACCESS_LOG_SQL) {
49 $this->_accesslog = new Request_AccessLog(ACCESS_LOG, ACCESS_LOG_SQL);
52 $GLOBALS['request'] = $this;
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
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",
67 if (isset($vars[$key]))
72 $addr = $vars['REMOTE_ADDR'];
73 if (defined('ENABLE_REVERSE_DNS') && ENABLE_REVERSE_DNS)
74 return $vars[$key] = gethostbyaddr($addr);
84 if (isset($this->args[$key]))
85 return $this->args[$key];
94 function setArg($key, $val)
97 unset($this->args[$key]);
99 $this->args[$key] = $val;
102 // Well oh well. Do we really want to pass POST params back as GET?
103 function getURLtoSelf($args = false, $exclude = array())
105 $get_args = $this->args;
107 $get_args = array_merge($get_args, $args);
109 // leave out empty arg values
110 foreach ($get_args as $g => $v) {
111 if ($v === false or $v === '') unset($get_args[$g]);
114 // Err... good point...
116 if ($this->isPost()) {
117 $exclude = array_merge($exclude, array('action', 'auth'));
118 //$get_args = $args; // or only the provided
120 trigger_error("Request::getURLtoSelf() should probably not be from POST",
125 foreach ($exclude as $ex) {
126 if (!empty($get_args[$ex])) unset($get_args[$ex]);
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']);
134 return WikiURL($pagename, $get_args);
139 return $this->get("REQUEST_METHOD") == "POST";
142 function isGetOrHead()
144 return in_array($this->get('REQUEST_METHOD'),
145 array('GET', 'HEAD'));
148 function httpVersion()
150 if (!preg_match('@HTTP\s*/\s*(\d+.\d+)@', $this->get('SERVER_PROTOCOL'), $m))
155 /* Redirects after edit may fail if no theme signature image is defined.
156 * Set DISABLE_HTTP_REDIRECT = true then.
158 function redirect($url, $noreturn = true)
160 $bogus = defined('DISABLE_HTTP_REDIRECT') && DISABLE_HTTP_REDIRECT;
163 header("Location: $url");
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.
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.)
175 * Fortunately, most/all browsers don't do that.
177 * "303 See Other" is what we really want. But it only
180 * FIXME: this is still not spec compliant for HTTP
183 $status = $this->httpVersion() >= 1.1 ? 303 : 302;
184 $this->setStatus($status);
188 $this->discardOutput(); // This might print the gzip headers. Not good.
189 $this->buffer_output(false);
191 include_once 'lib/Template.php';
192 $tmpl = new Template('redirect', $this, array('REDIRECT_URL' => $url));
196 // Safari needs window.location.href = targeturl
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;
206 window.location = url;
208 redirect('" . addslashes($url) . "')");
212 /** Set validators for this response.
214 * This sets a (possibly incomplete) set of validators
217 * The validator set can be extended using appendValidators().
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.
225 * $request->setValidators(array('pagename' => $pagename,
226 * '%mtime' => $rev->get('mtime')));
228 * // Wups... response content depends on $otherpage, too...
229 * $request->appendValidators(array('otherpage' => $otherpagerev->getPageName(),
230 * '%mtime' => $otherpagerev->get('mtime')));
232 * // After all validators have been set:
233 * $request->checkValidators();
235 function setValidators($validator_set)
237 if (is_array($validator_set))
238 $validator_set = new HTTP_ValidatorSet($validator_set);
239 $this->_validators = $validator_set;
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.
246 function appendValidators($validator_set)
248 if (!isset($this->_validators)) {
249 $this->setValidators($validator_set);
252 $this->_validators->append($validator_set);
255 /** Check validators and set headers in HTTP response
257 * This sets the appropriate "Last-Modified" and "ETag"
258 * headers in the HTTP response.
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.
265 function checkValidators()
267 $validators = &$this->_validators;
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));
276 // Set cache control headers
277 $this->cacheControl();
280 if (CACHE_CONTROL == 'NO_CACHE')
281 return; // don't check conditionals...
283 // Check conditional headers in request
284 $status = $validators->checkConditionalRequest($this);
286 // Return short response due to failed conditionals
287 $this->setStatus($status);
289 $this->discardOutput();
295 /** Set the cache control headers in the HTTP response.
297 function cacheControl($strategy = CACHE_CONTROL, $max_age = CACHE_CONTROL_MAX_AGE)
299 if ($strategy == 'NO_CACHE') {
300 $cache_control = "no-cache"; // better set private. See Pear HTTP_Header
302 } elseif ($strategy == 'ALLOW_STALE' && $max_age > 0) {
303 $cache_control = sprintf("max-age=%d", $max_age);
305 $cache_control = "must-revalidate";
308 header("Cache-Control: $cache_control");
309 header("Expires: " . Rfc1123DateTime(time() + $max_age));
310 header("Vary: Cookie"); // FIXME: add more here?
313 function setStatus($status)
315 if (preg_match('|^HTTP/.*?\s(\d+)|i', $status, $m)) {
319 $status = (integer)$status;
320 $reason = array('200' => 'OK',
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]));
333 if (isset($this->_log_entry))
334 $this->_log_entry->setStatus($status);
337 function buffer_output($compress = true)
339 // FIXME: disables sessions (some byte before all headers_sent())
340 /*if (defined('USECACHE') and !USECACHE) {
341 $this->_is_buffering_output = false;
344 if (defined('COMPRESS_OUTPUT')) {
345 if (!COMPRESS_OUTPUT)
347 } elseif (isCGI()) // necessary?
350 if ($this->getArg('start_debug')) $compress = false;
351 if ($this->getArg('nocache'))
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.
358 and (!function_exists('ob_gzhandler')
359 or !function_exists('apache_note'))
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"))
368 // New: we check for the client Accept-Encoding: "gzip" presence also
369 // This should eliminate a lot or reported problems.
371 and (!$this->get("HTTP_ACCEPT_ENCODING")
372 or !strstr($this->get("HTTP_ACCEPT_ENCODING"), "gzip"))
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
382 and $this->getArg('format')
383 and strstr($this->getArg('format'), 'rss')
388 ob_start('phpwiki_gzhandler');
390 // TODO: dont send a length or get the gzip'ed data length.
391 $this->_is_compressing_output = true;
392 header("Content-Encoding: gzip");
394 * Attempt to prevent Apache from doing the dreaded double-gzip.
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.
400 if (function_exists('apache_note'))
401 @apache_note('no-gzip', 1);
403 // Now we alway buffer output.
404 // This is so we can set HTTP headers (e.g. for redirect)
406 // FIXME: change the name of this method.
408 $this->_is_compressing_output = false;
410 $this->_is_buffering_output = true;
411 $this->_ob_get_length = 0;
414 function discardOutput()
416 if (!empty($this->_is_buffering_output)) {
417 if (ob_get_length()) ob_clean();
418 $this->_is_buffering_output = false;
420 trigger_error("Not buffering output", E_USER_NOTICE);
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.
431 function chunkOutput()
433 if (!empty($this->_is_buffering_output)
435 (function_exists('ob_get_level') and @ob_get_level())
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) {
443 if (ob_get_level() > 0) {
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);
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();
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();
474 header(sprintf("Content-Length: %d", $this->_ob_get_length));
477 $this->_is_buffering_output = false;
479 } elseif (function_exists('ob_get_level') and @ob_get_level()) {
482 session_write_close();
483 if (!empty($this->_dbi)) {
484 $this->_dbi->close();
491 function getSessionVar($key)
493 return $this->session->get($key);
496 function setSessionVar($key, $val)
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);
509 if (ENABLE_USER_NEW) {
510 unset($val->_HomePagehandle);
511 unset($val->_auth_dbi);
514 unset($val->_authdbi);
515 unset($val->_homepage);
516 unset($val->_request);
519 return $this->session->set($key, $val);
522 function deleteSessionVar($key)
524 return $this->session->delete($key);
527 function getCookieVar($key)
529 return $this->cookies->get($key);
532 function setCookieVar($key, $val, $lifetime_in_days = false, $path = false)
534 return $this->cookies->set($key, $val, $lifetime_in_days, $path);
537 function deleteCookieVar($key)
539 return $this->cookies->delete($key);
542 function getUploadedFile($key)
544 return Request_UploadedFile::getUploadedFile($key);
547 function _fix_magic_quotes_gpc()
549 $needs_fix = array('HTTP_POST_VARS',
556 if (get_magic_quotes_gpc()) {
557 foreach ($needs_fix as $vars)
558 $this->_stripslashes($GLOBALS[$vars]);
562 function _stripslashes(&$var)
564 if (is_array($var)) {
565 foreach ($var as $key => $val)
566 $this->_stripslashes($var[$key]);
567 } elseif (is_string($var))
568 $var = stripslashes($var);
571 function _fix_multipart_form_data()
573 if (preg_match('|^multipart/form-data|', $this->get('CONTENT_TYPE')))
574 $this->_strip_leading_nl($GLOBALS['HTTP_POST_VARS']);
577 function _strip_leading_nl(&$var)
579 if (is_array($var)) {
580 foreach ($var as $key => $val)
581 $this->_strip_leading_nl($var[$key]);
582 } elseif (is_string($var))
583 $var = preg_replace('|^\r?\n?|', '', $var);
587 class Request_SessionVars
589 function Request_SessionVars()
591 // Prevent cacheing problems with IE 5
592 session_cache_limiter('none');
594 // Avoid to get a notice if session is already started,
595 // for example if session.auto_start is activated
602 $vars = &$GLOBALS['HTTP_SESSION_VARS'];
603 if (isset($vars[$key]))
605 if (isset($_SESSION) and isset($_SESSION[$key])) // php-5.2
606 return $_SESSION[$key];
610 function set($key, $val)
612 $vars = &$GLOBALS['HTTP_SESSION_VARS'];
613 if (!function_usable('get_cfg_var') or get_cfg_var('register_globals')) {
614 // This is funky but necessary, at least in some PHP's
615 $GLOBALS[$key] = $val;
618 if (isset($_SESSION)) // php-5.2
619 $_SESSION[$key] = $val;
620 if (!check_php_version(5, 3))
621 session_register($key);
624 function delete($key)
626 $vars = &$GLOBALS['HTTP_SESSION_VARS'];
627 if (!function_usable('ini_get') or ini_get('register_globals'))
628 unset($GLOBALS[$key]);
629 if (DEBUG) trigger_error("delete session $key", E_USER_WARNING);
631 if (isset($_SESSION)) // php-5.2
632 unset($_SESSION[$key]);
633 if (!check_php_version(5, 3))
634 session_unregister($key);
638 class Request_CookieVars
643 $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
644 if (isset($vars[$key])) {
645 @$decode = base64_decode($vars[$key]);
646 if (strlen($decode) > 3 and substr($decode, 1, 1) == ':') {
647 @$val = unserialize($decode);
651 @$val = urldecode($vars[$key]);
658 function get_old($key)
660 if (defined('FUSIONFORGE') and FUSIONFORGE) {
663 $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
664 if (isset($vars[$key])) {
665 @$decode = base64_decode($vars[$key]);
666 if (strlen($decode) > 3 and substr($decode, 1, 1) == ':') {
667 @$val = unserialize($decode);
671 @$val = unserialize($vars[$key]);
681 function set($key, $val, $persist_days = false, $path = false)
683 // if already defined, ignore
684 if (defined('MAIN_setUser') and $key = getCookieName()) return;
685 if (defined('WIKI_XMLRPC') and WIKI_XMLRPC) return;
687 $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
688 if (is_numeric($persist_days)) {
689 $expires = time() + (24 * 3600) * $persist_days;
693 if (is_array($val) or is_object($val))
694 $packedval = base64_encode(serialize($val));
696 $packedval = urlencode($val);
697 $vars[$key] = $packedval;
698 @$_COOKIE[$key] = $packedval;
700 @setcookie($key, $packedval, $expires, $path);
702 @setcookie($key, $packedval, $expires);
705 function delete($key)
707 static $deleted = array();
708 if (isset($deleted[$key])) return;
709 if (defined('WIKI_XMLRPC') and WIKI_XMLRPC) return;
711 $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
712 if (!defined('COOKIE_DOMAIN'))
713 @setcookie($key, '', 0);
715 @setcookie($key, '', 0, COOKIE_DOMAIN);
716 unset($GLOBALS['HTTP_COOKIE_VARS'][$key]);
717 unset($_COOKIE[$key]);
724 You must set "upload_tmp_dir" = "/tmp/" or "C:/tmp/"
725 Best on the same drive as apache, with forward slashes
726 and with ending slash!
727 Otherwise "\\" => "" and the uploaded file will not be found.
729 class Request_UploadedFile
731 function getUploadedFile($postname)
733 global $HTTP_POST_FILES;
735 // Against php5 with !ini_get('register-long-arrays'). See Bug #1180115
736 if (empty($HTTP_POST_FILES) and !empty($_FILES))
737 $HTTP_POST_FILES =& $_FILES;
738 if (!isset($HTTP_POST_FILES[$postname]))
741 $fileinfo =& $HTTP_POST_FILES[$postname];
742 if ($fileinfo['error']) {
743 // See https://sourceforge.net/forum/message.php?msg_id=3093651
744 $err = (int)$fileinfo['error'];
745 // errmsgs by Shilad Sen
748 trigger_error(_("Upload error: file too big"), E_USER_WARNING);
751 trigger_error(_("Upload error: file too big"), E_USER_WARNING);
754 trigger_error(_("Upload error: file only partially received"), E_USER_WARNING);
757 trigger_error(_("Upload error: no file selected"), E_USER_WARNING);
760 trigger_error(_("Upload error: unknown error #") . $err, E_USER_WARNING);
765 // With windows/php 4.2.1 is_uploaded_file() always returns false.
766 // Be sure that upload_tmp_dir ends with a slash!
767 if (!is_uploaded_file($fileinfo['tmp_name'])) {
769 if (!$tmp_file = get_cfg_var('upload_tmp_dir')) {
770 $tmp_file = dirname(tempnam('', ''));
772 $tmp_file .= '/' . basename($fileinfo['tmp_name']);
773 /* ending slash in php.ini upload_tmp_dir is required. */
774 if (realpath(ereg_replace('/+', '/', $tmp_file)) != realpath($fileinfo['tmp_name'])) {
775 trigger_error(sprintf("Uploaded tmpfile illegal: %s != %s.", $tmp_file, $fileinfo['tmp_name']) .
777 "Probably illegal TEMP environment or upload_tmp_dir setting. " .
778 "Esp. on WINDOWS be sure to set upload_tmp_dir in php.ini to use forward slashes and " .
779 "end with a slash. upload_tmp_dir = \"C:/WINDOWS/TEMP/\" is good suggestion.",
784 trigger_error(sprintf("Workaround for PHP/Windows is_uploaded_file() problem for %s.",
785 $fileinfo['tmp_name'])."\n".
786 "Probably illegal TEMP environment or upload_tmp_dir setting.",
792 trigger_error(sprintf("Uploaded tmpfile %s not found.", $fileinfo['tmp_name']) . "\n" .
793 " Probably illegal TEMP environment or upload_tmp_dir setting.",
797 return new Request_UploadedFile($fileinfo);
800 function Request_UploadedFile($fileinfo)
802 $this->_info = $fileinfo;
807 return $this->_info['size'];
812 return $this->_info['name'];
817 return $this->_info['type'];
820 function getTmpName()
822 return $this->_info['tmp_name'];
827 if (($fd = fopen($this->_info['tmp_name'], "rb"))) {
828 if ($this->getSize() < filesize($this->_info['tmp_name'])) {
829 // FIXME: Some PHP's (or is it some browsers?) put
830 // HTTP/MIME headers in the file body, some don't.
832 // At least, I think that's the case. I know I used
833 // to need this code, now I don't.
835 // This code is more-or-less untested currently.
837 // Dump HTTP headers.
838 while (($header = fgets($fd, 4096))) {
839 if (trim($header) == '') {
841 } elseif (!preg_match('/^content-(length|type):/i', $header)) {
851 function getContents()
854 $data = fread($fd, $this->getSize());
861 * Create NCSA "combined" log entry for current request.
862 * Also needed for advanced spam prevention.
863 * global object holding global state (sql or file, entries, to dump)
865 class Request_AccessLog
868 * @param $logfile string Log file name.
870 function Request_AccessLog($logfile, $do_sql = false)
872 //global $request; // request not yet initialized!
874 $this->logfile = $logfile;
875 if ($logfile and !is_writeable($logfile)) {
877 (sprintf(_("%s is not writable."), _("The PhpWiki access log file"))
879 . sprintf(_("Please ensure that %s is writable, or redefine %s in config/config.ini."),
880 sprintf(_("the file “%s”"), ACCESS_LOG),
884 //$request->_accesslog =& $this;
885 //if (empty($request->_accesslog->entries))
886 register_shutdown_function("Request_AccessLogEntry_shutdown_function");
890 if (!in_array($DBParams['dbtype'], array('SQL', 'ADODB'))) {
891 trigger_error("Unsupported database backend for ACCESS_LOG_SQL.\nNeed DATABASE_TYPE=SQL or ADODB");
893 //$this->_dbi =& $request->_dbi;
894 $this->logtable = (!empty($DBParams['prefix']) ? $DBParams['prefix'] : '') . "accesslog";
897 $this->entries = array();
898 $this->entries[] = new Request_AccessLogEntry($this);
901 function _do($cmd, &$arg)
904 for ($i = 0; $i < count($this->entries); $i++)
905 $this->entries[$i]->$cmd($arg);
908 function push(&$request)
910 $this->_do('push', $request);
913 function setSize($arg)
915 $this->_do('setSize', $arg);
918 function setStatus($arg)
920 $this->_do('setStatus', $arg);
923 function setDuration($arg)
925 $this->_do('setDuration', $arg);
929 * Read sequentially all previous entries from the beginning.
930 * while ($logentry = Request_AccessLogEntry::read()) ;
931 * For internal log analyzers: RecentReferrers, WikiAccessRestrictions
935 return $this->logtable ? $this->read_sql() : $this->read_file();
939 * Return iterator of referer items reverse sorted (latest first).
941 function get_referer($limit = 15, $external_only = false)
943 if ($external_only) { // see stdlin.php:isExternalReferrer()
945 $blen = strlen($base);
947 if (!empty($this->_dbi)) {
948 // check same hosts in referer and request and remove them
949 $ext_where = " AND LEFT(referer,$blen) <> " . $this->_dbi->quote($base)
950 . " AND LEFT(referer,$blen) <> LEFT(CONCAT(" . $this->_dbi->quote(SERVER_URL) . ",request_uri),$blen)";
951 return $this->_read_sql_query("(referer <>'' AND NOT(ISNULL(referer)))"
952 . ($external_only ? $ext_where : '')
953 . " ORDER BY time_stamp DESC"
954 . ($limit ? " LIMIT $limit" : ""));
956 $iter = new WikiDB_Array_generic_iter(0);
957 $logs =& $iter->_array;
958 while ($logentry = $this->read_file()) {
959 if (!empty($logentry->referer)
960 and (!$external_only or (substr($logentry->referer, 0, $blen) != $base))
962 $iter->_array[] = $logentry;
963 if ($limit and count($logs) > $limit)
967 $logs = array_reverse($logs);
968 $logs = array_slice($logs, 0, min($limit, count($logs)));
974 * Read sequentially all previous entries from log file.
979 if ($this->logfile) $this->logfile = ACCESS_LOG; // support Request_AccessLog::read
981 if (empty($this->reader)) // start at the beginning
982 $this->reader = fopen($this->logfile, "r");
983 if ($s = fgets($this->reader)) {
984 $entry = new Request_AccessLogEntry($this);
985 if (preg_match('/^(\S+)\s(\S+)\s(\S+)\s\[(.+?)\] "([^"]+)" (\d+) (\d+) "([^"]*)" "([^"]*)"$/', $s, $m)) {
986 list(, $entry->host, $entry->ident, $entry->user, $entry->time,
987 $entry->request, $entry->status, $entry->size,
988 $entry->referer, $entry->user_agent) = $m;
991 } else { // until the end
992 fclose($this->reader);
997 function _read_sql_query($where = '')
999 $dbh =& $GLOBALS['request']->_dbi;
1000 $log_tbl =& $this->logtable;
1001 return $dbh->genericSqlIter("SELECT *,request_uri as request,request_time as time,remote_user as user,"
1002 . "remote_host as host,agent as user_agent"
1004 . ($where ? " WHERE $where" : ""));
1007 function read_sql($where = '')
1009 if (empty($this->sqliter))
1010 $this->sqliter = $this->_read_sql_query($where);
1011 return $this->sqliter->next();
1014 /* done in request->finish() before the db is closed */
1015 function write_sql()
1017 $dbh =& $GLOBALS['request']->_dbi;
1018 if (isset($this->entries) and $dbh and $dbh->isOpen())
1019 foreach ($this->entries as $entry) {
1020 $entry->write_sql();
1024 /* done in the shutdown callback */
1025 function write_file()
1027 if (isset($this->entries) and $this->logfile)
1028 foreach ($this->entries as $entry) {
1029 $entry->write_file();
1031 unset($this->entries);
1034 /* in an ideal world... */
1037 if ($this->logfile) $this->write_file();
1038 if ($this->logtable) $this->write_sql();
1039 unset($this->entries);
1043 class Request_AccessLogEntry
1048 * The log entry will be automatically appended to the log file or
1049 * SQL table when the current request terminates.
1051 * If you want to modify a Request_AccessLogEntry before it gets
1052 * written (e.g. via the setStatus and setSize methods) you should
1053 * use an '&' on the constructor, so that you're working with the
1054 * original (rather than a copy) object.
1057 * $log_entry = & new Request_AccessLogEntry("/tmp/wiki_access_log");
1058 * $log_entry->setStatus(401);
1059 * $log_entry->push($request);
1064 function Request_AccessLogEntry(&$accesslog)
1066 $this->_accesslog = $accesslog;
1067 $this->logfile = $accesslog->logfile;
1068 $this->time = time();
1069 $this->status = 200; // see setStatus()
1070 $this->size = 0; // see setSize()
1074 * @param $request object Request object for current request.
1076 function push(&$request)
1078 $this->host = $request->get('REMOTE_HOST');
1079 $this->ident = $request->get('REMOTE_IDENT');
1082 $user = $request->getUser();
1083 if ($user->isAuthenticated())
1084 $this->user = $user->UserName();
1087 $this->request = join(' ', array($request->get('REQUEST_METHOD'),
1088 $request->get('REQUEST_URI'),
1089 $request->get('SERVER_PROTOCOL')));
1090 $this->referer = (string)$request->get('HTTP_REFERER');
1091 $this->user_agent = (string)$request->get('HTTP_USER_AGENT');
1095 * Set result status code.
1097 * @param $status integer HTTP status code.
1099 function setStatus($status)
1101 $this->status = $status;
1105 * Set response size.
1107 * @param $size integer
1109 function setSize($size = 0)
1111 $this->size = (int)$size;
1114 function setDuration($seconds)
1116 // Pear DB does not correctly quote , in floats using ?. e.g. in european locales.
1118 $this->duration = strtr(sprintf("%f", $seconds), ",", ".");
1122 * Get time zone offset.
1124 * This is a static member function.
1126 * @param $time integer Unix timestamp (defaults to current time).
1127 * @return string Zone offset, e.g. "-0800" for PST.
1129 function _zone_offset($time = false)
1133 $offset = date("Z", $time);
1139 $offhours = floor($offset / 3600);
1140 $offmins = $offset / 60 - $offhours * 60;
1141 return sprintf("%s%02d%02d", $negoffset, $offhours, $offmins);
1145 * Format time in NCSA format.
1147 * This is a static member function.
1149 * @param $time integer Unix timestamp (defaults to current time).
1150 * @return string Formatted date & time.
1152 function _ncsa_time($time = false)
1156 return date("d/M/Y:H:i:s", $time) .
1157 " " . $this->_zone_offset();
1162 if ($this->_accesslog->logfile) $this->write_file();
1163 if ($this->_accesslog->logtable) $this->write_sql();
1167 * Write entry to log file.
1169 function write_file()
1171 $entry = sprintf('%s %s %s [%s] "%s" %d %d "%s" "%s"',
1172 $this->host, $this->ident, $this->user,
1173 $this->_ncsa_time($this->time),
1174 $this->request, $this->status, $this->size,
1175 $this->referer, $this->user_agent);
1176 if (!empty($this->_accesslog->reader)) {
1177 fclose($this->_accesslog->reader);
1178 unset($this->_accesslog->reader);
1180 //Error log doesn't provide locking.
1181 //error_log("$entry\n", 3, $this->logfile);
1183 if (($fp = fopen($this->logfile, "a"))) {
1184 flock($fp, LOCK_EX);
1185 fputs($fp, "$entry\n");
1190 /* This is better been done by apache mod_log_sql */
1191 /* If ACCESS_LOG_SQL & 2 we do write it by our own */
1192 function write_sql()
1196 $dbh =& $request->_dbi;
1197 if ($dbh and $dbh->isOpen() and $this->_accesslog->logtable) {
1198 //$log_tbl =& $this->_accesslog->logtable;
1199 if ($request->get('REQUEST_METHOD') == "POST") {
1200 // strangely HTTP_POST_VARS doesn't contain all posted vars.
1201 $args = $_POST; // copy not ref. clone not needed on hashes
1203 if (!empty($args['auth']['passwd'])) $args['auth']['passwd'] = '<not displayed>';
1204 if (!empty($args['dbadmin']['passwd'])) $args['dbadmin']['passwd'] = '<not displayed>';
1205 if (!empty($args['pref']['passwd'])) $args['pref']['passwd'] = '<not displayed>';
1206 if (!empty($args['pref']['passwd2'])) $args['pref']['passwd2'] = '<not displayed>';
1207 $this->request_args = substr(serialize($args), 0, 254); // if VARCHAR(255) is used.
1209 $this->request_args = $request->get('QUERY_STRING');
1211 $this->request_method = $request->get('REQUEST_METHOD');
1212 $this->request_uri = $request->get('REQUEST_URI');
1213 // duration problem: sprintf "%f" might use comma e.g. "100,201" in european locales
1214 $dbh->_backend->write_accesslog($this);
1220 * Shutdown callback.
1223 * @see Request_AccessLogEntry
1225 function Request_AccessLogEntry_shutdown_function()
1229 if (isset($request->_accesslog->entries) and $request->_accesslog->logfile)
1230 foreach ($request->_accesslog->entries as $entry) {
1231 $entry->write_file();
1233 unset($request->_accesslog->entries);
1238 function HTTP_ETag($val, $is_weak = false)
1240 $this->_val = wikihash($val);
1241 $this->_weak = $is_weak;
1246 * Strong comparison: If either (or both) tag is weak, they
1249 function equals($that, $strong_match = false)
1251 if ($this->_val != $that->_val)
1253 if ($strong_match and ($this->_weak or $that->_weak))
1260 $quoted = '"' . addslashes($this->_val) . '"';
1261 return $this->_weak ? "W/$quoted" : $quoted;
1264 /** Parse tag from header.
1266 * This is a static member function.
1268 function parse($strval)
1270 if (!preg_match(':^(W/)?"(.+)"$:i', trim($strval), $m))
1271 return false; // parse failed
1272 list(, $weak, $str) = $m;
1273 return new HTTP_ETag(stripslashes($str), $weak);
1276 function matches($taglist, $strong_match = false)
1278 $taglist = trim($taglist);
1280 if ($taglist == '*') {
1282 return !$this->_weak;
1287 while (preg_match('@^(W/)?"((?:\\\\.|[^"])*)"\s*,?\s*@i',
1289 list($match, $weak, $str) = $m;
1290 $taglist = substr($taglist, strlen($match));
1291 $tag = new HTTP_ETag(stripslashes($str), $weak);
1292 if ($this->equals($tag, $strong_match)) {
1300 // Possible results from the HTTP_ValidatorSet::_check*() methods.
1301 // (Higher numerical values take precedence.)
1302 define ('_HTTP_VAL_PASS', 0); // Test is irrelevant
1303 define ('_HTTP_VAL_NOT_MODIFIED', 1); // Test passed, content not changed
1304 define ('_HTTP_VAL_MODIFIED', 2); // Test failed, content changed
1305 define ('_HTTP_VAL_FAILED', 3); // Precondition failed.
1307 class HTTP_ValidatorSet
1309 function HTTP_ValidatorSet($validators)
1311 $this->_mtime = $this->_weak = false;
1312 $this->_tag = array();
1314 foreach ($validators as $key => $val) {
1315 if ($key == '%mtime') {
1316 $this->_mtime = $val;
1317 } elseif ($key == '%weak') {
1319 $this->_weak = true;
1321 $this->_tag[$key] = $val;
1326 function append($that)
1328 if (is_array($that))
1329 $that = new HTTP_ValidatorSet($that);
1331 // Pick the most recent mtime
1332 if (isset($that->_mtime))
1333 if (!isset($this->_mtime) || $that->_mtime > $this->_mtime)
1334 $this->_mtime = $that->_mtime;
1336 // If either is weak, we're weak
1337 if (!empty($that->_weak))
1338 $this->_weak = true;
1339 if (is_array($this->_tag))
1340 $this->_tag = array_merge($this->_tag, $that->_tag);
1342 $this->_tag = $that->_tag;
1349 return new HTTP_ETag($this->_tag, $this->_weak);
1352 function getModificationTime()
1354 return $this->_mtime;
1357 function checkConditionalRequest(&$request)
1359 $result = max($this->_checkIfUnmodifiedSince($request),
1360 $this->_checkIfModifiedSince($request),
1361 $this->_checkIfMatch($request),
1362 $this->_checkIfNoneMatch($request));
1364 if ($result == _HTTP_VAL_PASS || $result == _HTTP_VAL_MODIFIED)
1365 return false; // "please proceed with normal processing"
1366 elseif ($result == _HTTP_VAL_FAILED)
1367 return 412; // "412 Precondition Failed"
1368 elseif ($result == _HTTP_VAL_NOT_MODIFIED)
1369 return 304; // "304 Not Modified"
1371 trigger_error("Ack, shouldn't get here", E_USER_ERROR);
1375 function _checkIfUnmodifiedSince(&$request)
1377 if ($this->_mtime !== false) {
1378 $since = ParseRfc1123DateTime($request->get("HTTP_IF_UNMODIFIED_SINCE"));
1379 if ($since !== false && $this->_mtime > $since)
1380 return _HTTP_VAL_FAILED;
1382 return _HTTP_VAL_PASS;
1385 function _checkIfModifiedSince(&$request)
1387 if ($this->_mtime !== false and $request->isGetOrHead()) {
1388 $since = ParseRfc1123DateTime($request->get("HTTP_IF_MODIFIED_SINCE"));
1389 if ($since !== false) {
1390 if ($this->_mtime <= $since)
1391 return _HTTP_VAL_NOT_MODIFIED;
1392 return _HTTP_VAL_MODIFIED;
1395 return _HTTP_VAL_PASS;
1398 function _checkIfMatch(&$request)
1400 if ($this->_tag && ($taglist = $request->get("HTTP_IF_MATCH"))) {
1401 $tag = $this->getETag();
1402 if (!$tag->matches($taglist, 'strong'))
1403 return _HTTP_VAL_FAILED;
1405 return _HTTP_VAL_PASS;
1408 function _checkIfNoneMatch(&$request)
1410 if ($this->_tag && ($taglist = $request->get("HTTP_IF_NONE_MATCH"))) {
1411 $tag = $this->getETag();
1412 $strong_compare = !$request->isGetOrHead();
1414 if ($tag->matches($taglist, $strong_compare)) {
1415 if ($request->isGetOrHead())
1416 return _HTTP_VAL_NOT_MODIFIED;
1418 return _HTTP_VAL_FAILED;
1420 return _HTTP_VAL_MODIFIED;
1423 return _HTTP_VAL_PASS;
1430 // c-basic-offset: 4
1431 // c-hanging-comment-ender-p: nil
1432 // indent-tabs-mode: nil