Code coverage for /20080809/modules/statistics/statistics.module

Line #Times calledCode
1
<?php
2
// $Id: statistics.module,v 1.279 2008/06/12 18:46:51 dries Exp $
3
4
/**
5
 * @file
6
 * Logs access statistics for your site.
7
 */
8
9
/**
10
 * Implementation of hook_help().
11
 */
1229
function statistics_help($path, $arg) {
13
  switch ($path) {
1422
    case 'admin/help#statistics':
150
      $output = '<p>' . t('The statistics module keeps track of numerous
site usage statistics, including the number of times, and from where, each
of your posts is viewed. These statistics are useful in determining how
users are interacting with each other and with your site, and are required
for the display of some Drupal blocks.') . '</p>';
160
      $output .= '<p>' . t('The statistics module provides:') . '</p>';
170
      $output .= '<ul><li>' . t('a counter for each post on your site that
increments each time the post is viewed. (Enable <em>Count content
views</em> on the <a href="@accesslog">access log settings page</a>, and
determine if the post access counters should be visible to any user roles
on the <a href="@permissions">permissions page</a>.)', array('@accesslog'
=> url('admin/reports/settings'), '@permissions' =>
url('admin/user/permissions'))) . '</li>';
180
      $output .= '<li>' . t('a <a href="@recent-hits">recent hits</a> log
that displays information about the latest activity on your site, including
the URL and title of the page accessed, the user name (if available) and IP
address of the accessing party.', array('@recent-hits' =>
url('admin/reports/hits'))) . '</li>';
190
      $output .= '<li>' . t('a <a href="@top-referrers">top referrers</a>
log that displays the referring parties for your site visits (where your
visitors came from).', array('@top-referrers' =>
url('admin/reports/referrers'))) . '</li>';
200
      $output .= '<li>' . t('a <a href="@top-pages">top pages</a> log that
displays site content in descending order by number of views.',
array('@top-pages' => url('admin/reports/pages'))) . '</li>';
210
      $output .= '<li>' . t('a <a href="@top-visitors">top visitors</a> log
that displays the most active users on your site.', array('@top-visitors'
=> url('admin/reports/visitors'))) . '</li>';
220
      $output .= '<li>' . t('a <em>Popular content</em> block that displays
the day\'s most viewed content, the all-time most viewed content, and the
last content viewed. (Enable the <em>Popular content</em> block on the <a
href="@blocks">blocks administration page</a>.)', array('@blocks' =>
url('admin/build/block'))) . '</li></ul>';
230
      $output .= '<p>' . t('Configuring the statistics module') . '</p>';
240
      $output .= '<ul><li>' . t('When the <em>Enable access log</em>
setting on the <a href="@accesslog">access log settings page</a> is
enabled, data about every page accessed (including the remote host\'s IP
address, referrer, node accessed, and user name) is stored in the access
log. The access log must be enabled for the <a href="@recent-hits">recent
hits</a>, <a href="@top-referrers">top referrers</a>, <a
href="@top-pages">top pages</a>, and <a href="@top-visitors">top
visitors</a> log pages to function. Enabling the access log adds one
additional database call per page displayed by Drupal.', array('@accesslog'
=> url('admin/reports/settings'), '@recent-hits' =>
url('admin/reports/hits'), '@top-referrers' =>
url('admin/reports/referrers'), '@top-pages' => url('admin/reports/pages'),
'@top-visitors' => url('admin/reports/visitors'))) . '</li>';
250
      $output .= '<li>' . t('The <em>Discard access logs older than</em>
setting on the <a href="@accesslog">access log settings page</a> specifies
the length of time entries are retained in the access log before they are
deleted. Automatic access log entry deletion requires a correctly
configured <a href="@cron">cron maintenance task</a>.', array('@accesslog'
=> url('admin/reports/settings'), '@cron' => url('admin/reports/status')))
. '</li>';
260
      $output .= '<li>' . t('The <em>Count content views</em> setting on
the <a href="@accesslog">access log settings page</a> enables a counter for
each post on your site that increments each time the post is viewed. This
option must be enabled to provide post-specific access counts. Enabling
this option adds one additional database call per each post displayed by
Drupal.', array('@accesslog' => url('admin/reports/settings'))) .
'</li></ul>';
270
      $output .= '<p>' . t('For more information, see the online handbook
entry for <a href="@statistics">Statistics module</a>.',
array('@statistics' => 'http://drupal.org/handbook/modules/statistics/')) .
'</p>';
280
      return $output;
2922
    case 'admin/reports/settings':
300
      return '<p>' . t('Settings for the statistical information that
Drupal will keep about the site. See <a href="@statistics">site
statistics</a> for the actual information.', array('@statistics' =>
url('admin/reports/hits'))) . '</p>';
3122
    case 'admin/reports/hits':
