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

Line #Times calledCode
1
<?php
2
// $Id: statistics.module,v 1.286 2008/10/09 15:15:53 webchick 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.
54
      $fields = array(
555
        'daycount' => 1,
565
        'totalcount' => 1,
575
        'nid' => arg(1),
585
        'timestamp' => REQUEST_TIME,
595
      );
605
      db_merge('node_counter')
615
        ->fields($fields)
625
        ->expression('daycount', 'daycount + 1')
635
        ->expression('totalcount', 'totalcount + 1')
645
        ->execute();
655
    }
665
  }
6727
  if (variable_get('statistics_enable_access_log', 0)) {
68
    // Log this page access.
6914
    db_insert('accesslog')->fields(array(
7014
      'title' => strip_tags(drupal_get_title()),
7114
      'path' => $_GET['q'],
7214
      'url' => $_SERVER['HTTP_REFERER'],
7314
      'hostname' => ip_address(),
7414
      'uid' => $user->uid,
7514
      'sid' => session_id(),
7614
      'timer' => timer_read('page'),
7714
      'timestamp' => REQUEST_TIME,
7814
    ))->execute();
7914
  }
8027
}
81
82
/**
83
 * Implementation of hook_perm().
84
 */
8529
function statistics_perm() {
86
  return array(
87
    'access statistics' => array(
882
      'title' => t('Access statistics'),
892
      'description' => t('View content access statistics.'),
902
    ),
91
    'view post access counter' => array(
922
      'title' => t('View post access counter'),
932
      'description' => t('View the total number of times a piece of content
has been accessed.'),
942
    ),
952
  );
960
}
97
98
/**
99
 * Implementation of hook_link().
100
 */
10129
function statistics_link($type, $node = NULL, $teaser = FALSE) {
1029
  global $id;
1039
  $links = array();
104
1059
  if ($type != 'comment' && user_access('view post access counter')) {
1060
    $statistics = statistics_get($node->nid);
1070
    if ($statistics) {
1080
      $links['statistics_counter']['title'] =
format_plural($statistics['totalcount'], '1 read', '@count reads');
1090
    }
1100
  }
111
1129
  return $links;
1130
}
114
115
/**
116
 * Implementation of hook_menu().
117
 */
11829
function statistics_menu() {
1192
  $items['admin/reports/hits'] = array(
1202
    'title' => 'Recent hits',
1212
    'description' => 'View pages that have recently been visited.',
1222
    'page callback' => 'statistics_recent_hits',
1232
    'access arguments' => array('access statistics'),
124
  );
1252
  $items['admin/reports/pages'] = array(
1262
    'title' => 'Top pages',
1272
    'description' => 'View pages that have been hit frequently.',
1282
    'page callback' => 'statistics_top_pages',
1292
    'access arguments' => array('access statistics'),
1302
    'weight' => 1,
131
  );
1322
  $items['admin/reports/visitors'] = array(
1332
    'title' => 'Top visitors',
1342
    'description' => 'View visitors that hit many pages.',
1352
    'page callback' => 'statistics_top_visitors',
1362
    'access arguments' => array('access statistics'),
1372
    'weight' => 2,
138
  );
1392
  $items['admin/reports/referrers'] = array(
1402
    'title' => 'Top referrers',
1412
    'description' => 'View top referrers.',
1422
    'page callback' => 'statistics_top_referrers',
1432
    'access arguments' => array('access statistics'),
144
  );
1452
  $items['admin/reports/access/%'] = array(
1462
    'title' => 'Details',
1472
    'description' => 'View access log.',
1482
    'page callback' => 'statistics_access_log',
1492
    'page arguments' => array(3),
1502
    'access arguments' => array('access statistics'),
1512
    'type' => MENU_CALLBACK,
152
  );
1532
  $items['admin/reports/settings'] = array(
1542
    'title' => 'Access log settings',
1552
    'description' => 'Control details about what and how your site logs.',
1562
    'page callback' => 'drupal_get_form',
1572
    'page arguments' => array('statistics_access_logging_settings'),
1582
    'access arguments' => array('administer site configuration'),
1592
    'type' => MENU_NORMAL_ITEM,
1602
    'weight' => 3,
161
  );
1622
  $items['user/%user/track/navigation'] = array(
1632
    'title' => 'Track page visits',
1642
    'page callback' => 'statistics_user_tracker',
1652
    'access callback' => 'user_access',
1662
    'access arguments' => array('access statistics'),
1672
    'type' => MENU_LOCAL_TASK,
1682
    'weight' => 2,
169
  );
1702
  $items['node/%node/track'] = array(
1712
    'title' => 'Track',
1722
    'page callback' => 'statistics_node_tracker',
1732
    'access callback' => 'user_access',
1742
    'access arguments' => array('access statistics'),
1752
    'type' => MENU_LOCAL_TASK,
1762
    'weight' => 2,
177
  );
178
1792
  return $items;
1800
}
181
182
/**
183
 * Implementation of hook_user_delete().
184
 */
18529
function statistics_user_delete(&$edit, &$user, $category) {
1860
  db_query('UPDATE {accesslog} SET uid = 0 WHERE uid = %d', $user->uid);
1870
}
188
189
/**
190
 * Implementation of hook_cron().
191
 */
19229
function statistics_cron() {
1930
  $statistics_timestamp = variable_get('statistics_day_timestamp', '');
194
1950
  if ((REQUEST_TIME - $statistics_timestamp) >= 86400) {
196
    // Reset day counts.
1970
    db_query('UPDATE {node_counter} SET daycount = 0');
1980
    variable_set('statistics_day_timestamp', REQUEST_TIME);
1990
  }
200
201
  // Clean up expired access logs.
2020
  db_query('DELETE FROM {accesslog} WHERE timestamp < %d', REQUEST_TIME -
variable_get('statistics_flush_accesslog_timer', 259200));
2030
}
204
205
/**
206
 * Returns all time or today top or last viewed node(s).
207
 *
208
 * @param $dbfield
209
 *   one of
210
 *   - 'totalcount': top viewed content of all time.
211
 *   - 'daycount': top viewed content for today.
212
 *   - 'timestamp': last viewed node.
213
 *
214
 * @param $dbrows
215
 *   number of rows to be returned.
216
 *
217
 * @return
218
 *   A query result containing n.nid, n.title, u.uid, u.name of the
selected node(s)
219
 *   or FALSE if the query could not be executed correctly.
220
 */
22129
function statistics_title_list($dbfield, $dbrows) {
2220
  if (in_array($dbfield, array('totalcount', 'daycount', 'timestamp'))) {
2230
    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);
2240
  }
2250
  return FALSE;
2260
}
227
228
229
/**
230
 * Retrieves a node's "view statistics".
231
 *
232
 * @param $nid
233
 *   node ID
234
 *
235
 * @return
236
 *   An array with three entries: [0]=totalcount, [1]=daycount,
[2]=timestamp
237
 *   - totalcount: count of the total number of times that node has been
viewed.
238
 *   - daycount: count of the total number of times that node has been
viewed "today".
239
 *     For the daycount to be reset, cron must be enabled.
240
 *   - timestamp: timestamp of when that node was last viewed.
241
 */
