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();
27 private $_is_compressing_output;
28 public $_is_buffering_output;
29 public $_ob_get_length;
30 private $_do_chunked_output;
33 function __construct()
37 $this->_fix_multipart_form_data();
39 switch ($this->get('REQUEST_METHOD')) {
42 $this->args = &$GLOBALS['HTTP_GET_VARS'];
45 $this->args = &$GLOBALS['HTTP_POST_VARS'];
48 $this->args = array();
52 $this->session = new Request_SessionVars;
53 $this->cookies = new Request_CookieVars;
55 if (ACCESS_LOG or ACCESS_LOG_SQL) {
56 $this->_accesslog = new Request_AccessLog(ACCESS_LOG, ACCESS_LOG_SQL);
64 if (!empty($GLOBALS['HTTP_SERVER_VARS']))
65 $vars = &$GLOBALS['HTTP_SERVER_VARS'];
66 elseif (!empty($GLOBALS['HTTP_ENV_VARS']))
67 $vars = &$GLOBALS['HTTP_ENV_VARS']; // cgi or other servers than Apache
69 trigger_error("Serious php configuration error!"
70 . " No HTTP_SERVER_VARS and HTTP_ENV_VARS vars available."
71 . " These should get defined in lib/prepend.php",
74 if (isset($vars[$key]))
79 $addr = $vars['REMOTE_ADDR'];
80 if (defined('ENABLE_REVERSE_DNS') && ENABLE_REVERSE_DNS)
81 return $vars[$key] = gethostbyaddr($addr);
95 if (isset($this->args[$key]))
96 return $this->args[$key];
105 function setArg($key, $val)
108 unset($this->args[$key]);
110 $this->args[$key] = $val;
113 // Well oh well. Do we really want to pass POST params back as GET?
114 function getURLtoSelf($args = array(), $exclude = array())
116 $get_args = $this->args;
118 $get_args = array_merge($get_args, $args);
120 // leave out empty arg values
121 foreach ($get_args as $g => $v) {
122 if ($v === false or $v === '') unset($get_args[$g]);
125 // Err... good point...
127 if ($this->isPost()) {
128 $exclude = array_merge($exclude, array('action', 'auth'));
129 //$get_args = $args; // or only the provided
131 trigger_error("Request::getURLtoSelf() should probably not be from POST",
136 foreach ($exclude as $ex) {
137 if (!empty($get_args[$ex])) unset($get_args[$ex]);
140 $pagename = $get_args['pagename'];
141 unset ($get_args['pagename']);
142 if (!empty($get_args['action']) and $get_args['action'] == 'browse')
143 unset($get_args['action']);
145 return WikiURL($pagename, $get_args);
150 return $this->get("REQUEST_METHOD") == "POST";
153 function isGetOrHead()
155 return in_array($this->get('REQUEST_METHOD'),
156 array('GET', 'HEAD'));
159 function httpVersion()
161 if (!preg_match('@HTTP\s*/\s*(\d+.\d+)@', $this->get('SERVER_PROTOCOL'), $m))
166 /* Redirects after edit may fail if no theme signature image is defined.
167 * Set DISABLE_HTTP_REDIRECT = true then.
169 function redirect($url, $noreturn = true)
171 $bogus = defined('DISABLE_HTTP_REDIRECT') && DISABLE_HTTP_REDIRECT;
174 header("Location: $url");
176 * "302 Found" is not really meant to be sent in response
177 * to a POST. Worse still, according to (both HTTP 1.0
178 * and 1.1) spec, the user, if it is sent, the user agent
179 * is supposed to use the same method to fetch the
180 * redirected URI as the original.
182 * That means if we redirect from a POST, the user-agent
183 * supposed to generate another POST. Not what we want.
184 * (We do this after a page save after all.)
186 * Fortunately, most/all browsers don't do that.
188 * "303 See Other" is what we really want. But it only
191 * FIXME: this is still not spec compliant for HTTP
194 $status = $this->httpVersion() >= 1.1 ? 303 : 302;
195 $this->setStatus($status);
199 $this->discardOutput(); // This might print the gzip headers. Not good.
200 $this->buffer_output(false);
202 include_once 'lib/Template.php';
203 $tmpl = new Template('redirect', $this, array('REDIRECT_URL' => $url));
207 // Safari needs window.location.href = targeturl
209 function redirect(url) {
210 if (typeof location.replace == 'function')
211 location.replace(url);
212 else if (typeof location.assign == 'function')
213 location.assign(url);
214 else if (self.location.href)
215 self.location.href = url;
217 window.location = url;
219 redirect('" . addslashes($url) . "')");
223 /** Set validators for this response.
225 * This sets a (possibly incomplete) set of validators
228 * The validator set can be extended using appendValidators().
230 * When you're all done setting and appending validators, you
231 * must call checkValidators() to check them and set the
232 * appropriate headers in the HTTP response.
236 * $request->setValidators(array('pagename' => $pagename,
237 * '%mtime' => $rev->get('mtime')));
239 * // Wups... response content depends on $otherpage, too...
240 * $request->appendValidators(array('otherpage' => $otherpagerev->getPageName(),
241 * '%mtime' => $otherpagerev->get('mtime')));
243 * // After all validators have been set:
244 * $request->checkValidators();
246 function setValidators($validator_set)
248 if (is_array($validator_set))
249 $validator_set = new HTTP_ValidatorSet($validator_set);
250 $this->_validators = $validator_set;
253 /** Append more validators for this response.
254 * i.e dependencies on other pages mtimes
255 * now it may be called in init also to simplify client code.
257 function appendValidators($validator_set)
259 if (!isset($this->_validators)) {
260 $this->setValidators($validator_set);
263 $this->_validators->append($validator_set);
266 /** Check validators and set headers in HTTP response
268 * This sets the appropriate "Last-Modified" and "ETag"
269 * headers in the HTTP response.
271 * Additionally, if the validators match any(all) conditional
272 * headers in the HTTP request, this method will not return, but
273 * instead will send "304 Not Modified" or "412 Precondition
274 * Failed" (as appropriate) back to the client.
276 function checkValidators()
278 $validators = &$this->_validators;
280 // Set validator headers
281 if (!empty($this->_is_buffering_output) or !headers_sent()) {
282 if (($etag = $validators->getETag()) !== false)
283 header("ETag: " . $etag->asString());
284 if (($mtime = $validators->getModificationTime()) !== false)
285 header("Last-Modified: " . Rfc1123DateTime($mtime));
287 // Set cache control headers
288 $this->cacheControl();
291 if (CACHE_CONTROL == 'NO_CACHE')
292 return; // don't check conditionals...
294 // Check conditional headers in request
295 $status = $validators->checkConditionalRequest($this);
297 // Return short response due to failed conditionals
298 $this->setStatus($status);
300 $this->discardOutput();
306 /** Set the cache control headers in the HTTP response.
308 function cacheControl($strategy = CACHE_CONTROL, $max_age = CACHE_CONTROL_MAX_AGE)
310 if ($strategy == 'NO_CACHE') {
311 $cache_control = "no-cache"; // better set private. See Pear HTTP_Header
313 } elseif ($strategy == 'ALLOW_STALE' && $max_age > 0) {
314 $cache_control = sprintf("max-age=%d", $max_age);
316 $cache_control = "must-revalidate";
319 header("Cache-Control: $cache_control");
320 header("Expires: " . Rfc1123DateTime(time() + $max_age));
321 header("Vary: Cookie"); // FIXME: add more here?
324 function setStatus($status)
326 if (preg_match('|^HTTP/.*?\s(\d+)|i', $status, $m)) {
330 $status = (integer)$status;
331 $reason = array('200' => 'OK',
333 '303' => 'See Other',
334 '304' => 'Not Modified',
335 '400' => 'Bad Request',
336 '401' => 'Unauthorized',
337 '403' => 'Forbidden',
338 '404' => 'Not Found',
339 '412' => 'Precondition Failed');
340 // FIXME: is it always okay to send HTTP/1.1 here, even for older clients?
341 header(sprintf("HTTP/1.1 %d %s", $status, $reason[$status]));
344 if (isset($this->_log_entry))
345 $this->_log_entry->setStatus($status);
348 function buffer_output($compress = true)
350 // FIXME: disables sessions (some byte before all headers_sent())
351 /*if (defined('USECACHE') and !USECACHE) {
352 $this->_is_buffering_output = false;
355 if (defined('COMPRESS_OUTPUT')) {
356 if (!COMPRESS_OUTPUT)
358 } elseif (isCGI()) // necessary?
361 if ($this->getArg('start_debug')) $compress = false;
362 if ($this->getArg('nocache'))
365 // Should we compress even when apache_note is not available?
366 // sf.net bug #933183 and http://bugs.php.net/17557
367 // This effectively eliminates CGI, but all other servers also. hmm.
369 and (!function_exists('ob_gzhandler')
370 or !function_exists('apache_note'))
374 // "output handler 'ob_gzhandler' cannot be used twice"
375 // http://www.php.net/ob_gzhandler
376 if ($compress and ini_get("zlib.output_compression"))
379 // New: we check for the client Accept-Encoding: "gzip" presence also
380 // This should eliminate a lot or reported problems.
382 and (!$this->get("HTTP_ACCEPT_ENCODING")
383 or !strstr($this->get("HTTP_ACCEPT_ENCODING"), "gzip"))
387 // Most RSS clients are NOT(!) application/xml gzip compatible yet.
388 // Even if they are sending the accept-encoding gzip header!
389 // wget is, Mozilla, and MSIE no.
390 // Of the RSS readers only MagpieRSS 0.5.2 is. http://www.rssgov.com/rssparsers.html
392 and $this->getArg('format')
393 and strstr($this->getArg('format'), 'rss')
398 ob_start('phpwiki_gzhandler');
400 // TODO: dont send a length or get the gzip'ed data length.
401 $this->_is_compressing_output = true;
402 header("Content-Encoding: gzip");
404 * Attempt to prevent Apache from doing the dreaded double-gzip.
406 * It would be better if we could detect when apache was going
407 * to zip for us, and then let it ... but I have yet to figure
408 * out how to do that.
410 if (function_exists('apache_note'))
411 @apache_note('no-gzip', 1);
413 // Now we alway buffer output.
414 // This is so we can set HTTP headers (e.g. for redirect)
416 // FIXME: change the name of this method.
418 $this->_is_compressing_output = false;
420 $this->_is_buffering_output = true;
421 $this->_ob_get_length = 0;
424 function discardOutput()
426 if (!empty($this->_is_buffering_output)) {
427 if (ob_get_length()) ob_clean();
428 $this->_is_buffering_output = false;
430 trigger_error(_("Not buffering output"), E_USER_NOTICE);
435 * Longer texts need too much memory on tiny or memory-limit=8MB systems.
436 * We might want to flush our buffer and restart again.
437 * (This would be fine if php would release its memory)
438 * Note that this must not be called inside Template expansion or other
439 * sections with ob_buffering.
441 function chunkOutput()
443 if (!empty($this->_is_buffering_output)
446 $this->_do_chunked_output = true;
447 if (empty($this->_ob_get_length)) $this->_ob_get_length = 0;
448 $this->_ob_get_length += ob_get_length();
449 while (ob_get_level() > 0) {
452 if (ob_get_level() > 0) {
461 $this->_finishing = true;
462 if (!empty($this->_accesslog)) {
463 $this->_accesslog->push($this);
464 if (empty($this->_do_chunked_output) and empty($this->_ob_get_length))
465 $this->_ob_get_length = ob_get_length();
466 $this->_accesslog->setSize($this->_ob_get_length);
468 if ($RUNTIMER) $this->_accesslog->setDuration($RUNTIMER->getTime());
469 // sql logging must be done before the db is closed.
470 if (isset($this->_accesslog->logtable))
471 $this->_accesslog->write_sql();
474 if (!empty($this->_is_buffering_output)) {
475 // if _is_compressing_output then ob_get_length() returns
476 // the uncompressed length, not the gzip'ed as required.
477 if (!headers_sent() and !$this->_is_compressing_output) {
478 // php url-rewriting miscalculates the ob length. fixes bug #1376007
479 if (ini_get('use_trans_sid') == 'off') {
480 if (empty($this->_do_chunked_output)) {
481 $this->_ob_get_length = ob_get_length();
483 header(sprintf("Content-Length: %d", $this->_ob_get_length));
486 $this->_is_buffering_output = false;
488 } elseif (@ob_get_level()) {
491 session_write_close();
492 if (!empty($this->_dbi)) {
493 $this->_dbi->close();
500 function getSessionVar($key)
502 return $this->session->get($key);
505 function setSessionVar($key, $val)
507 if ($key == 'wiki_user') {
508 if (empty($val->page))
509 $val->page = $this->getArg('pagename');
510 if (empty($val->action))
511 $val->action = $this->getArg('action');
512 // avoid recursive objects and session resource handles
513 // avoid overlarge session data (max 4000 byte!)
514 if (isset($val->_group)) {
515 unset($val->_group->_request);
516 unset($val->_group->user);
518 unset($val->_HomePagehandle);
519 unset($val->_auth_dbi);
521 $this->session->set($key, $val);
524 function getCookieVar($key)
526 return $this->cookies->get($key);
529 function setCookieVar($key, $val, $lifetime_in_days = false, $path = false)
531 $this->cookies->set($key, $val, $lifetime_in_days, $path);
534 function deleteCookieVar($key)
536 $this->cookies->delete($key);
539 function getUploadedFile($key)
541 return Request_UploadedFile::getUploadedFile($key);
544 private function _stripslashes(&$var)
546 if (is_array($var)) {
547 foreach ($var as $key => $val)
548 $this->_stripslashes($var[$key]);
549 } elseif (is_string($var))
550 $var = stripslashes($var);
553 private function _fix_multipart_form_data()
555 if (preg_match('|^multipart/form-data|', $this->get('CONTENT_TYPE')))
556 $this->_strip_leading_nl($GLOBALS['HTTP_POST_VARS']);
559 private function _strip_leading_nl(&$var)
561 if (is_array($var)) {
562 foreach ($var as $key => $val)
563 $this->_strip_leading_nl($var[$key]);
564 } elseif (is_string($var))
565 $var = preg_replace('|^\r?\n?|', '', $var);
569 class Request_SessionVars
571 function __construct()
573 // Prevent cacheing problems with IE 5
574 session_cache_limiter('none');
576 // Avoid to get a notice if session is already started,
577 // for example if session.auto_start is activated
584 $vars = &$GLOBALS['HTTP_SESSION_VARS'];
585 if (isset($vars[$key]))
587 if (isset($_SESSION) and isset($_SESSION[$key])) // php-5.2
588 return $_SESSION[$key];
592 function set($key, $val)
594 $vars = &$GLOBALS['HTTP_SESSION_VARS'];
595 if (!function_usable('get_cfg_var') or get_cfg_var('register_globals')) {
596 // This is funky but necessary, at least in some PHP's
597 $GLOBALS[$key] = $val;
600 if (isset($_SESSION)) // php-5.2
601 $_SESSION[$key] = $val;
604 function delete($key)
606 $vars = &$GLOBALS['HTTP_SESSION_VARS'];
607 if (!function_usable('ini_get') or ini_get('register_globals'))
608 unset($GLOBALS[$key]);
610 trigger_error("delete session $key", E_USER_WARNING);
612 if (isset($_SESSION)) // php-5.2
613 unset($_SESSION[$key]);
617 class Request_CookieVars
622 $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
623 if (isset($vars[$key])) {
624 @$decode = base64_decode($vars[$key]);
625 if (strlen($decode) > 3 and substr($decode, 1, 1) == ':') {
626 @$val = unserialize($decode);
630 @$val = urldecode($vars[$key]);
637 function get_old($key)
639 if (defined('FUSIONFORGE') && FUSIONFORGE) {
642 $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
643 if (isset($vars[$key])) {
644 @$decode = base64_decode($vars[$key]);
645 if (strlen($decode) > 3 and substr($decode, 1, 1) == ':') {
646 @$val = unserialize($decode);
650 @$val = unserialize($vars[$key]);
660 function set($key, $val, $persist_days = false, $path = false)
662 // if already defined, ignore
663 if (defined('MAIN_setUser') and $key = getCookieName()) return;
664 if (defined('WIKI_XMLRPC') and WIKI_XMLRPC) return;
666 $vars = &$GLOBALS['HTTP_COOKIE_VARS'];
667 if (is_numeric($persist_days)) {
668 $expires = time() + (24 * 3600) * $persist_days;
672 if (is_array($val) or is_object($val))
673 $packedval = base64_encode(serialize($val));
675 $packedval = urlencode($val);
676 $vars[$key] = $packedval;
677 @$_COOKIE[$key] = $packedval;
679 @setcookie($key, $packedval, $expires, $path);
681 @setcookie($key, $packedval, $expires);
684 function delete($key)
686 static $deleted = array();
687 if (isset($deleted[$key])) return;
688 if (defined('WIKI_XMLRPC') and WIKI_XMLRPC) return;
690 if (!defined('COOKIE_DOMAIN'))
691 @setcookie($key, '', 0);
693 @setcookie($key, '', 0, COOKIE_DOMAIN);
694 unset($GLOBALS['HTTP_COOKIE_VARS'][$key]);
695 unset($_COOKIE[$key]);
702 You must set "upload_tmp_dir" = "/tmp/" or "C:/tmp/"
703 Best on the same drive as apache, with forward slashes
704 and with ending slash!
705 Otherwise "\\" => "" and the uploaded file will not be found.
707 class Request_UploadedFile
709 function __construct($fileinfo)
711 $this->_info = $fileinfo;
714 static function getUploadedFile($postname)
716 global $HTTP_POST_FILES;
718 // Against php5 with !ini_get('register-long-arrays'). See Bug #1180115
719 if (empty($HTTP_POST_FILES) and !empty($_FILES))
720 $HTTP_POST_FILES =& $_FILES;
721 if (!isset($HTTP_POST_FILES[$postname]))
724 $fileinfo =& $HTTP_POST_FILES[$postname];
725 if ($fileinfo['error']) {
726 // See https://sourceforge.net/forum/message.php?msg_id=3093651
727 $err = (int)$fileinfo['error'];
728 // errmsgs by Shilad Sen
731 trigger_error(_("Upload error: file too big"), E_USER_WARNING);
734 trigger_error(_("Upload error: file too big"), E_USER_WARNING);
737 trigger_error(_("Upload error: file only partially received"), E_USER_WARNING);
740 trigger_error(_("Upload error: no file selected"), E_USER_WARNING);
743 trigger_error(_("Upload error: unknown error #") . $err, E_USER_WARNING);
748 // With windows/php 4.2.1 is_uploaded_file() always returns false.
749 // Be sure that upload_tmp_dir ends with a slash!
750 if (!is_uploaded_file($fileinfo['tmp_name'])) {
752 if (!$tmp_file = get_cfg_var('upload_tmp_dir')) {
753 $tmp_file = dirname(tempnam('', ''));
755 $tmp_file .= '/' . basename($fileinfo['tmp_name']);
756 /* ending slash in php.ini upload_tmp_dir is required. */
757 if (realpath(ereg_replace('/+', '/', $tmp_file)) != realpath($fileinfo['tmp_name'])) {
758 trigger_error(sprintf("Uploaded tmpfile illegal: %s != %s.", $tmp_file, $fileinfo['tmp_name']) .
760 "Probably illegal TEMP environment or upload_tmp_dir setting. " .
761 "Esp. on WINDOWS be sure to set upload_tmp_dir in php.ini to use forward slashes and " .
762 "end with a slash. upload_tmp_dir = \"C:/WINDOWS/TEMP/\" is good suggestion.",
767 trigger_error(sprintf("Uploaded tmpfile %s not found.", $fileinfo['tmp_name']) . "\n" .
768 " Probably illegal TEMP environment or upload_tmp_dir setting.",
772 return new Request_UploadedFile($fileinfo);
777 return $this->_info['size'];
782 return $this->_info['name'];
787 return $this->_info['type'];
790 function getTmpName()
792 return $this->_info['tmp_name'];
797 if (($fd = fopen($this->_info['tmp_name'], "rb"))) {
798 if ($this->getSize() < filesize($this->_info['tmp_name'])) {
799 // FIXME: Some PHP's (or is it some browsers?) put
800 // HTTP/MIME headers in the file body, some don't.
802 // At least, I think that's the case. I know I used
803 // to need this code, now I don't.
805 // This code is more-or-less untested currently.
807 // Dump HTTP headers.
808 while (($header = fgets($fd, 4096))) {
809 if (trim($header) == '') {
811 } elseif (!preg_match('/^content-(length|type):/i', $header)) {
821 function getContents()
824 $data = fread($fd, $this->getSize());
831 * Create NCSA "combined" log entry for current request.
832 * Also needed for advanced spam prevention.
833 * global object holding global state (sql or file, entries, to dump)
835 class Request_AccessLog
841 * @param string $logfile Log file name.
842 * @param bool $do_sql
844 function __construct($logfile, $do_sql = false)
846 $this->logfile = $logfile;
847 if ($logfile and !is_writeable($logfile)) {
849 (sprintf(_("%s is not writable."), _("The PhpWiki access log file"))
851 . sprintf(_("Please ensure that %s is writable, or redefine %s in config/config.ini."),
852 sprintf(_("the file “%s”"), ACCESS_LOG),
856 register_shutdown_function("Request_AccessLogEntry_shutdown_function");
860 if (!in_array($DBParams['dbtype'], array('SQL', 'ADODB', 'PDO'))) {
861 trigger_error(_("Unsupported database backend for ACCESS_LOG_SQL. Need DATABASE_TYPE=SQL or ADODB or PDO."));
863 $this->logtable = (!empty($DBParams['prefix']) ? $DBParams['prefix'] : '') . "accesslog";
866 $this->entries = array();
867 $this->entries[] = new Request_AccessLogEntry($this);
870 function _do($cmd, &$arg)
873 for ($i = 0; $i < count($this->entries); $i++)
874 $this->entries[$i]->$cmd($arg);
877 function push(&$request)
879 $this->_do('push', $request);
882 function setSize($arg)
884 $this->_do('setSize', $arg);
887 function setStatus($arg)
889 $this->_do('setStatus', $arg);
892 function setDuration($arg)
894 $this->_do('setDuration', $arg);
898 * Read sequentially all previous entries from the beginning.
899 * while ($logentry = Request_AccessLogEntry::read()) ;
900 * For internal log analyzers: RecentReferrers, WikiAccessRestrictions
904 return $this->logtable ? $this->read_sql() : $this->read_file();
908 * Return iterator of referrer items reverse sorted (latest first).
911 * @param bool $external_only
912 * @return WikiDB_Array_generic_iter
914 function get_referer($limit = 15, $external_only = false)
916 if ($external_only) { // see stdlin.php:isExternalReferrer()
921 $blen = strlen($base);
922 if (!empty($this->_dbi)) {
923 // check same hosts in referer and request and remove them
924 $ext_where = " AND LEFT(referer,$blen) <> " . $this->_dbi->quote($base)
925 . " AND LEFT(referer,$blen) <> LEFT(CONCAT(" . $this->_dbi->quote(SERVER_URL) . ",request_uri),$blen)";
926 return $this->_read_sql_query("(referer <>'' AND NOT(ISNULL(referer)))"
927 . ($external_only ? $ext_where : '')
928 . " ORDER BY time_stamp DESC"
929 . ($limit ? " LIMIT $limit" : ""));
931 $iter = new WikiDB_Array_generic_iter(0);
932 $logs =& $iter->_array;
933 while ($logentry = $this->read_file()) {
934 if (!empty($logentry->referer)
935 and (!$external_only or (substr($logentry->referer, 0, $blen) != $base))
937 $iter->_array[] = $logentry;
938 if ($limit and count($logs) > $limit)
942 $logs = array_reverse($logs);
943 $logs = array_slice($logs, 0, min($limit, count($logs)));
949 * Read sequentially backwards all previous entries from log file.
954 if ($this->logfile) $this->logfile = ACCESS_LOG; // support Request_AccessLog::read
956 if (empty($this->reader)) // start at the beginning
957 $this->reader = fopen($this->logfile, "r");
958 if ($s = fgets($this->reader)) {
959 $entry = new Request_AccessLogEntry($this);
960 if (preg_match('/^(\S+)\s(\S+)\s(\S+)\s\[(.+?)\] "([^"]+)" (\d+) (\d+) "([^"]*)" "([^"]*)"$/', $s, $m)) {
961 list(, $entry->host, $entry->ident, $entry->user, $entry->time,
962 $entry->request, $entry->status, $entry->size,
963 $entry->referer, $entry->user_agent) = $m;
966 } else { // until the end
967 fclose($this->reader);
972 function _read_sql_query($where = '')
975 $dbh =& $request->_dbi;
976 $log_tbl =& $this->logtable;
977 return $dbh->genericSqlIter("SELECT *,request_uri as request,request_time as time,remote_user as user,"
978 . "remote_host as host,agent as user_agent"
980 . ($where ? " WHERE $where" : ""));
983 function read_sql($where = '')
985 if (empty($this->sqliter))
986 $this->sqliter = $this->_read_sql_query($where);
987 return $this->sqliter->next();
990 /* done in request->finish() before the db is closed */
994 $dbh =& $request->_dbi;
995 if (isset($this->entries) and $dbh and $dbh->isOpen())
996 foreach ($this->entries as $entry) {
1001 /* done in the shutdown callback */
1002 function write_file()
1004 if (isset($this->entries) and $this->logfile)
1005 foreach ($this->entries as $entry) {
1006 $entry->write_file();
1008 unset($this->entries);
1011 /* in an ideal world... */
1014 if ($this->logfile) $this->write_file();
1015 if ($this->logtable) $this->write_sql();
1016 unset($this->entries);
1020 class Request_AccessLogEntry
1029 public $request_args;
1030 public $request_method;
1031 public $request_uri;
1034 * The log entry will be automatically appended to the log file or
1035 * SQL table when the current request terminates.
1037 * If you want to modify a Request_AccessLogEntry before it gets
1038 * written (e.g. via the setStatus and setSize methods) you should
1039 * use an '&' on the constructor, so that you're working with the
1040 * original (rather than a copy) object.
1043 * $log_entry = & new Request_AccessLogEntry("/tmp/wiki_access_log");
1044 * $log_entry->setStatus(401);
1045 * $log_entry->push($request);
1049 function __construct(&$accesslog)
1051 $this->_accesslog = $accesslog;
1052 $this->logfile = $accesslog->logfile;
1053 $this->time = time();
1054 $this->status = 200; // see setStatus()
1055 $this->size = 0; // see setSize()
1059 * @param $request object Request object for current request.
1061 function push(&$request)
1063 $this->host = $request->get('REMOTE_HOST');
1064 $this->ident = $request->get('REMOTE_IDENT');
1067 $user = $request->getUser();
1068 if ($user->isAuthenticated())
1069 $this->user = $user->UserName();
1072 $this->request = join(' ', array($request->get('REQUEST_METHOD'),
1073 $request->get('REQUEST_URI'),
1074 $request->get('SERVER_PROTOCOL')));
1075 $this->referer = (string)$request->get('HTTP_REFERER');
1076 $this->user_agent = (string)$request->get('HTTP_USER_AGENT');
1080 * Set result status code.
1082 * @param $status integer HTTP status code.
1084 function setStatus($status)
1086 $this->status = $status;
1090 * Set response size.
1092 * @param $size integer
1094 function setSize($size = 0)
1096 $this->size = (int)$size;
1099 function setDuration($seconds)
1101 // Pear DB does not correctly quote , in floats using ?. e.g. in european locales.
1103 $this->duration = strtr(sprintf("%f", $seconds), ",", ".");
1107 * Get time zone offset.
1109 * @param int $time Unix timestamp (defaults to current time).
1110 * @return string Zone offset, e.g. "-0800" for PST.
1112 static function _zone_offset($time = 0)
1116 $offset = date("Z", $time);
1122 $offhours = floor($offset / 3600);
1123 $offmins = $offset / 60 - $offhours * 60;
1124 return sprintf("%s%02d%02d", $negoffset, $offhours, $offmins);
1128 * Format time in NCSA format.
1130 * @param int $time Unix timestamp (defaults to current time).
1131 * @return string Formatted date & time.
1133 function _ncsa_time($time = 0)
1137 return date("d/M/Y:H:i:s", $time) .
1138 " " . $this->_zone_offset();
1143 if ($this->_accesslog->logfile) $this->write_file();
1144 if ($this->_accesslog->logtable) $this->write_sql();
1148 * Write entry to log file.
1150 function write_file()
1152 $entry = sprintf('%s %s %s [%s] "%s" %d %d "%s" "%s"',
1153 $this->host, $this->ident, $this->user,
1154 $this->_ncsa_time($this->time),
1155 $this->request, $this->status, $this->size,
1156 $this->referer, $this->user_agent);
1157 if (!empty($this->_accesslog->reader)) {
1158 fclose($this->_accesslog->reader);
1159 unset($this->_accesslog->reader);
1161 //Error log doesn't provide locking.
1162 //error_log("$entry\n", 3, $this->logfile);
1164 if (($fp = fopen($this->logfile, "a"))) {
1165 flock($fp, LOCK_EX);
1166 fputs($fp, "$entry\n");
1171 /* This is better been done by apache mod_log_sql */
1172 /* If ACCESS_LOG_SQL & 2 we do write it by our own */
1173 function write_sql()
1177 $dbh =& $request->_dbi;
1178 if ($dbh and $dbh->isOpen() and $this->_accesslog->logtable) {
1179 //$log_tbl =& $this->_accesslog->logtable;
1180 if ($request->get('REQUEST_METHOD') == "POST") {
1181 // strangely HTTP_POST_VARS doesn't contain all posted vars.
1182 $args = $_POST; // copy not ref. clone not needed on hashes
1184 if (!empty($args['auth']['passwd'])) $args['auth']['passwd'] = '<not displayed>';
1185 if (!empty($args['dbadmin']['passwd'])) $args['dbadmin']['passwd'] = '<not displayed>';
1186 if (!empty($args['pref']['passwd'])) $args['pref']['passwd'] = '<not displayed>';
1187 if (!empty($args['pref']['passwd2'])) $args['pref']['passwd2'] = '<not displayed>';
1188 $this->request_args = substr(serialize($args), 0, 254); // if VARCHAR(255) is used.
1190 $this->request_args = $request->get('QUERY_STRING');
1192 $this->request_method = $request->get('REQUEST_METHOD');
1193 $this->request_uri = $request->get('REQUEST_URI');
1194 // duration problem: sprintf "%f" might use comma e.g. "100,201" in european locales
1195 $dbh->_backend->write_accesslog($this);
1201 * Shutdown callback. Ensures that the file is written.
1204 * @see Request_AccessLogEntry
1206 function Request_AccessLogEntry_shutdown_function()
1210 if (isset($request->_accesslog->entries) and $request->_accesslog->logfile)
1211 foreach ($request->_accesslog->entries as $entry) {
1212 $entry->write_file();
1214 unset($request->_accesslog->entries);
1219 function __construct($val, $is_weak = false)
1221 $this->_val = wikihash($val);
1222 $this->_weak = $is_weak;
1227 * Strong comparison: If either (or both) tag is weak, they
1230 function equals($that, $strong_match = false)
1232 if ($this->_val != $that->_val)
1234 if ($strong_match and ($this->_weak or $that->_weak))
1241 $quoted = '"' . addslashes($this->_val) . '"';
1242 return $this->_weak ? "W/$quoted" : $quoted;
1245 /** Parse tag from header.
1248 static function parse($strval)
1250 if (!preg_match(':^(W/)?"(.+)"$:i', trim($strval), $m))
1251 return false; // parse failed
1252 list(, $weak, $str) = $m;
1253 return new HTTP_ETag(stripslashes($str), $weak);
1256 function matches($taglist, $strong_match = false)
1258 $taglist = trim($taglist);
1260 if ($taglist == '*') {
1262 return !$this->_weak;
1267 while (preg_match('@^(W/)?"((?:\\\\.|[^"])*)"\s*,?\s*@i',
1269 list($match, $weak, $str) = $m;
1270 $taglist = substr($taglist, strlen($match));
1271 $tag = new HTTP_ETag(stripslashes($str), $weak);
1272 if ($this->equals($tag, $strong_match)) {
1280 // Possible results from the HTTP_ValidatorSet::_check*() methods.
1281 // (Higher numerical values take precedence.)
1282 define ('_HTTP_VAL_PASS', 0); // Test is irrelevant
1283 define ('_HTTP_VAL_NOT_MODIFIED', 1); // Test passed, content not changed
1284 define ('_HTTP_VAL_MODIFIED', 2); // Test failed, content changed
1285 define ('_HTTP_VAL_FAILED', 3); // Precondition failed.
1287 class HTTP_ValidatorSet
1289 function __construct($validators)
1291 $this->_mtime = $this->_weak = false;
1292 $this->_tag = array();
1294 foreach ($validators as $key => $val) {
1295 if ($key == '%mtime') {
1296 $this->_mtime = $val;
1297 } elseif ($key == '%weak') {
1299 $this->_weak = true;
1301 $this->_tag[$key] = $val;
1306 function append($that)
1308 if (is_array($that))
1309 $that = new HTTP_ValidatorSet($that);
1311 // Pick the most recent mtime
1312 if (isset($that->_mtime))
1313 if (!isset($this->_mtime) || $that->_mtime > $this->_mtime)
1314 $this->_mtime = $that->_mtime;
1316 // If either is weak, we're weak
1317 if (!empty($that->_weak))
1318 $this->_weak = true;
1319 if (is_array($this->_tag))
1320 $this->_tag = array_merge($this->_tag, $that->_tag);
1322 $this->_tag = $that->_tag;
1329 return new HTTP_ETag($this->_tag, $this->_weak);
1332 function getModificationTime()
1334 return $this->_mtime;
1338 * @param Request $request
1341 function checkConditionalRequest(&$request)
1343 $result = max($this->_checkIfUnmodifiedSince($request),
1344 $this->_checkIfModifiedSince($request),
1345 $this->_checkIfMatch($request),
1346 $this->_checkIfNoneMatch($request));
1348 if ($result == _HTTP_VAL_PASS || $result == _HTTP_VAL_MODIFIED)
1349 return false; // "please proceed with normal processing"
1350 elseif ($result == _HTTP_VAL_FAILED)
1351 return 412; // "412 Precondition Failed"
1352 elseif ($result == _HTTP_VAL_NOT_MODIFIED)
1353 return 304; // "304 Not Modified"
1355 trigger_error("Ack, shouldn't get here", E_USER_ERROR);
1360 * @param Request $request
1363 function _checkIfUnmodifiedSince(&$request)
1365 if ($this->_mtime !== false) {
1366 $since = ParseRfc1123DateTime($request->get("HTTP_IF_UNMODIFIED_SINCE"));
1367 if ($since !== false && $this->_mtime > $since)
1368 return _HTTP_VAL_FAILED;
1370 return _HTTP_VAL_PASS;
1374 * @param Request $request
1377 function _checkIfModifiedSince(&$request)
1379 if ($this->_mtime !== false and $request->isGetOrHead()) {
1380 $since = ParseRfc1123DateTime($request->get("HTTP_IF_MODIFIED_SINCE"));
1381 if ($since !== false) {
1382 if ($this->_mtime <= $since)
1383 return _HTTP_VAL_NOT_MODIFIED;
1384 return _HTTP_VAL_MODIFIED;
1387 return _HTTP_VAL_PASS;
1391 * @param Request $request
1394 function _checkIfMatch(&$request)
1396 if ($this->_tag && ($taglist = $request->get("HTTP_IF_MATCH"))) {
1397 $tag = $this->getETag();
1398 if (!$tag->matches($taglist, 'strong'))
1399 return _HTTP_VAL_FAILED;
1401 return _HTTP_VAL_PASS;
1405 * @param Request $request
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