320
      return '<p>' . t("This page displays the site's most recent hits.") .
'</p>';
3322
    case 'admin/reports/referrers':
340
      return '<p>' . t('This page displays all external referrers, or
external references to your website.') . '</p>';
3522
    case 'admin/reports/visitors':
362
      return '<p>' . t("When you ban a visitor, you prevent the visitor's
IP address from accessing your site. Unlike blocking a user, banning a
visitor works even for anonymous users. This is most commonly used to block
resource-intensive bots or web crawlers.") . '</p>';
370
  }
3822
}
39
40
/**
41
 * Implementation of hook_exit().
42
 *
43
 * This is where statistics are gathered on page accesses.
44
 */
4529
function statistics_exit() {
4627
  global $user;
47
4827
  drupal_bootstrap(DRUPAL_BOOTSTRAP_PATH);
49
5027
  if (variable_get('statistics_count_content_views', 0)) {
51
    // We are counting content views.
525
    if ((arg(0) == 'node') && is_numeric(arg(1)) && arg(2) == '') {
53
      // A node has been viewed, so update the node's counters.
545
      db_query('UPDATE {node_counter} SET daycount = daycount + 1,
totalcount = totalcount + 1, timestamp = %d WHERE nid = %d', time(),
arg(1));
55
      // If we affected 0 rows, this is the first time viewing the node.
565
      if (!db_affected_rows()) {
57
        // We must create a new row to store counters for the new node.
581
        db_query('INSERT INTO {node_counter} (nid, daycount, totalcount,
timestamp) VALUES (%d, 1, 1, %d)', arg(1), time());
591
      }
605
    }
615
  }
6227
  if (variable_get('statistics_enable_access_log', 0)) {
63
    // Log this page access.
6414
    db_query("INSERT INTO {accesslog} (title, path, url, hostname, uid,
sid, timer, timestamp) values('%s', '%s', '%s', '%s', %d, '%s', %d, %d)",
strip_tags(drupal_get_title()), $_GET['q'], referer_uri(), ip_address(),
$user->uid, session_id(), timer_read('page'), time());
6514
  }
6627
}
67
68
/**
69
 * Implementation of hook_perm().
70
 */