24229
function statistics_get($nid) {
243
2440
  if ($nid > 0) {
245
    // Retrieve an array with both totalcount and daycount.
2460
    $statistics = db_fetch_array(db_query('SELECT totalcount, daycount,
timestamp FROM {node_counter} WHERE nid = %d', $nid));
2470
  }
248
2490
  return $statistics;
2500
}
251
252
/**
253
 * Implementation of hook_block().
254
 */
25529
function statistics_block($op = 'list', $delta = '', $edit = array()) {
256
  switch ($op) {
2570
    case 'list':
2580
      if (variable_get('statistics_count_content_views', 0)) {
2590
        $blocks['popular']['info'] = t('Popular content');
260
        // Too dynamic to cache.
2610
        $blocks['popular']['cache'] = BLOCK_NO_CACHE;
2620
        return $blocks;
2630
      }
2640
      break;
265
2660
    case 'configure':
267
      // Popular content block settings
2680
      $numbers = array('0' => t('Disabled')) + drupal_map_assoc(array(1, 2,
3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25, 30, 40));
2690
      $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.'));
2700
      $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.'));
2710
      $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.'));
2720
      return $form;
273
2740
    case 'save':
2750
      variable_set('statistics_block_top_day_num',
$edit['statistics_block_top_day_num']);
2760
      variable_set('statistics_block_top_all_num',
$edit['statistics_block_top_all_num']);
2770
      variable_set('statistics_block_top_last_num',
$edit['statistics_block_top_last_num']);
2780
      break;
279
2800
    case 'view':
2810
      if (user_access('access content')) {
2820
        $content = array();
283
2840
        $daytop = variable_get('statistics_block_top_day_num', 0);
2850
        if ($daytop && ($result = statistics_title_list('daycount',
$daytop)) && ($node_title_list = node_title_list($result, t("Today's:"))))
{
2860
          $content[] = $node_title_list;
2870
        }
288
2890
        $alltimetop = variable_get('statistics_block_top_all_num', 0);
2900
        if ($alltimetop && ($result = statistics_title_list('totalcount',
$alltimetop)) && ($node_title_list = node_title_list($result, t('All
time:')))) {
2910
          $content[] = $node_title_list;
2920
        }
293
2940
        $lasttop = variable_get('statistics_block_top_last_num', 0);
2950
        if ($lasttop && ($result = statistics_title_list('timestamp',
$lasttop)) && ($node_title_list = node_title_list($result, t('Last
viewed:')))) {
2960
          $content[] = $node_title_list;
2970
        }
298
2990
        if (count($content)) {
3000
          $block['content'] = implode('<br />', $content);
3010
          $block['subject'] = t('Popular content');
3020
          return $block;
3030
        }
3040
      }
3050
  }
3060
}
307
308
/**
309
 * It is possible to adjust the width of columns generated by the
310
 * statistics module.
311
 */
31229
function _statistics_link($path, $width = 35) {
3130
  $title = drupal_get_path_alias($path);
3140
  $title = truncate_utf8($title, $width, FALSE, TRUE);
3150
  return l($title, $path);
3160
}
317
31829
function _statistics_format_item($title, $path) {
3190
  $path = ($path ? $path : '/');
3200
  $output  = ($title ? "$title<br />" : '');
3210
  $output .= _statistics_link($path);
3220
  return $output;
3230
}
324
325
/**
326
 * Implementation of hook_nodeapi_delete().
327
 */
32829
function statistics_nodeapi_delete(&$node, $arg = 0) {
329
  // clean up statistics table when node is deleted
3300
  db_query('DELETE FROM {node_counter} WHERE nid = %d', $node->nid);
3310
}
332
333
/**
334
 * Implementation of hook_ranking().
335
 */
33629
function statistics_ranking() {
3371
  if (variable_get('statistics_count_content_views', 0)) {
338
    return array(
339
      'views' => array(
3401
        'title' => t('Number of views'),
3411
        'join' => 'LEFT JOIN {node_counter} node_counter ON
node_counter.nid = i.sid',
342
        // Inverse law that maps the highest view count on the site to 1
and 0 to 0.
3431
        'score' => '2.0 - 2.0 / (1.0 + node_counter.totalcount * %f)',
3441
        'arguments' => array(variable_get('node_cron_views_scale', 0)),
3451
      ),
3461
    );
3470
  }
3480
}
34929