4 * Copyright 2005, 2007 Reini Urban
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.
24 * Read and write file and SQL accesslog. Write sequentially.
26 * Read from file per pagename: Hits
31 * Create NCSA "combined" log entry for current request.
32 * Also needed for advanced spam prevention.
33 * global object holding global state (sql or file, entries, to dump)
35 class Request_AccessLog
38 * @param string $logfile Log file name.
41 function Request_AccessLog($logfile, $do_sql = false)
43 //global $request; // request not yet initialized!
45 $this->logfile = $logfile;
46 if ($logfile and !is_writeable($logfile)) {
48 (sprintf(_("%s is not writable."), _("The PhpWiki access log file"))
50 . sprintf(_("Please ensure that %s is writable, or redefine %s in config/config.ini."),
51 sprintf(_("the file ā%sā"), ACCESS_LOG),
55 //$request->_accesslog =& $this;
56 //if (empty($request->_accesslog->entries))
57 register_shutdown_function("Request_AccessLogEntry_shutdown_function");
60 if (!$request->_dbi->isSQL()) {
61 trigger_error("Unsupported database backend for ACCESS_LOG_SQL. Need DATABASE_TYPE=SQL or ADODB or PDO.");
64 //$this->_dbi =& $request->_dbi;
65 $this->logtable = (!empty($DBParams['prefix']) ? $DBParams['prefix'] : '') . "accesslog";
68 $this->entries = array();
69 $this->entries[] = new Request_AccessLogEntry($this);
72 function _do($cmd, &$arg)
75 for ($i = 0; $i < count($this->entries); $i++)
76 $this->entries[$i]->$cmd($arg);
79 function push(&$request)
81 $this->_do('push', $request);
84 function setSize($arg)
86 $this->_do('setSize', $arg);
89 function setStatus($arg)
91 $this->_do('setStatus', $arg);
94 function setDuration($arg)
96 $this->_do('setDuration', $arg);
100 * Read sequentially all previous entries from the beginning.
101 * while ($logentry = Request_AccessLogEntry::read()) ;
102 * For internal log analyzers: RecentReferrers, WikiAccessRestrictions
106 return $this->logtable ? $this->read_sql() : $this->read_file();
110 * Return iterator of referer items reverse sorted (latest first).
112 function get_referer($limit = 15, $external_only = false)
114 if ($external_only) { // see stdlin.php:isExternalReferrer()
116 $blen = strlen($base);
118 if (!empty($this->_dbi)) {
119 // check same hosts in referer and request and remove them
120 $ext_where = " AND LEFT(referer,$blen) <> " . $this->_dbi->quote($base)
121 . " AND LEFT(referer,$blen) <> LEFT(CONCAT(" . $this->_dbi->quote(SERVER_URL) . ",request_uri),$blen)";
122 return $this->_read_sql_query("(referer <>'' AND NOT(ISNULL(referer)))"
123 . ($external_only ? $ext_where : '')
124 . " ORDER BY time_stamp DESC"
125 . ($limit ? " LIMIT $limit" : ""));
127 $iter = new WikiDB_Array_generic_iter(0);
128 $logs =& $iter->_array;
129 while ($logentry = $this->read_file()) {
130 if (!empty($logentry->referer)
131 and (!$external_only or (substr($logentry->referer, 0, $blen) != $base))
133 $iter->_array[] = $logentry;
134 if ($limit and count($logs) > $limit)
138 $logs = array_reverse($logs);
139 $logs = array_slice($logs, 0, min($limit, count($logs)));
145 * Read sequentially backwards all previous entries from log file.
151 if ($this->logfile) $this->logfile = ACCESS_LOG; // support Request_AccessLog::read
153 if (empty($this->reader)) // start at the beginning
154 $this->reader = fopen($this->logfile, "r");
155 if ($s = fgets($this->reader)) {
156 $entry = new Request_AccessLogEntry($this);
157 $re = '/^(\S+)\s(\S+)\s(\S+)\s\[(.+?)\] "([^"]+)" (\d+) (\d+) "([^"]*)" "([^"]*)"$/';
158 if (preg_match($re, $s, $m)) {
159 list(, $entry->host, $entry->ident, $entry->user, $entry->time,
160 $entry->request, $entry->status, $entry->size,
161 $entry->referer, $entry->user_agent) = $m;
164 } else { // until the end
165 fclose($this->reader);
170 function read_sql($where = '')
172 if (empty($this->sqliter))
173 $this->sqliter = $this->_read_sql_query($where);
174 return $this->sqliter->next();
177 function _read_sql_query($where = '')
180 $dbh =& $request->_dbi;
181 $log_tbl =& $this->logtable;
182 return $dbh->genericSqlIter("SELECT *,request_uri as request,request_time as time,remote_user as user,"
183 . "remote_host as host,agent as user_agent"
185 . ($where ? " WHERE $where" : ""));
188 /* done in request->finish() before the db is closed */
192 $dbh =& $request->_dbi;
193 if (isset($this->entries) and $dbh and $dbh->isOpen())
194 foreach ($this->entries as $entry) {
199 /* done in the shutdown callback */
200 function write_file()
202 if (isset($this->entries) and $this->logfile)
203 foreach ($this->entries as $entry) {
204 $entry->write_file();
206 unset($this->entries);
209 /* in an ideal world... */
212 if ($this->logfile) $this->write_file();
213 if ($this->logtable) $this->write_sql();
214 unset($this->entries);
218 class Request_AccessLogEntry
221 * The log entry will be automatically appended to the log file or
222 * SQL table when the current request terminates.
224 * If you want to modify a Request_AccessLogEntry before it gets
225 * written (e.g. via the setStatus and setSize methods) you should
226 * use an '&' on the constructor, so that you're working with the
227 * original (rather than a copy) object.
230 * $log_entry = & new Request_AccessLogEntry("/tmp/wiki_access_log");
231 * $log_entry->setStatus(401);
232 * $log_entry->push($request);
236 function __construct(&$accesslog)
238 $this->_accesslog = $accesslog;
239 $this->logfile = $accesslog->logfile;
240 $this->time = time();
241 $this->status = 200; // see setStatus()
242 $this->size = 0; // see setSize()
246 * @param $request object Request object for current request.
248 function push(&$request)
250 $this->host = $request->get('REMOTE_HOST');
251 $this->ident = $request->get('REMOTE_IDENT');
254 $user = $request->getUser();
255 if ($user->isAuthenticated())
256 $this->user = $user->UserName();
259 $this->request = join(' ', array($request->get('REQUEST_METHOD'),
260 $request->get('REQUEST_URI'),
261 $request->get('SERVER_PROTOCOL')));
262 $this->referer = (string)$request->get('HTTP_REFERER');
263 $this->user_agent = (string)$request->get('HTTP_USER_AGENT');
267 * Set result status code.
269 * @param $status integer HTTP status code.
271 function setStatus($status)
273 $this->status = $status;
279 * @param $size integer
281 function setSize($size = 0)
283 $this->size = (int)$size;
286 function setDuration($seconds)
288 // Pear DB does not correctly quote , in floats using ?. e.g. in european locales.
290 $this->duration = str_replace(",", ".", sprintf("%f", $seconds));
294 * Get time zone offset.
296 * This is a static member function.
298 * @param int|bool $time Unix timestamp (defaults to current time).
299 * @return string Zone offset, e.g. "-0800" for PST.
301 function _zone_offset($time = false)
305 $offset = date("Z", $time);
311 $offhours = floor($offset / 3600);
312 $offmins = $offset / 60 - $offhours * 60;
313 return sprintf("%s%02d%02d", $negoffset, $offhours, $offmins);
317 * Format time in NCSA format.
319 * This is a static member function.
321 * @param int|bool $time Unix timestamp (defaults to current time).
322 * @return string Formatted date & time.
324 function _ncsa_time($time = false)
328 return date("d/M/Y:H:i:s", $time) .
329 " " . $this->_zone_offset();
334 if ($this->_accesslog->logfile) $this->write_file();
335 if ($this->_accesslog->logtable) $this->write_sql();
339 * Write entry to log file.
341 function write_file()
343 $entry = sprintf('%s %s %s [%s] "%s" %d %d "%s" "%s"',
344 $this->host, $this->ident, $this->user,
345 $this->_ncsa_time($this->time),
346 $this->request, $this->status, $this->size,
347 $this->referer, $this->user_agent);
348 if (!empty($this->_accesslog->reader)) {
349 fclose($this->_accesslog->reader);
350 unset($this->_accesslog->reader);
352 //Error log doesn't provide locking.
353 //error_log("$entry\n", 3, $this->logfile);
355 if (($fp = fopen($this->logfile, "a"))) {
357 fputs($fp, "$entry\n");
362 /* This is better been done by apache mod_log_sql */
363 /* If ACCESS_LOG_SQL & 2 we do write it by our own */
368 $dbh =& $request->_dbi;
369 if ($dbh and $dbh->isOpen() and $this->_accesslog->logtable) {
370 //$log_tbl =& $this->_accesslog->logtable;
371 if ($request->get('REQUEST_METHOD') == "POST") {
372 // strangely HTTP_POST_VARS doesn't contain all posted vars.
373 $args = $_POST; // copy not ref. clone not needed on hashes
375 if (!empty($args['auth']['passwd'])) $args['auth']['passwd'] = '<not displayed>';
376 if (!empty($args['dbadmin']['passwd'])) $args['dbadmin']['passwd'] = '<not displayed>';
377 if (!empty($args['pref']['passwd'])) $args['pref']['passwd'] = '<not displayed>';
378 if (!empty($args['pref']['passwd2'])) $args['pref']['passwd2'] = '<not displayed>';
379 $this->request_args = substr(serialize($args), 0, 254); // if VARCHAR(255) is used.
381 $this->request_args = $request->get('QUERY_STRING');
383 $this->request_method = $request->get('REQUEST_METHOD');
384 $this->request_uri = $request->get('REQUEST_URI');
385 // duration problem: sprintf "%f" might use comma e.g. "100,201" in european locales
386 $dbh->_backend->write_accesslog($this);
392 * Shutdown callback. Ensures that the file is written.
395 * @see Request_AccessLogEntry
397 function Request_AccessLogEntry_shutdown_function()
401 if (isset($request->_accesslog->entries) and $request->_accesslog->logfile)
402 foreach ($request->_accesslog->entries as $entry) {
403 $entry->write_file();
405 unset($request->_accesslog->entries);
408 // TODO: SQL access methods....
409 // (c) 2005 Charles Corrigan (the mysql parts)
410 // (c) 2006 Rein Urban (the postgresql parts)
411 // from AnalyseAccessLogSql.php
412 class Request_AccessLog_SQL
416 * Build the query string
418 * FIXME: some or all of these queries may be MySQL specific / non-portable
419 * FIXME: properly quote the string args
421 * The column names displayed are generated from the actual query column
422 * names, so make sure that each column in the query is given a user
423 * friendly name. Note that the column names are passed to _() and so may be
426 * If there are query specific where conditions, then the construction
427 * " if ($where_conditions<>'')
428 * $where_conditions = 'WHERE '.$where_conditions.' ';"
429 * should be changed to
430 * " if ($where_conditions<>'')
431 * $where_conditions = 'AND '.$where_conditions.' ';"
432 * and in the assignment to query have something like
433 * " $query= "SELECT "
435 * ."FROM $accesslog "
436 * ."WHERE referer IS NOT NULL "
439 function _getQueryString(&$args)
441 // extract any parametrised conditions from the arguments,
442 // in particular, how much history to select
443 $where_conditions = $this->_getWhereConditions($args);
445 // get the correct name for the table
446 //FIXME is there a more correct way to do this?
447 global $DBParams, $request;
448 $accesslog = (!empty($DBParams['prefix']) ? $DBParams['prefix'] : '') . "accesslog";
451 $backend_type = $request->_dbi->_backend->backendType();
452 switch ($backend_type) {
454 $Referring_URL = "left(referer,length(referer)-instr(reverse(referer),'?'))";
458 $Referring_URL = "substr(referer,0,position('?' in referer))";
461 $Referring_URL = "referer";
463 switch ($args['mode']) {
464 case 'referring_urls':
465 if ($where_conditions <> '')
466 $where_conditions = 'WHERE ' . $where_conditions . ' ';
468 . "$Referring_URL AS Referring_URL, "
469 . "count(*) AS Referral_Count "
472 . "GROUP BY Referring_URL";
474 case 'external_referers':
475 $args['local_referrers'] = 'false';
476 $where_conditions = $this->_getWhereConditions($args);
477 if ($where_conditions <> '')
478 $where_conditions = 'WHERE ' . $where_conditions . ' ';
480 . "$Referring_URL AS Referring_URL, "
481 . "count(*) AS Referral_Count "
484 . "GROUP BY Referring_URL";
486 case 'referring_domains':
487 if ($where_conditions <> '')
488 $where_conditions = 'WHERE ' . $where_conditions . ' ';
489 switch ($backend_type) {
491 $Referring_Domain = "left(referer, if(locate('/', referer, 8) > 0,locate('/', referer, 8) -1, length(referer)))";
495 $Referring_Domain = "substr(referer,0,8) || regexp_replace(substr(referer,8), '/.*', '')";
498 $Referring_Domain = "referer";
502 . "$Referring_Domain AS Referring_Domain, "
503 . "count(*) AS Referral_Count "
506 . "GROUP BY Referring_Domain";
509 if ($where_conditions <> '')
510 $where_conditions = 'WHERE ' . $where_conditions . ' ';
512 . "remote_host AS Remote_Host, "
513 . "count(*) AS Access_Count "
516 . "GROUP BY Remote_Host";
519 if ($where_conditions <> '')
520 $where_conditions = 'WHERE ' . $where_conditions . ' ';
522 . "remote_user AS User, "
523 . "count(*) AS Access_Count "
526 . "GROUP BY remote_user";
529 if ($where_conditions <> '')
530 $where_conditions = 'WHERE ' . $where_conditions . ' ';
532 . "remote_host AS Remote_Host, "
533 . "remote_user AS User, "
534 . "count(*) AS Access_Count "
537 . "GROUP BY remote_host, remote_user";
540 // This queries for all entries in the SQL access log table that
541 // have a dns name that I know to be a web search engine crawler and
542 // categorises the results into time buckets as per the list below
544 // 1 - 1 hour - 3600 = 60 * 60
545 // 2 - 1 day - 86400 = 60 * 60 * 24
546 // 3 - 1 week - 604800 = 60 * 60 * 24 * 7
547 // 4 - 1 month - 2629800 = 60 * 60 * 24 * 365.25 / 12
548 // 5 - 1 year - 31557600 = 60 * 60 * 24 * 365.25
551 . "CASE WHEN $now-time_stamp<60 THEN '" . _("0 - last minute") . "' ELSE "
552 . "CASE WHEN $now-time_stamp<3600 THEN '" . _("1 - 1 minute to 1 hour") . "' ELSE "
553 . "CASE WHEN $now-time_stamp<86400 THEN '" . _("2 - 1 hour to 1 day") . "' ELSE "
554 . "CASE WHEN $now-time_stamp<604800 THEN '" . _("3 - 1 day to 1 week") . "' ELSE "
555 . "CASE WHEN $now-time_stamp<2629800 THEN '" . _("4 - 1 week to 1 month") . "' ELSE "
556 . "CASE WHEN $now-time_stamp<31557600 THEN '" . _("5 - 1 month to 1 year") . "' ELSE "
557 . "'" . _("6 - more than 1 year") . "' END END END END END END AS Time_Scale, "
558 . "remote_host AS Remote_Host, "
559 . "count(*) AS Access_Count "
561 . "WHERE (remote_host LIKE '%googlebot.com' "
562 . "OR remote_host LIKE '%alexa.com' "
563 . "OR remote_host LIKE '%inktomisearch.com' "
564 . "OR remote_host LIKE '%msnbot.msn.com') "
565 . ($where_conditions ? 'AND ' . $where_conditions : '')
566 . "GROUP BY Time_Scale, remote_host";
568 case "search_bots_hits":
569 // This queries for all entries in the SQL access log table that
570 // have a dns name that I know to be a web search engine crawler and
571 // displays the URI that was hit.
572 // If PHPSESSID appears in the URI, just display the URI to the left of this
573 $sessname = session_name();
574 switch ($backend_type) {
576 $Request_URI = "IF(instr(request_uri, '$sessname')=0, request_uri,left(request_uri, instr(request_uri, '$sessname')-2))";
580 $Request_URI = "regexp_replace(request_uri, '$sessname.*', '')";
583 $Request_URI = 'request_uri';
588 . "CASE WHEN $now-time_stamp<60 THEN '" . _("0 - last minute") . "' ELSE "
589 . "CASE WHEN $now-time_stamp<3600 THEN '" . _("1 - 1 minute to 1 hour") . "' ELSE "
590 . "CASE WHEN $now-time_stamp<86400 THEN '" . _("2 - 1 hour to 1 day") . "' ELSE "
591 . "CASE WHEN $now-time_stamp<604800 THEN '" . _("3 - 1 day to 1 week") . "' ELSE "
592 . "CASE WHEN $now-time_stamp<2629800 THEN '" . _("4 - 1 week to 1 month") . "' ELSE "
593 . "CASE WHEN $now-time_stamp<31557600 THEN '" . _("5 - 1 month to 1 year") . "' ELSE "
594 . "'" . _("6 - more than 1 year") . "' END END END END END END AS Time_Scale, "
595 . "remote_host AS Remote_Host, "
596 . "$Request_URI AS Request_URI "
598 . "WHERE (remote_host LIKE '%googlebot.com' "
599 . "OR remote_host LIKE '%alexa.com' "
600 . "OR remote_host LIKE '%inktomisearch.com' "
601 . "OR remote_host LIKE '%msnbot.msn.com') "
602 . ($where_conditions ? 'AND ' . $where_conditions : '')
603 . "ORDER BY time_stamp";
608 /** Honeypot for xgettext. Those strings are translated dynamically.
610 function _locale_dummy()
615 _("external_referers"),
616 _("referring_domains"),
621 _("search_bots_hits"),
630 function getDefaultArguments()
633 'mode' => 'referring_domains',
634 // referring_domains, referring_urls, remote_hosts, users, host_users, search_bots, search_bots_hits
636 // blank means use the mode as the caption/title for the output
637 'local_referrers' => 'true', // only show external referring sites
638 'period' => '', // the type of period to report:
639 // may be weeks, days, hours, minutes, or blank for all
640 'count' => '0' // the number of periods to report
644 function table_output()
646 $query = $this->_getQueryString($args);
649 return HTML::p(sprintf(_("Unrecognised parameter 'mode=%s'"),
652 // get the data back.
653 // Note that this must be done before the final generation ofthe table,
654 // otherwise the headers will not be ready
655 $tbody = $this->_getQueryResults($query, $dbi);
657 return HTML::table(array('border' => 1),
658 HTML::caption($this->_getCaption($args)),
659 HTML::thead($this->_theadrow),
663 function _getQueryResults($query, &$dbi)
665 $queryResult = $dbi->genericSqlIter($query);
667 $tbody = HTML::tbody(HTML::tr(HTML::td(_("<empty>"))));
669 $tbody = HTML::tbody();
670 while ($row = $queryResult->next()) {
671 $this->_setHeaders($row);
673 foreach ($row as $value) {
674 // output a '-' for empty values, otherwise the table looks strange
675 $tr->pushContent(HTML::td(empty($value) ? '-' : $value));
677 $tbody->pushContent($tr);
680 $queryResult->free();
684 function _setHeaders($row)
686 if (!$this->_headerSet) {
687 foreach ($row as $key => $value) {
688 $this->_theadrow->pushContent(HTML::th(_($key)));
690 $this->_headerSet = true;
694 function _getWhereConditions(&$args)
696 $where_conditions = '';
698 if ($args['period'] <> '') {
700 if ($args['period'] == 'minutes') {
702 } elseif ($args['period'] == 'hours') {
704 } elseif ($args['period'] == 'days') {
705 $since = 60 * 60 * 24;
706 } elseif ($args['period'] == 'weeks') {
707 $since = 60 * 60 * 24 * 7;
709 $since = $since * $args['count'];
711 if ($where_conditions <> '')
712 $where_conditions = $where_conditions . ' AND ';
713 $since = time() - $since;
714 $where_conditions = $where_conditions . "time_stamp > $since";
718 if ($args['local_referrers'] <> 'true') {
720 if ($where_conditions <> '')
721 $where_conditions = $where_conditions . ' AND ';
722 $localhost = SERVER_URL;
723 $len = strlen($localhost);
724 $backend_type = $request->_dbi->_backend->backendType();
725 switch ($backend_type) {
727 $ref_localhost = "left(referer,$len)<>'$localhost'";
731 $ref_localhost = "substr(referer,0,$len)<>'$localhost'";
736 $where_conditions = $where_conditions . $ref_localhost;
739 // The assumed contract is that there is a space at the end of the
740 // conditions string, so that following SQL clauses (such as GROUP BY)
741 // will not cause a syntax error
742 if ($where_conditions <> '')
743 $where_conditions = $where_conditions . ' ';
745 return $where_conditions;
748 function _getCaption(&$args)
750 $caption = $args['caption'];
752 $caption = gettext($args['mode']);
753 if ($args['period'] <> '' && $args['count'])
754 $caption = $caption . " - " . $args['count'] . " " . gettext($args['period']);
764 // c-hanging-comment-ender-p: nil
765 // indent-tabs-mode: nil