7129
function statistics_perm() {
72
  return array(
732
    'access statistics' => t('View content access statistics.'),
742
    'view post access counter' => t('View the total number of times a piece
of content has been accessed.'),
752
  );
760
}
77
78
/**
79
 * Implementation of hook_link().
80
 */
8129
function statistics_link($type, $node = NULL, $teaser = FALSE) {
829
  global $id;
839
  $links = array();
84
859
  if ($type != 'comment' && user_access('view post access counter')) {
860
    $statistics = statistics_get($node->nid);
870
    if ($statistics) {
880
      $links['statistics_counter']['title'] =
format_plural($statistics['totalcount'], '1 read', '@count reads');
890
    }
900
  }
91
929
  return $links;
930
}
94
95
/**
96
 * Implementation of hook_menu().
97
 */
9829
function statistics_menu() {
992
  $items['admin/reports/hits'] = array(
1002
    'title' => 'Recent hits',
1012
    'description' => 'View pages that have recently been visited.',
1022
    'page callback' => 'statistics_recent_hits',
1032
    'access arguments' => array('access statistics'),
104
  );
1052
  $items['admin/reports/pages'] = array(
1062
    'title' => 'Top pages',
1072
    'description' => 'View pages that have been hit frequently.',
1082
    'page callback' => 'statistics_top_pages',
1092
    'access arguments' => array('access statistics'),
1102
    'weight' => 1,
111
  );
1122
  $items['admin/reports/visitors'] = array(
1132
    'title' => 'Top visitors',
1142
    'description' => 'View visitors that hit many pages.',
1152
    'page callback' => 'statistics_top_visitors',
1162
    'access arguments' => array('access statistics'),
1172
    'weight' => 2,
118
  );
1192
  $items['admin/reports/referrers'] = array(
1202
    'title' => 'Top referrers',
1212
    'description' => 'View top referrers.',
1222
    'page callback' => 'statistics_top_referrers',
1232
    'access arguments' => array('access statistics'),
124
  );
1252
  $items['admin/reports/access/%'] = array(
1262
    'title' => 'Details',
1272
    'description' => 'View access log.',
1282
    'page callback' => 'statistics_access_log',
1292
    'page arguments' => array(3),
1302
    'access arguments' => array('access statistics'),
1312
    'type' => MENU_CALLBACK,
132
  );
1332
  $items['admin/reports/settings'] = array(
1342
    'title' => 'Access log settings',
1352
    'description' => 'Control details about what and how your site logs.',
1362
    'page callback' => 'drupal_get_form',
1372
    'page arguments' => array('statistics_access_logging_settings'),
1382
    'access arguments' => array('administer site configuration'),
1392
    'type' => MENU_NORMAL_ITEM,
1402
    'weight' => 3,
141
  );
1422
  $items['user/%user/track/navigation'] = array(
1432
    'title' => 'Track page visits',
1442
    'page callback' => 'statistics_user_tracker',
1452
    'access callback' => 'user_access',
1462
    'access arguments' => array('access statistics'),
1472
    'type' => MENU_LOCAL_TASK,
1482
    'weight' => 2,
149
  );
1502
  $items['node/%node/track'] = array(
1512
    'title' => 'Track',
1522
    'page callback' => 'statistics_node_tracker',
1532
    'access callback' => 'user_access',
1542
    'access arguments' => array('access statistics'),
1552
    'type' => MENU_LOCAL_TASK,
1562
    'weight' => 2,
157
  );
158
1592
  return $items;
1600
}
161
162
/**
163
 * Implementation of hook_user().
164
 */
16529
function statistics_user($op, &$edit, &$user) {
16628
  if ($op == 'delete') {
1670
    db_query('UPDATE {accesslog} SET uid = 0 WHERE uid = %d', $user->uid);
1680
  }
16928
}
170
171
/**
172
 * Implementation of hook_cron().
173
 */
17429
function statistics_cron() {
1750
  $statistics_timestamp = variable_get('statistics_day_timestamp', '');
176
1770
  if ((time() - $statistics_timestamp) >= 86400) {
178
    // Reset day counts.
1790
    db_query('UPDATE {node_counter} SET daycount = 0');
1800
    variable_set('statistics_day_timestamp', time());
1810
  }
182
183
  // Clean up expired access logs.
1840
  db_query('DELETE FROM {accesslog} WHERE timestamp < %d', time() -
variable_get('statistics_flush_accesslog_timer', 259200));
1850
}
186
187
/**
188
 * Returns all time or today top or last viewed node(s).
189
 *
190
 * @param $dbfield
191
 *   one of
192
 *   - 'totalcount': top viewed content of all time.
193
 *   - 'daycount': top viewed content for today.
194
 *   - 'timestamp': last viewed node.
195
 *
196
 * @param $dbrows
197
 *   number of rows to be returned.
198
 *
199
 * @return
200
 *   A query result containing n.nid, n.title, u.uid, u.name of the
selected node(s)
201
 *   or FALSE if the query could not be executed correctly.
202
 */
20329
function statistics_title_list($dbfield, $dbrows) {
2040
  if (in_array($dbfield, array('totalcount', 'daycount', 'timestamp'))) {
2050
    return db_query_range(db_rewrite_sql("SELECT n.nid, n.title, u.uid,
u.name FROM {node} n INNER JOIN {node_counter} s ON n.nid = s.nid INNER
JOIN {users} u ON n.uid = u.uid WHERE s." . $dbfield . " != 0 AND n.status
= 1 ORDER BY s." . $dbfield . " DESC"), 0, $dbrows);
2060
  }
2070
  return FALSE;
2080
}
209
210
211
/**
212
 * Retrieves a node's "view statistics".
213
 *
214
 * @param $nid
215
 *   node ID
216
 *
217
 * @return
218
 *   An array with three entries: [0]=totalcount, [1]=daycount,
[2]=timestamp
219
 *   - totalcount: count of the total number of times that node has been
viewed.
220
 *   - daycount: count of the total number of times that node has been
viewed "today".
221
 *     For the daycount to be reset, cron must be enabled.
222
 *   - timestamp: timestamp of when that node was last viewed.
223
 */
22429
function statistics_get($nid) {
225
2260
  if ($nid > 0) {
227
    // Retrieve an array with both totalcount and daycount.
2280
    $statistics = db_fetch_array(db_query('SELECT totalcount, daycount,
timestamp FROM {node_counter} WHERE nid = %d', $nid));
2290
  }
230
2310
  return $statistics;
2320
}
233
234
/**
235
 * Implementation of hook_block().
236
 */
23729
function statistics_block($op = 'list', $delta = '', $edit = array()) {
238
  switch ($op) {
2390
    case 'list':
2400
      if (variable_get('statistics_count_content_views', 0)) {
2410
        $blocks['popular']['info'] = t('Popular content');
242
        // Too dynamic to cache.
2430
        $blocks['popular']['cache'] = BLOCK_NO_CACHE;
2440
        return $blocks;
2450
      }
2460
      break;
247
2480
    case 'configure':
249
      // Popular content block settings
2500
      $numbers = array('0' => t('Disabled')) + drupal_map_assoc(array(1, 2,
3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25, 30, 40));
2510
      $form['statistics_block_top_day_num'] = array('#type' => 'select',
'#title' => t("Number of day's top views to display"), '#default_value' =>
variable_get('statistics_block_top_day_num', 0), '#options' => $numbers,
'#description' => t('How many content items to display in "day" list.'));
2520
      $form['statistics_block_top_all_num'] = array('#type' => 'select',
'#title' => t('Number of all time views to display'), '#default_value' =>
variable_get('statistics_block_top_all_num', 0), '#options' => $numbers,
'#description' => t('How many content items to display in "all time"
list.'));
2530
      $form['statistics_block_top_last_num'] = array('#type' => 'select',
'#title' => t('Number of most recent views to display'), '#default_value'
=> variable_get('statistics_block_top_last_num', 0), '#options' =>
$numbers, '#description' => t('How many content items to display in
"recently viewed" list.'));
2540
      return $form;
255
2560
    case 'save':
2570
      variable_set('statistics_block_top_day_num',
$edit['statistics_block_top_day_num']);
2580
      variable_set('statistics_block_top_all_num',
$edit['statistics_block_top_all_num']);
2590
      variable_set('statistics_block_top_last_num',
$edit['statistics_block_top_last_num']);
2600
      break;
261
2620
    case 'view':
2630
      if (user_access('access content')) {
2640
        $content = array();
265
2660
        $daytop = variable_get('statistics_block_top_day_num', 0);
2670
        if ($daytop && ($result = statistics_title_list('daycount',
$daytop)) && ($node_title_list = node_title_list($result, t("Today's:"))))
{
2680
          $content[] = $node_title_list;
2690
        }
270
2710
        $alltimetop = variable_get('statistics_block_top_all_num', 0);
2720
        if ($alltimetop && ($result = statistics_title_list('totalcount',
$alltimetop)) && ($node_title_list = node_title_list($result, t('All
time:')))) {
2730
          $content[] = $node_title_list;
2740
        }
275
2760
        $lasttop = variable_get('statistics_block_top_last_num', 0);
2770
        if ($lasttop && ($result = statistics_title_list('timestamp',
$lasttop)) && ($node_title_list = node_title_list($result, t('Last
viewed:')))) {
2780
          $content[] = $node_title_list;
2790
        }
280
2810
        if (count($content)) {
2820
          $block['content'] = implode('<br />', $content);
2830
          $block['subject'] = t('Popular content');
2840
          return $block;
2850
        }
2860
      }
2870
  }
2880
}
289
290
/**
291
 * It is possible to adjust the width of columns generated by the
292
 * statistics module.
293
 */
29429
function _statistics_link($path, $width = 35) {
2950
  $title = drupal_get_path_alias($path);
2960
  $title = truncate_utf8($title, $width, FALSE, TRUE);
2970
  return l($title, $path);
2980
}
299
30029
function _statistics_format_item($title, $path) {
3010
  $path = ($path ? $path : '/');
3020
  $output  = ($title ? "$title<br />" : '');
3030
  $output .= _statistics_link($path);
3040
  return $output;
3050
}
306
307
/**
308
 * Implementation of hook_nodeapi().
309
 */
31029
function statistics_nodeapi(&$node, $op, $arg = 0) {
311
  switch ($op) {
31210
    case 'delete':
313
      // clean up statistics table when node is deleted
3140
      db_query('DELETE FROM {node_counter} WHERE nid = %d', $node->nid);
3150
  }
31610
}
317
318
/**
319
 * Implementation of hook_ranking().
320
 */
32129
function statistics_ranking() {
3221
  if (variable_get('statistics_count_content_views', 0)) {
323
    return array(
324
      'views' => array(
3251
        'title' => t('Number of views'),
3261
        'join' => 'LEFT JOIN {node_counter} node_counter ON
node_counter.nid = i.sid',
327
        // Inverse law that maps the highest view count on the site to 1
and 0 to 0.
3281
        'score' => '2.0 - 2.0 / (1.0 + node_counter.totalcount * %f)',
3291
        'arguments' => array(variable_get('node_cron_views_scale', 0)),
3301
      ),
3311
    );
3320
  }
3330
}
33429