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 $logfile string Log file name.
40 function Request_AccessLog($logfile, $do_sql = false)
42 //global $request; // request not yet initialized!
44 $this->logfile = $logfile;
45 if ($logfile and !is_writeable($logfile)) {
47 (sprintf(_("%s is not writable."), _("The PhpWiki access log file"))
49 . sprintf(_("Please ensure that %s is writable, or redefine %s in config/config.ini."),
50 sprintf(_("the file ā%sā"), ACCESS_LOG),
54 //$request->_accesslog =& $this;
55 //if (empty($request->_accesslog->entries))
56 register_shutdown_function("Request_AccessLogEntry_shutdown_function");
59 if (!$request->_dbi->isSQL()) {
60 trigger_error("Unsupported database backend for ACCESS_LOG_SQL.\nNeed DATABASE_TYPE=SQL or ADODB or PDO");
63 //$this->_dbi =& $request->_dbi;
64 $this->logtable = (!empty($DBParams['prefix']) ? $DBParams['prefix'] : '') . "accesslog";
67 $this->entries = array();
68 $this->entries[] = new Request_AccessLogEntry($this);
71 function _do($cmd, &$arg)
74 for ($i = 0; $i < count($this->entries); $i++)
75 $this->entries[$i]->$cmd($arg);
78 function push(&$request)
80 $this->_do('push', $request);
83 function setSize($arg)
85 $this->_do('setSize', $arg);
88 function setStatus($arg)
90 $this->_do('setStatus', $arg);
93 function setDuration($arg)
95 $this->_do('setDuration', $arg);
99 * Read sequentially all previous entries from the beginning.
100 * while ($logentry = Request_AccessLogEntry::read()) ;
101 * For internal log analyzers: RecentReferrers, WikiAccessRestrictions
105 return $this->logtable ? $this->read_sql() : $this->read_file();
109 * Return iterator of referer items reverse sorted (latest first).
111 function get_referer($limit = 15, $external_only = false)
113 if ($external_only) { // see stdlin.php:isExternalReferrer()
115 $blen = strlen($base);
117 if (!empty($this->_dbi)) {
118 // check same hosts in referer and request and remove them
119 $ext_where = " AND LEFT(referer,$blen) <> " . $this->_dbi->quote($base)
120 . " AND LEFT(referer,$blen) <> LEFT(CONCAT(" . $this->_dbi->quote(SERVER_URL) . ",request_uri),$blen)";
121 return $this->_read_sql_query("(referer <>'' AND NOT(ISNULL(referer)))"
122 . ($external_only ? $ext_where : '')
123 . " ORDER BY time_stamp DESC"
124 . ($limit ? " LIMIT $limit" : ""));
126 $iter = new WikiDB_Array_generic_iter(0);
127 $logs =& $iter->_array;
128 while ($logentry = $this->read_file()) {
129 if (!empty($logentry->referer)
130 and (!$external_only or (substr($logentry->referer, 0, $blen) != $base))
132 $iter->_array[] = $logentry;
133 if ($limit and count($logs) > $limit)
137 $logs = array_reverse($logs);
138 $logs = array_slice($logs, 0, min($limit, count($logs)));
144 * Read sequentially backwards all previous entries from log file.
150 if ($this->logfile) $this->logfile = ACCESS_LOG; // support Request_AccessLog::read
152 if (empty($this->reader)) // start at the beginning
153 $this->reader = fopen($this->logfile, "r");
154 if ($s = fgets($this->reader)) {
155 $entry = new Request_AccessLogEntry($this);
156 $re = '/^(\S+)\s(\S+)\s(\S+)\s\[(.+?)\] "([^"]+)" (\d+) (\d+) "([^"]*)" "([^"]*)"$/';
157 if (preg_match($re, $s, $m)) {
158 list(, $entry->host, $entry->ident, $entry->user, $entry->time,
159 $entry->request, $entry->status, $entry->size,
160 $entry->referer, $entry->user_agent) = $m;
163 } else { // until the end
164 fclose($this->reader);
169 function read_sql($where = '')
171 if (empty($this->sqliter))
172 $this->sqliter = $this->_read_sql_query($where);
173 return $this->sqliter->next();
176 function _read_sql_query($where = '')
179 $dbh =& $request->_dbi;
180 $log_tbl =& $this->logtable;
181 return $dbh->genericSqlIter("SELECT *,request_uri as request,request_time as time,remote_user as user,"
182 . "remote_host as host,agent as user_agent"
184 . ($where ? " WHERE $where" : ""));
187 /* done in request->finish() before the db is closed */
191 $dbh =& $request->_dbi;
192 if (isset($this->entries) and $dbh and $dbh->isOpen())
193 foreach ($this->entries as $entry) {
198 /* done in the shutdown callback */
199 function write_file()
201 if (isset($this->entries) and $this->logfile)
202 foreach ($this->entries as $entry) {
203 $entry->write_file();
205 unset($this->entries);
208 /* in an ideal world... */
211 if ($this->logfile) $this->write_file();
212 if ($this->logtable) $this->write_sql();
213 unset($this->entries);
217 class Request_AccessLogEntry
222 * The log entry will be automatically appended to the log file or
223 * SQL table when the current request terminates.
225 * If you want to modify a Request_AccessLogEntry before it gets
226 * written (e.g. via the setStatus and setSize methods) you should
227 * use an '&' on the constructor, so that you're working with the
228 * original (rather than a copy) object.
231 * $log_entry = & new Request_AccessLogEntry("/tmp/wiki_access_log");
232 * $log_entry->setStatus(401);
233 * $log_entry->push($request);
238 function Request_AccessLogEntry(&$accesslog)
240 $this->_accesslog = $accesslog;
241 $this->logfile = $accesslog->logfile;
242 $this->time = time();
243 $this->status = 200; // see setStatus()
244 $this->size = 0; // see setSize()
248 * @param $request object Request object for current request.
250 function push(&$request)
252 $this->host = $request->get('REMOTE_HOST');
253 $this->ident = $request->get('REMOTE_IDENT');
256 $user = $request->getUser();
257 if ($user->isAuthenticated())
258 $this->user = $user->UserName();
261 $this->request = join(' ', array($request->get('REQUEST_METHOD'),
262 $request->get('REQUEST_URI'),
263 $request->get('SERVER_PROTOCOL')));
264 $this->referer = (string)$request->get('HTTP_REFERER');
265 $this->user_agent = (string)$request->get('HTTP_USER_AGENT');
269 * Set result status code.
271 * @param $status integer HTTP status code.
273 function setStatus($status)
275 $this->status = $status;
281 * @param $size integer
283 function setSize($size = 0)
285 $this->size = (int)$size;
288 function setDuration($seconds)
290 // Pear DB does not correctly quote , in floats using ?. e.g. in european locales.
292 $this->duration = str_replace(",", ".", sprintf("%f", $seconds));
296 * Get time zone offset.
298 * This is a static member function.
300 * @param $time integer Unix timestamp (defaults to current time).
301 * @return string Zone offset, e.g. "-0800" for PST.
303 function _zone_offset($time = false)
307 $offset = date("Z", $time);
313 $offhours = floor($offset / 3600);
314 $offmins = $offset / 60 - $offhours * 60;
315 return sprintf("%s%02d%02d", $negoffset, $offhours, $offmins);
319 * Format time in NCSA format.
321 * This is a static member function.
323 * @param $time integer Unix timestamp (defaults to current time).
324 * @return string Formatted date & time.
326 function _ncsa_time($time = false)
330 return date("d/M/Y:H:i:s", $time) .
331 " " . $this->_zone_offset();
336 if ($this->_accesslog->logfile) $this->write_file();
337 if ($this->_accesslog->logtable) $this->write_sql();
341 * Write entry to log file.
343 function write_file()
345 $entry = sprintf('%s %s %s [%s] "%s" %d %d "%s" "%s"',
346 $this->host, $this->ident, $this->user,
347 $this->_ncsa_time($this->time),
348 $this->request, $this->status, $this->size,
349 $this->referer, $this->user_agent);
350 if (!empty($this->_accesslog->reader)) {
351 fclose($this->_accesslog->reader);
352 unset($this->_accesslog->reader);
354 //Error log doesn't provide locking.
355 //error_log("$entry\n", 3, $this->logfile);
357 if (($fp = fopen($this->logfile, "a"))) {
359 fputs($fp, "$entry\n");
364 /* This is better been done by apache mod_log_sql */
365 /* If ACCESS_LOG_SQL & 2 we do write it by our own */
370 $dbh =& $request->_dbi;
371 if ($dbh and $dbh->isOpen() and $this->_accesslog->logtable) {
372 //$log_tbl =& $this->_accesslog->logtable;
373 if ($request->get('REQUEST_METHOD') == "POST") {
374 // strangely HTTP_POST_VARS doesn't contain all posted vars.
375 $args = $_POST; // copy not ref. clone not needed on hashes
377 if (!empty($args['auth']['passwd'])) $args['auth']['passwd'] = '<not displayed>';
378 if (!empty($args['dbadmin']['passwd'])) $args['dbadmin']['passwd'] = '<not displayed>';
379 if (!empty($args['pref']['passwd'])) $args['pref']['passwd'] = '<not displayed>';
380 if (!empty($args['pref']['passwd2'])) $args['pref']['passwd2'] = '<not displayed>';
381 $this->request_args = substr(serialize($args), 0, 254); // if VARCHAR(255) is used.
383 $this->request_args = $request->get('QUERY_STRING');
385 $this->request_method = $request->get('REQUEST_METHOD');
386 $this->request_uri = $request->get('REQUEST_URI');
387 // duration problem: sprintf "%f" might use comma e.g. "100,201" in european locales
388 $dbh->_backend->write_accesslog($this);
394 * Shutdown callback. Ensures that the file is written.
397 * @see Request_AccessLogEntry
399 function Request_AccessLogEntry_shutdown_function()
403 if (isset($request->_accesslog->entries) and $request->_accesslog->logfile)
404 foreach ($request->_accesslog->entries as $entry) {
405 $entry->write_file();
407 unset($request->_accesslog->entries);
410 // TODO: SQL access methods....
411 // (c) 2005 Charles Corrigan (the mysql parts)
412 // (c) 2006 Rein Urban (the postgresql parts)
413 // from AnalyseAccessLogSql.php
414 class Request_AccessLog_SQL
418 * Build the query string
420 * FIXME: some or all of these queries may be MySQL specific / non-portable
421 * FIXME: properly quote the string args
423 * The column names displayed are generated from the actual query column
424 * names, so make sure that each column in the query is given a user
425 * friendly name. Note that the column names are passed to _() and so may be
428 * If there are query specific where conditions, then the construction
429 * " if ($where_conditions<>'')
430 * $where_conditions = 'WHERE '.$where_conditions.' ';"
431 * should be changed to
432 * " if ($where_conditions<>'')
433 * $where_conditions = 'AND '.$where_conditions.' ';"
434 * and in the assignment to query have something like
435 * " $query= "SELECT "
437 * ."FROM $accesslog "
438 * ."WHERE referer IS NOT NULL "
441 function _getQueryString(&$args)
443 // extract any parametrised conditions from the arguments,
444 // in particular, how much history to select
445 $where_conditions = $this->_getWhereConditions($args);
447 // get the correct name for the table
448 //FIXME is there a more correct way to do this?
449 global $DBParams, $request;
450 $accesslog = (!empty($DBParams['prefix']) ? $DBParams['prefix'] : '') . "accesslog";
453 $backend_type = $request->_dbi->_backend->backendType();
454 switch ($backend_type) {
456 $Referring_URL = "left(referer,length(referer)-instr(reverse(referer),'?'))";
460 $Referring_URL = "substr(referer,0,position('?' in referer))";
463 $Referring_URL = "referer";
465 switch ($args['mode']) {
466 case 'referring_urls':
467 if ($where_conditions <> '')
468 $where_conditions = 'WHERE ' . $where_conditions . ' ';
470 . "$Referring_URL AS Referring_URL, "
471 . "count(*) AS Referral_Count "
474 . "GROUP BY Referring_URL";
476 case 'external_referers':
477 $args['local_referrers'] = 'false';
478 $where_conditions = $this->_getWhereConditions($args);
479 if ($where_conditions <> '')
480 $where_conditions = 'WHERE ' . $where_conditions . ' ';
482 . "$Referring_URL AS Referring_URL, "
483 . "count(*) AS Referral_Count "
486 . "GROUP BY Referring_URL";
488 case 'referring_domains':
489 if ($where_conditions <> '')
490 $where_conditions = 'WHERE ' . $where_conditions . ' ';
491 switch ($backend_type) {
493 $Referring_Domain = "left(referer, if(locate('/', referer, 8) > 0,locate('/', referer, 8) -1, length(referer)))";
497 $Referring_Domain = "substr(referer,0,8) || regexp_replace(substr(referer,8), '/.*', '')";
500 $Referring_Domain = "referer";
504 . "$Referring_Domain AS Referring_Domain, "
505 . "count(*) AS Referral_Count "
508 . "GROUP BY Referring_Domain";
511 if ($where_conditions <> '')
512 $where_conditions = 'WHERE ' . $where_conditions . ' ';
514 . "remote_host AS Remote_Host, "
515 . "count(*) AS Access_Count "
518 . "GROUP BY Remote_Host";
521 if ($where_conditions <> '')
522 $where_conditions = 'WHERE ' . $where_conditions . ' ';
524 . "remote_user AS User, "
525 . "count(*) AS Access_Count "
528 . "GROUP BY remote_user";
531 if ($where_conditions <> '')
532 $where_conditions = 'WHERE ' . $where_conditions . ' ';
534 . "remote_host AS Remote_Host, "
535 . "remote_user AS User, "
536 . "count(*) AS Access_Count "
539 . "GROUP BY remote_host, remote_user";
542 // This queries for all entries in the SQL access log table that
543 // have a dns name that I know to be a web search engine crawler and
544 // categorises the results into time buckets as per the list below
546 // 1 - 1 hour - 3600 = 60 * 60
547 // 2 - 1 day - 86400 = 60 * 60 * 24
548 // 3 - 1 week - 604800 = 60 * 60 * 24 * 7
549 // 4 - 1 month - 2629800 = 60 * 60 * 24 * 365.25 / 12
550 // 5 - 1 year - 31557600 = 60 * 60 * 24 * 365.25
553 . "CASE WHEN $now-time_stamp<60 THEN '" . _("0 - last minute") . "' ELSE "
554 . "CASE WHEN $now-time_stamp<3600 THEN '" . _("1 - 1 minute to 1 hour") . "' ELSE "
555 . "CASE WHEN $now-time_stamp<86400 THEN '" . _("2 - 1 hour to 1 day") . "' ELSE "
556 . "CASE WHEN $now-time_stamp<604800 THEN '" . _("3 - 1 day to 1 week") . "' ELSE "
557 . "CASE WHEN $now-time_stamp<2629800 THEN '" . _("4 - 1 week to 1 month") . "' ELSE "
558 . "CASE WHEN $now-time_stamp<31557600 THEN '" . _("5 - 1 month to 1 year") . "' ELSE "
559 . "'" . _("6 - more than 1 year") . "' END END END END END END AS Time_Scale, "
560 . "remote_host AS Remote_Host, "
561 . "count(*) AS Access_Count "
563 . "WHERE (remote_host LIKE '%googlebot.com' "
564 . "OR remote_host LIKE '%alexa.com' "
565 . "OR remote_host LIKE '%inktomisearch.com' "
566 . "OR remote_host LIKE '%msnbot.msn.com') "
567 . ($where_conditions ? 'AND ' . $where_conditions : '')
568 . "GROUP BY Time_Scale, remote_host";
570 case "search_bots_hits":
571 // This queries for all entries in the SQL access log table that
572 // have a dns name that I know to be a web search engine crawler and
573 // displays the URI that was hit.
574 // If PHPSESSID appears in the URI, just display the URI to the left of this
575 $sessname = session_name();
576 switch ($backend_type) {
578 $Request_URI = "IF(instr(request_uri, '$sessname')=0, request_uri,left(request_uri, instr(request_uri, '$sessname')-2))";
582 $Request_URI = "regexp_replace(request_uri, '$sessname.*', '')";
585 $Request_URI = 'request_uri';
590 . "CASE WHEN $now-time_stamp<60 THEN '" . _("0 - last minute") . "' ELSE "
591 . "CASE WHEN $now-time_stamp<3600 THEN '" . _("1 - 1 minute to 1 hour") . "' ELSE "
592 . "CASE WHEN $now-time_stamp<86400 THEN '" . _("2 - 1 hour to 1 day") . "' ELSE "
593 . "CASE WHEN $now-time_stamp<604800 THEN '" . _("3 - 1 day to 1 week") . "' ELSE "
594 . "CASE WHEN $now-time_stamp<2629800 THEN '" . _("4 - 1 week to 1 month") . "' ELSE "
595 . "CASE WHEN $now-time_stamp<31557600 THEN '" . _("5 - 1 month to 1 year") . "' ELSE "
596 . "'" . _("6 - more than 1 year") . "' END END END END END END AS Time_Scale, "
597 . "remote_host AS Remote_Host, "
598 . "$Request_URI AS Request_URI "
600 . "WHERE (remote_host LIKE '%googlebot.com' "
601 . "OR remote_host LIKE '%alexa.com' "
602 . "OR remote_host LIKE '%inktomisearch.com' "
603 . "OR remote_host LIKE '%msnbot.msn.com') "
604 . ($where_conditions ? 'AND ' . $where_conditions : '')
605 . "ORDER BY time_stamp";
610 /** Honeypot for xgettext. Those strings are translated dynamically.
612 function _locale_dummy()
617 _("external_referers"),
618 _("referring_domains"),
623 _("search_bots_hits"),
632 function getDefaultArguments()
635 'mode' => 'referring_domains',
636 // referring_domains, referring_urls, remote_hosts, users, host_users, search_bots, search_bots_hits
638 // blank means use the mode as the caption/title for the output
639 'local_referrers' => 'true', // only show external referring sites
640 'period' => '', // the type of period to report:
641 // may be weeks, days, hours, minutes, or blank for all
642 'count' => '0' // the number of periods to report
646 function table_output()
648 $query = $this->_getQueryString($args);
651 return HTML::p(sprintf(_("Unrecognised parameter 'mode=%s'"),
654 // get the data back.
655 // Note that this must be done before the final generation ofthe table,
656 // otherwise the headers will not be ready
657 $tbody = $this->_getQueryResults($query, $dbi);
659 return HTML::table(array('border' => 1,
662 HTML::caption(HTML::h1(HTML::br(), $this->_getCaption($args))),
663 HTML::thead($this->_theadrow),
667 function _getQueryResults($query, &$dbi)
669 $queryResult = $dbi->genericSqlIter($query);
671 $tbody = HTML::tbody(HTML::tr(HTML::td(_("<empty>"))));
673 $tbody = HTML::tbody();
674 while ($row = $queryResult->next()) {
675 $this->_setHeaders($row);
677 foreach ($row as $value) {
678 // output a '-' for empty values, otherwise the table looks strange
679 $tr->pushContent(HTML::td(empty($value) ? '-' : $value));
681 $tbody->pushContent($tr);
684 $queryResult->free();
688 function _setHeaders($row)
690 if (!$this->_headerSet) {
691 foreach ($row as $key => $value) {
692 $this->_theadrow->pushContent(HTML::th(_($key)));
694 $this->_headerSet = true;
698 function _getWhereConditions(&$args)
700 $where_conditions = '';
702 if ($args['period'] <> '') {
704 if ($args['period'] == 'minutes') {
706 } elseif ($args['period'] == 'hours') {
708 } elseif ($args['period'] == 'days') {
709 $since = 60 * 60 * 24;
710 } elseif ($args['period'] == 'weeks') {
711 $since = 60 * 60 * 24 * 7;
713 $since = $since * $args['count'];
715 if ($where_conditions <> '')
716 $where_conditions = $where_conditions . ' AND ';
717 $since = time() - $since;
718 $where_conditions = $where_conditions . "time_stamp > $since";
722 if ($args['local_referrers'] <> 'true') {
724 if ($where_conditions <> '')
725 $where_conditions = $where_conditions . ' AND ';
726 $localhost = SERVER_URL;
727 $len = strlen($localhost);
728 $backend_type = $request->_dbi->_backend->backendType();
729 switch ($backend_type) {
731 $ref_localhost = "left(referer,$len)<>'$localhost'";
735 $ref_localhost = "substr(referer,0,$len)<>'$localhost'";
740 $where_conditions = $where_conditions . $ref_localhost;
743 // The assumed contract is that there is a space at the end of the
744 // conditions string, so that following SQL clauses (such as GROUP BY)
745 // will not cause a syntax error
746 if ($where_conditions <> '')
747 $where_conditions = $where_conditions . ' ';
749 return $where_conditions;
752 function _getCaption(&$args)
754 $caption = $args['caption'];
756 $caption = gettext($args['mode']);
757 if ($args['period'] <> '' && $args['count'])
758 $caption = $caption . " - " . $args['count'] . " " . gettext($args['period']);
768 // c-hanging-comment-ender-p: nil
769 // indent-tabs-mode: nil