drupal/modules/statistics.module

493 lines
22 KiB
Plaintext

<?php
// $Id$
/**
* @file
* Logs access statistics for your site.
*/
/**
* Implementation of hook_help().
*/
function statistics_help($section) {
switch ($section) {
case 'admin/help#statistics':
return t("
<h3>Introduction</h3>
<p>The statistics module keeps track of numerous statistics for your site but be warned, statistical collection does cause a little overhead, thus everything comes <strong>disabled</strong> by default.</p>
<p>The module counts how many times, and from where -- using HTTP referrer -- each of your posts is viewed. Once we have that count the module can do the following with it:
<ul>
<li>The count can be displayed in the node's link section next to \"# comments\".</li>
<li>A configurable block can be added which can display a configurable number of the day's top stories, the all time top stories, and the last stories read.</li>
<li>A configurable user page can be added, which can display the day's top stories, the all time top stories, and the last stories read. You can individually configure how many posts are displayed in each section.</li>
</ul>
<p>Notes on using the statistics:</p>
<ul>
<li>If you enable the view counters for content, this adds 1 database query for each node that is viewed (2 queries if it's the first time the node has ever been viewed).</li>
<li>If you enable the access log, this adds 1 database query for each page that Drupal displays. Logged information includes: HTTP referrer (if any), node being accessed (if any), user ID (if any), the IP address of the user, and the time the page was viewed.</li>
</ul>
<p>As with any new module, the statistics module needs to be <a href=\"%modules\">enabled</a> before you can use it. Also refer to the <a href=\"%permissions\">permissions section</a>, as this module supports four separate permissions.</p>
<h3>Configuring the statistics module</h3>
<p>There are some configuration options added to the main <a href=\"%configuration\">administer &raquo; settings &raquo; statistics</a> section:</p>
<ul>
<li><em>enable access log</em> -- allows you to turn the access log on and off. This log is used to store data about every page accessed, such as the remote host's IP address, where they came from (referrer), what node they've viewed, and their user name. Enabling the log adds one database call per page displayed by Drupal.</li>
<li><em>discard access logs older than</em> -- allows you to configure how long an access log entry is saved, after which time it is deleted from the database table. To use this you need to run \"cron.php\"</li>
<li><em>enable node view counter</em> -- allows you to turn on and off the node-counting functionality of this module. If it is turned on, an extra database query is added for each node displayed, which increments a counter.</li>
<li><em>display node view counters</em> -- allows you to globally disable the displaying of node view counters.</li>
</ul>
<h3>Popular content block</h3>
<p>This module creates a block that can display the day's top viewed content, the all time top viewed content, and the last content viewed. Each of these links can be enabled or disabled individually, and the number of posts displayed for each can be configured with a drop down menu. If you disable all sections of this block, it will not appear.</p>
<p>Don't forget to <a href=\"%block\">enable the block</a>.</p>",
array('%modules' => url('admin/modules'), '%permissions' => url('admin/access/permissions'), '%referer' => url('admin/logs/referrers'), '%configuration' => url('admin/settings/statistics'), '%block' => url('admin/block')));
case 'admin/modules#description':
return t('Logs access statistics for your site.');
case 'admin/settings/statistics':
return t('<p>Settings for the statistical information that Drupal will keep about the site. See <a href="%statistics">site statistics</a> for the actual information.</p>', array('%statistics' => url('admin/logs/hits')));
case 'admin/logs/hits':
return t('<p>This page shows you the most recent hits.</p>');
case 'admin/logs/referrers':
return t('<p>This page shows you all external referrers. These are links pointing to your web site from outside your web site.</p>');
case 'admin/logs/visitors':
return t('<p>When you ban a visitor, you prevent his IP address from accessing your site. Unlike blocking a user, banning a visitor works even for anonymous users. The most common use for this is to block bots/web crawlers that are consuming too many resources.</p>');
}
}
/**
* Implementation of hook_exit().
*
* This is where statistics are gathered on page accesses.
*/
function statistics_exit() {
global $user, $recent_activity;
if (variable_get('statistics_count_content_views', 0)) {
// We are counting content views.
if ((arg(0) == 'node') && arg(1)) {
// A node has been viewed, so update the node's counters.
db_query('UPDATE {node_counter} SET daycount = daycount + 1, totalcount = totalcount + 1, timestamp = %d WHERE nid = %d', time(), arg(1));
// If we affected 0 rows, this is the first time viewing the node.
if (!db_affected_rows()) {
// We must create a new row to store counters for the new node.
db_query('INSERT INTO {node_counter} (nid, daycount, totalcount, timestamp) VALUES(%d, 1, 1, %d)', arg(1), time());
}
}
}
if ((variable_get('statistics_enable_access_log', 0)) && (module_invoke('throttle', 'status') == 0)) {
// Log this page access.
db_query("INSERT INTO {accesslog} (title, path, url, hostname, uid, timer, timestamp) values('%s', '%s', '%s', '%s', %d, %d, %d)", drupal_get_title(), $_GET['q'], referer_uri(), $_SERVER['REMOTE_ADDR'], $user->uid, timer_read('page'), time());
}
}
/**
* Implementation of hook_perm().
*/
function statistics_perm() {
return array('access statistics');
}
/**
* Implementation of hook_link().
*/
function statistics_link($type, $node = 0, $main = 0) {
global $id;
$links = array();
if ($type != 'comment' && variable_get('statistics_display_counter', 0)) {
$statistics = statistics_get($node->nid);
if ($statistics) {
$links[] = format_plural($statistics['totalcount'], '1 read', '%count reads');
}
}
return $links;
}
/**
* Implementation of hook_menu().
*/
function statistics_menu($may_cache) {
$items = array();
$access = user_access('access statistics');
if ($may_cache) {
$items[] = array('path' => 'admin/logs/hits', 'title' => t('recent hits'),
'callback' => 'statistics_recent_hits', 'access' => $access,
'weight' => 3);
$items[] = array('path' => 'admin/logs/pages', 'title' => t('top pages'),
'callback' => 'statistics_top_pages', 'access' => $access,
'weight' => 1);
$items[] = array('path' => 'admin/logs/visitors', 'title' => t('top visitors'),
'callback' => 'statistics_top_visitors', 'access' => $access,
'weight' => 2);
$items[] = array('path' => 'admin/logs/referrers', 'title' => t('referrers'),
'callback' => 'statistics_top_referrers', 'access' => $access);
$items[] = array('path' => 'admin/logs/access', 'title' => t('details'),
'callback' => 'statistics_access_log', 'access' => $access,
'type' => MENU_CALLBACK);
}
else {
if (arg(0) == 'user' && is_numeric(arg(1))) {
$items[] = array('path' => 'user/'. arg(1) .'/track/navigation', 'title' => t('track page visits'),
'callback' => 'statistics_user_tracker', 'access' => $access,
'type' => MENU_LOCAL_TASK, 'weight' => 2);
}
if (arg(0) == 'node' && is_numeric(arg(1))) {
$items[] = array('path' => 'node/'. arg(1) .'/track', 'title' => t('track'),
'callback' => 'statistics_node_tracker', 'access' => $access,
'type' => MENU_LOCAL_TASK, 'weight' => 2);
}
}
return $items;
}
function statistics_access_log($aid) {
$result = db_query('SELECT a.*, u.name FROM {accesslog} a LEFT JOIN {users} u ON a.uid = u.uid WHERE aid = %d', $aid);
if ($access = db_fetch_object($result)) {
$output = '<table border="1" cellpadding="2" cellspacing="2">';
$output .= ' <tr><th>'. t('Page URL') ."</th><td>". l(url($access->path, NULL, NULL, TRUE), $access->url) ."</td></tr>";
$output .= ' <tr><th>'. t('Page title') .'</th><td>'. check_plain($access->title) .'</td></tr>';
$output .= ' <tr><th>'. t('Referrer') ."</th><td>". ($access->url ? l($access->url, $access->url) : '') ."</td></tr>";
$output .= ' <tr><th>'. t('Date') .'</th><td>'. format_date($access->timestamp, 'large') .'</td></tr>';
$output .= ' <tr><th>'. t('User') .'</th><td>'. theme('username', $access) .'</td></tr>';
$output .= ' <tr><th>'. t('Hostname') .'</th><td>'. check_plain($access->hostname) .'</td></tr>';
$output .= '</table>';
return $output;
}
else {
drupal_not_found();
}
}
function statistics_node_tracker() {
if ($node = node_load(arg(1))) {
$header = array(
array('data' => t('Time'), 'field' => 'a.timestamp', 'sort' => 'desc'),
array('data' => t('Referrer'), 'field' => 'a.url'),
array('data' => t('User'), 'field' => 'u.name'),
array('data' => t('Operations')));
$result = pager_query('SELECT a.aid, a.timestamp, a.url, a.uid, u.name FROM {accesslog} a LEFT JOIN {users} u ON a.uid = u.uid WHERE a.path LIKE \'node/%d%%\'' . tablesort_sql($header), 30, 0, NULL, $node->nid);
while ($log = db_fetch_object($result)) {
$rows[] = array(
array('data' => format_date($log->timestamp, 'small'), 'class' => 'nowrap'),
l(_statistics_column_width($log->url), $log->url),
theme('username', $log),
l(t('details'), "admin/logs/access/$log->aid"));
}
if ($pager = theme('pager', NULL, 30, 0, tablesort_pager())) {
$rows[] = array(array('data' => $pager, 'colspan' => '4'));
}
drupal_set_title(check_plain($node->title));
return theme('table', $header, $rows);
}
else {
drupal_not_found();
}
}
function statistics_user_tracker() {
if ($account = user_load(array('uid' => arg(1)))) {
$header = array(
array('data' => t('Timestamp'), 'field' => 'timestamp', 'sort' => 'desc'),
array('data' => t('Page'), 'field' => 'path'),
array('data' => t('Operations')));
$result = pager_query('SELECT aid, timestamp, path, title FROM {accesslog} WHERE uid = %d' . tablesort_sql($header), 30, 0, NULL, $account->uid);
while ($log = db_fetch_object($result)) {
$rows[] = array(
array('data' => format_date($log->timestamp, 'small'), 'class' => 'nowrap'),
_statistics_format_item($log->title, $log->path),
l(t('details'), "admin/logs/access/$log->aid"));
}
if ($pager = theme('pager', NULL, 30, 0, tablesort_pager())) {
$rows[] = array(array('data' => $pager, 'colspan' => '3'));
}
drupal_set_title($account->name);
return theme('table', $header, $rows);
}
else {
drupal_not_found();
}
}
/**
* Menu callback; presents the "recent hits" page.
*/
function statistics_recent_hits($type = 'all', $id = 0) {
$header = array(
array('data' => t('Timestamp'), 'field' => 'a.timestamp', 'sort' => 'desc'),
array('data' => t('Page'), 'field' => 'a.path'),
array('data' => t('User'), 'field' => 'u.name'),
array('data' => t('Operations'))
);
$sql = 'SELECT a.aid, a.path, a.title, a.uid, u.name, a.timestamp FROM {accesslog} a LEFT JOIN {users} u ON u.uid = a.uid' . tablesort_sql($header);
$result = pager_query($sql, 30);
while ($log = db_fetch_object($result)) {
$rows[] = array(
array('data' => format_date($log->timestamp, 'small'), 'class' => 'nowrap'),
_statistics_format_item($log->title, $log->path),
theme('username', $log),
l(t('details'), "admin/logs/access/$log->aid"));
}
if ($pager = theme('pager', NULL, 30, 0, tablesort_pager())) {
$rows[] = array(array('data' => $pager, 'colspan' => '4'));
}
return theme('table', $header, $rows);
}
/**
* Menu callback; presents the "top pages" page.
*/
function statistics_top_pages() {
$sql = "SELECT COUNT(path) AS hits, path, title, AVG(timer) AS average_time, SUM(timer) AS total_time FROM {accesslog} GROUP BY path";
$sql_cnt = "SELECT COUNT(DISTINCT(path)) FROM {accesslog}";
$header = array(
array('data' => t('Hits'), 'field' => 'hits', 'sort' => 'desc'),
array('data' => t('Page'), 'field' => 'path'),
array('data' => t('Average page generation time'), 'field' => 'average_time'),
array('data' => t('Total page generation time'), 'field' => 'total_time')
);
$sql .= tablesort_sql($header);
$result = pager_query($sql, 30, 0, $sql_cnt);
while ($page = db_fetch_object($result)) {
$rows[] = array($page->hits, _statistics_format_item($page->title, $page->path), t('%time ms', array('%time' => round($page->average_time))), format_interval(round($page->total_time / 1000)));
}
if ($pager = theme('pager', NULL, 30, 0, tablesort_pager())) {
$rows[] = array(array('data' => $pager, 'colspan' => '4'));
}
drupal_set_title(t('Top pages in the past %interval', array('%interval' => format_interval(variable_get('statistics_flush_accesslog_timer', 259200)))));
return theme('table', $header, $rows);
}
/**
* Menu callback; presents the "top visitors" page.
*/
function statistics_top_visitors() {
$header = array(
array('data' => t('Hits'), 'field' => 'hits', 'sort' => 'desc'),
array('data' => t('Visitor'), 'field' => 'u.name'),
array('data' => t('Total page generation time'), 'field' => 'total'),
array('data' => t('Operations'))
);
$sql = "SELECT COUNT(a.uid) AS hits, a.uid, u.name, a.hostname, SUM(a.timer) AS total, ac.aid FROM {accesslog} a LEFT JOIN {access} ac ON ac.type = 'host' AND LOWER(a.hostname) LIKE (ac.mask) LEFT JOIN {users} u ON a.uid = u.uid GROUP BY a.hostname". tablesort_sql($header);
$sql_cnt = "SELECT COUNT(DISTINCT(uid)) FROM {accesslog}";
$result = pager_query($sql, 30, 0, $sql_cnt);
while ($account = db_fetch_object($result)) {
$qs = drupal_get_destination();
$ban_link = $account->aid ? l(t('unban'), "admin/access/rules/delete/$account->aid", array(), $qs) : l(t('ban'), "admin/access/rules/add/$account->hostname/host", array(), $qs);
$rows[] = array($account->hits, ($account->uid ? theme('username', $account) : $account->hostname), format_interval(round($account->total / 1000)), $ban_link);
}
if ($pager = theme('pager', NULL, 30, 0, tablesort_pager())) {
$rows[] = array(array('data' => $pager, 'colspan' => '4'));
}
drupal_set_title(t('Top visitors in the past %interval', array('%interval' => format_interval(variable_get('statistics_flush_accesslog_timer', 259200)))));
return theme('table', $header, $rows);
}
/**
* Menu callback; presents the "referrer" page.
*/
function statistics_top_referrers() {
$query = "SELECT url, COUNT(url) AS hits, MAX(timestamp) AS last FROM {accesslog} WHERE url NOT LIKE '%%%s%%' AND url <> '' GROUP BY url";
$query_cnt = "SELECT COUNT(DISTINCT(url)) FROM {accesslog} WHERE url <> '' AND url NOT LIKE '%%%s%%'";
drupal_set_title(t('Top referrers in the past %interval', array('%interval' => format_interval(variable_get('statistics_flush_accesslog_timer', 259200)))));
$header = array(
array('data' => t('Hits'), 'field' => 'hits', 'sort' => 'desc'),
array('data' => t('Url'), 'field' => 'url'),
array('data' => t('Last visit'), 'field' => 'last'),
);
$query .= tablesort_sql($header);
$result = pager_query($query, 30, 0, $query_cnt, $_SERVER['HTTP_HOST']);
while ($referrer = db_fetch_object($result)) {
$rows[] = array($referrer->hits, '<a href="'. check_url($referrer->url) .'">'. check_plain(_statistics_column_width($referrer->url)) .'</a>', t('%time ago', array('%time' => format_interval(time() - $referrer->last))));
}
if ($pager = theme('pager', NULL, 30, 0, tablesort_pager())) {
$rows[] = array(array('data' => $pager, 'colspan' => '3'));
}
return theme('table', $header, $rows);
}
/**
* Implementation of hook_settings().
*/
function statistics_settings() {
// access log settings:
$group = form_radios(t('Enable access log'), 'statistics_enable_access_log', variable_get('statistics_enable_access_log', 0), array('1' => t('Enabled'), '0' => t('Disabled')), t('Log each page access. Required for referrer statistics.'));
$period = drupal_map_assoc(array(3600, 10800, 21600, 32400, 43200, 86400, 172800, 259200, 604800, 1209600, 2419200, 4838400, 9676800), 'format_interval');
$group .= form_select(t('Discard access logs older than'), 'statistics_flush_accesslog_timer', variable_get('statistics_flush_accesslog_timer', 259200), $period, t('Older access log entries (including referrer statistics) will be automatically discarded. Requires crontab.'));
$output = form_group(t('Access log settings'), $group);
// count content views settings
$group = form_radios(t('Count content views'), 'statistics_count_content_views', variable_get('statistics_count_content_views', 0), array('1' => t('Enabled'), '0' => t('Disabled')), t('Increment a counter each time content is viewed.'));
$group .= form_radios(t('Display counter values'), 'statistics_display_counter', variable_get('statistics_display_counter', 0), array('1' => t('Enabled'), '0' => t('Disabled')), t('Display how many times given content has been viewed.'));
$output .= form_group(t('Content viewing counter settings'), $group);
return $output;
}
/**
* Implementation of hook_cron().
*/
function statistics_cron() {
$statistics_timestamp = variable_get('statistics_day_timestamp', '');
if ((time() - $statistics_timestamp) >= 86400) {
/* reset day counts */
db_query('UPDATE {node_counter} SET daycount = 0');
variable_set('statistics_day_timestamp', time());
}
/* clean expired access logs */
db_query('DELETE FROM {accesslog} WHERE timestamp < %d', time() - variable_get('statistics_flush_accesslog_timer', 259200));
}
/**
* Returns all time or today top or last viewed node(s).
*
* @param $dbfield
* one of
* - 'totalcount': top viewed content of all time.
* - 'daycount': top viewed content for today.
* - 'timestamp': last viewed node.
*
* @param $dbrows
* number of rows to be returned.
*
* @return
* A query result containing n.nid, n.title, u.uid, u.name of the selected node(s)
* or FALSE if the query could not be executed correctly.
*/
function statistics_title_list($dbfield, $dbrows) {
return db_query_range(db_rewrite_sql("SELECT n.nid, n.title, u.uid, u.name FROM {node_counter} s INNER JOIN {node} n ON s.nid = n.nid INNER JOIN {users} u ON n.uid = u.uid WHERE %s <> '0' AND n.status = 1 ORDER BY %s DESC"), 's.'. $dbfield, 's.'. $dbfield, 0, $dbrows);
}
/**
* Retrieves a node's "view statistics".
*
* @param $nid
* node ID
*
* @return
* An array with three entries: [0]=totalcount, [1]=daycount, [2]=timestamp
* - totalcount: count of the total number of times that node has been viewed.
* - daycount: count of the total number of times that node has been viewed "today".
* For the daycount to be reset, cron must be enabled.
* - timestamp: timestamp of when that node was last viewed.
*/
function statistics_get($nid) {
if ($nid > 0) {
/* retrieves an array with both totalcount and daycount */
$statistics = db_fetch_array(db_query('SELECT totalcount, daycount, timestamp FROM {node_counter} WHERE nid = %d', $nid));
}
return $statistics;
}
/**
* Implementation of hook_block().
*/
function statistics_block($op = 'list', $delta = 0, $edit = array()) {
switch ($op) {
case 'list':
if (variable_get('statistics_count_content_views', 0)) {
$blocks[0]['info'] = t('Popular content');
}
return $blocks;
case 'configure':
// Popular content block settings
$numbers = array('0' => t('Disabled')) + drupal_map_assoc(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25, 30, 40));
$output = form_select(t("Number of day's top views to display"), 'statistics_block_top_day_num', variable_get('statistics_block_top_day_num', 0), $numbers, t('How many content items to display in "day" list.'));
$output .= form_select(t('Number of all time views to display'), 'statistics_block_top_all_num', variable_get('statistics_block_top_all_num', 0), $numbers, t('How many content items to display in "all time" list.'));
$output .= form_select(t('Number of most recent views to display'), 'statistics_block_top_last_num', variable_get('statistics_block_top_last_num', 0), $numbers, t('How many content items to display in "recently viewed" list.'));
return $output;
case 'save':
variable_set('statistics_block_top_day_num', $edit['statistics_block_top_day_num']);
variable_set('statistics_block_top_all_num', $edit['statistics_block_top_all_num']);
variable_set('statistics_block_top_last_num', $edit['statistics_block_top_last_num']);
break;
case 'view':
if (user_access('access content')) {
$content = array();
$daytop = variable_get('statistics_block_top_day_num', 0);
if ($daytop && ($result = statistics_title_list('daycount', $daytop)) && db_num_rows($result)) {
$content[] = node_title_list($result, t("Today's:"));
}
$alltimetop = variable_get('statistics_block_top_all_num', 0);
if ($alltimetop && ($result = statistics_title_list('totalcount', $alltimetop)) && db_num_rows($result)) {
$content[] = node_title_list($result, t('All time:'));
}
$lasttop = variable_get('statistics_block_top_last_num', 0);
if ($lasttop && ($result = statistics_title_list('timestamp', $lasttop)) && db_num_rows($result)) {
$content[] = node_title_list($result, t('Last viewed:'));
}
if (count($content)) {
$block['content'] = implode('<br />', $content);
$block['subject'] = t('Popular content');
return $block;
}
}
}
}
/**
* It is possible to adjust the width of columns generated by the
* statistics module.
*/
function _statistics_column_width($column, $width = 35) {
return (strlen($column) > $width ? substr($column, 0, $width) . '...' : $column);
}
function _statistics_format_item($title, $link) {
$link = ($link ? $link : '/');
$output = ($title ? "$title<br />" : '');
$output .= l(_statistics_column_width($link), $link);
return $output;
}
/**
* Implementation of hook_nodeapi().
*/
function statistics_nodeapi(&$node, $op, $arg = 0) {
switch ($op) {
case 'delete':
// clean up statistics table when node is deleted
db_query('DELETE FROM {node_counter} WHERE nid = %d', $node->nid);
}
}