summaryrefslogtreecommitdiff
path: root/modules/statistics/statistics.module
blob: 01a61dd72569929ea33fba85c4d55d24ff38a33b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
<?php
// $Id$

/**
 * 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 the day's top stories, the all time top stories, and the last stories read. Each section in the block has a title, which you can change, as well as being able to change how many node titles will be displayed</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>
      <li>A configurable block can be added that displays the count of how many users, as well as a list of their names, and guests are currently accessing your site.</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><a href=\"%referers\">referrers log</a></h3>
      <p>This admin page shows you site-wide referrer statistics.  You can see <em>'all'</em> statistics, <em>'external'</em> statistics or <em>'internal'</em> statistics.  Default is 'all'.</p>
      <h3><a href=\"%access\">access log</a></h3>
      <p>This admin page gives you an at-a-glance look at your most popular content.  It is useful for understanding what content on your Drupal site is the most popular.  Also on this page are links to the referrer statistics for each listed node.</p>
      <h3>Configuring the statistics module</h3>
      <p>There are some configuration options added to the main <a href=\"%configuration\">administer &raquo; configuration</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 theyve 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.  Additionally, a user group must have 'access statistics' permissions to view the 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>
      <h3>Popular content page</h3>
      <p>This module creates a user page that can display summaries of the day's most popular viewed content, the all time most popular content, and the last content viewed.  Each of these summaries can be enabled or disabled individually, and the number of posts displayed for each can be configured with a drop down menu.  You can also assign a name for the automatically generated link to the user page.  If no name is set, the link will not be displayed.</p>
      <h3>Permissions</h3><p>This module has four permissions that need to be configured in the <a href=\"%permissions\">permissions section</a>.</p>
      <ul>
      <li><em>access statistics</em> - enable for user roles that get to see view counts for individual content.  (This does not define access to the block)</li>
      <li><em>administer statistics module</em> - enable for user roles that get to configure the statistics module.</li><li><em>administer statistics</em> - enable for user roles that get to view the referrer statistics.</li>
      </ul>
      <p>If '<em>administer statistics</em>' and '<em>access statistics</em>' are both enabled, the user will see a link from each node to that node's referrer statistics (if enabled).</p>",
      array('%modules' => url('admin/system/modules'), '%permissions' => url('admin/user/permission'), '%referer' => url('admin/logs/referrer'), '%access' => url('admin/logs/access'), '%configuration' => url('admin/system/modules/statistics'), '%block' => url('admin/system/block')));
    case 'admin/system/modules#description':
      return t('Logs access statistics for your site.');
    case 'admin/system/modules/statistics':
      return 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/logs/topnodes')));
    case 'admin/logs/topnodes':
      return t('This page gives you an at-a-glance look at your most popular content.');
    case 'admin/logs/referrer':
      return t('This page shows your site-wide referrer statistics.  You can see "all referrers", "external referrers" or "internal referrers". Referrers are web pages, both local and on other sites, that point to your web site.');
    case 'admin/logs/referrer/internal':
      return t('This page shows you only "internal referrers". These are links pointing to your web site from within your web site.');
    case 'admin/logs/referrer/external':
      return t('This page shows you only "external referrers". These are links pointing to your web site from outside your web site.');
    case strstr($section, 'admin/logs/access'):
      return t("This page shows you who is accessing your web site.  You can see the hostnames and referrers.  In particular, it is easy to inspect a user's navigation history/trail by clicking on <em>track user</em>.");
  }
}

/**
 * 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) == 'view') && arg(2)) {
      // 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(2));
      // 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(2), time());
      }
    }
  }

  if ((variable_get('statistics_enable_access_log', 0)) && (module_invoke('throttle', 'status') < 5)) {
    // Statistical logs are enabled.
    $referrer = referer_uri();
    $hostname = $_SERVER['REMOTE_ADDR'];

    // Log this page access.
    if ((arg(0) == 'node') && (arg(1) == 'view') && arg(2)) {
      db_query("INSERT INTO {accesslog} (nid, url, hostname, uid, timestamp) values(%d, '%s', '%s', %d, %d)", arg(2), $referrer, $hostname, $user->uid, time());
    }
    else {
      db_query("INSERT INTO {accesslog} (url, hostname, uid, timestamp) values('%s', '%s', %d, %d)", $referrer, $hostname, $user->uid, time());
    }
  }
}

/**
 * Implementation of hook_perm().
 *
 * The following permissions are defined:
 * - "administer statistics module": full administrative control of module
 * - "administer statistics": view statistics / referrer log
 * - "access statistics": see how many times individual nodes have been
 *   viewed (if enabled)
 */
function statistics_perm() {
  return array('administer statistics module', 'administer statistics', 'access statistics');
}

/**
 * Implementation of hook_link().
 */
function statistics_link($type, $node = 0, $main = 0) {
  global $id;

  $links = array();

  if ($type == 'node' && user_access('access statistics') && variable_get('statistics_display_counter', 0)) {
    $statistics = statistics_get($node->nid);
    if ($statistics) {
      if (user_access('administer statistics')) {
        $links[] = l(format_plural($statistics['totalcount'], '1 read', '%count reads'), "admin/logs/access/node/$node->nid");
      }
      else {
        $links[] = format_plural($statistics['totalcount'], '1 read', '%count reads');
      }
    }
  }

  if ($type == 'page' && user_access('access content')) {
    $userlink = variable_get('statistics_userpage_link', '');
    if ($userlink) {
      $links[] = l(t($userlink), 'statistics', array('title' => t("View this site's most popular content.")));
    }
  }

  if ($type == 'system') {
    menu('statistics', t('most popular content'), user_access('access content') ? 'statistics_page' : MENU_DENIED, 0, MENU_HIDE);

    $access = user_access('administer statistics module') || user_access('administer statistics');

    menu('admin/logs/topnodes', t('top nodes'), $access ? 'statistics_admin_topnodes' : MENU_DENIED, 1);
    menu('admin/logs/referrer', t('referrer'), $access ? 'statistics_top_refer' : MENU_DENIED, 2);
    menu('admin/logs/referrer/internal', t('internal referrers only'), MENU_FALLTHROUGH);
    menu('admin/logs/referrer/external', t('external referrers only'), MENU_FALLTHROUGH);
    menu('admin/logs/access', t('access'), $access ? 'statistics_admin_displaylog' : MENU_DENIED, 3);
  }

  return $links;
}

function statistics_admin_topnodes_table() {

  $header = array(
    array('data' => t('title'), 'field' => 'n.title'),
    array('data' => t('today'), 'field' => 's.daycount', 'sort' => 'desc'),
    array('data' => t('all time'), 'field' => 's.totalcount'),
    array('data' => t('last hit'), 'field' => 's.timestamp'),
    array('data' => t('operations'))
  );
  $sql = 'SELECT s.nid, s.daycount, s.totalcount, s.timestamp, n.title FROM {node_counter} s INNER JOIN {node} n ON s.nid = n.nid';
  $sql .= tablesort_sql($header);
  $result = pager_query($sql, 20); // WHERE s.%s <> '0'

  while ($nid = db_fetch_array($result)) {
    $rows[] = array(l($nid['title'], 'node/view/'. $nid['nid'], array('title' => t('View this posting.'))), $nid['daycount'], $nid['totalcount'], format_date($nid['timestamp'], 'small'), l('track node', "admin/logs/access/node/$nid[nid]"));
  }
  if ($pager = theme('pager', NULL, 20, 0, tablesort_pager())) {
    $rows[] = array(array('data' => $pager, 'colspan' => 5));
  }

  return theme('table', $header, $rows);
}

function statistics_admin_accesslog_table($type, $id) {

  if ($type == 1) {
    /* retrieve user access logs */
    if ($id) {
      /* retrieve recent access logs for user $id */
      $sql = 'SELECT a.nid, a.url, a.hostname, a.uid, a.timestamp, n.title FROM {accesslog} a LEFT JOIN {node} n ON a.nid = n.nid WHERE a.uid = '. check_query($id);
    }
    else {
      /* retrieve recent access logs for all users */
      $sql = 'SELECT a.nid, a.url, a.hostname, a.uid, MAX(a.timestamp) AS timestamp, n.title FROM {accesslog} a LEFT JOIN {node} n ON a.nid = n.nid WHERE a.uid <> 0 GROUP BY a.uid, a.nid, a.url, a.hostname';
    }
  }
  else if ($type == 2) {
    /* retrieve recent access logs for node $id */
    $sql = 'SELECT a.nid, a.url, a.hostname, a.uid, a.timestamp, n.title FROM {accesslog} a INNER JOIN {node} n ON a.nid = n.nid WHERE a.nid = '. check_query($id);
  }
  else if ($type == 3) {
    /* retrieve recent access logs for hostname $id */
    $sql = "SELECT a.nid, a.url, a.hostname, a.uid, a.timestamp, n.title FROM {accesslog} a LEFT JOIN {node} n ON a.nid = n.nid WHERE a.hostname = '". check_query($id) ."'";
  }
  else {
    /* retrieve all recent access logs */
    $sql = 'SELECT a.nid, a.url, a.hostname, a.uid, a.timestamp, n.title FROM {accesslog} a LEFT JOIN {node} n ON a.nid = n.nid';
  }

  $header = array(
    array('data' => t('timestamp'), 'field' => 'timestamp', 'sort' => 'desc'),
    array('data' => t('post'), 'field' => 'nid'),
    array('data' => t('user'), 'field' => 'uid'),
    array('data' => t('hostname'), 'field' => 'hostname'),
    array('data' => t('referrer'), 'field' => 'url'),
    array('data' => t('operations'), 'colspan' => '3')
  );

  $sql .= tablesort_sql($header);

  $result = pager_query($sql, 50);
  while ($log = db_fetch_object($result)) {
    $user = user_load(array('uid' => $log->uid));

    if ($log->url) {
      $url = "<a href=\"$log->url\" title=\"$log->url\">". (strlen($log->url) > 28 ? substr($log->url, 0, 28) . '...' : $log->url) .'</a>';
    }
    else {
      $url = message_na();
    }

    $rows[] = array(array('data' => format_date($log->timestamp, 'small'), 'nowrap' => 'nowrap'), ($log->nid ? l($log->title, "node/view/$log->nid") : message_na()), format_name($user), $log->hostname ? $log->hostname : message_na(), $url, ($log->nid ? l(t('track node'), "admin/logs/access/node/$log->nid") : ''), ($user->uid ? l(t('track user'), "admin/logs/access/user/$user->uid") : ''), ($log->hostname ? l(t('track host'), "admin/logs/access/host/$log->hostname") : ''));
  }

  if ($pager = theme('pager', NULL, 50, 0, tablesort_pager())) {
    $rows[] = array(array('data' => $pager, 'colspan' => 8));
  }

  return theme('table', $header, $rows);
}

/**
 * Menu callback; presents the "Top referrers" page.
 *
 * @param $view
 *   - "internal": Only display internal links.
 *   - "external": Only display links from off-site.
 *   - "all": Display all referrers.
 */
function statistics_top_refer($view = 'all') {
  if ($view == 'all') {
    $query = "SELECT url, MAX(timestamp) AS last_view, COUNT(url) AS count FROM {accesslog} WHERE url <> '' GROUP BY url";
    $query_cnt = "SELECT COUNT(DISTINCT(url)) FROM {accesslog} WHERE url <> ''";
    $describe = t('Top referrers of the past %interval');
  }
  elseif ($view == 'internal') {
    $query = "SELECT url, MAX(timestamp) AS last_view, COUNT(url) AS count FROM {accesslog} WHERE url LIKE '%". check_query($_SERVER['HTTP_HOST']) ."%' GROUP BY url";
    $query_cnt = "SELECT COUNT(DISTINCT(url)) FROM {accesslog} WHERE url <> '' AND url LIKE '%". check_query($_SERVER['HTTP_HOST']) ."%'";
    $describe = t('Top internal referrers of the past %interval');
  }
  else {
    /* default to external */
    $query = "SELECT url, MAX(timestamp) AS last_view, COUNT(url) AS count FROM {accesslog} WHERE url NOT LIKE '%". check_query($_SERVER['HTTP_HOST']) ."%' AND url <> '' GROUP BY url";
    $query_cnt = "SELECT COUNT(DISTINCT(url)) FROM {accesslog} WHERE url <> '' AND url NOT LIKE '%". check_query($_SERVER['HTTP_HOST']) ."%'";
    $describe = t('Top external referrers of the past %interval');
  }

  $title = strtr($describe, array('%interval' => format_interval(variable_get('statistics_flush_accesslog_timer', 259200))));

  $header = array(
    array('data' => t('URL'), 'field' => 'url'),
    array('data' => t('last view'), 'field' => 'last_view'),
    array('data' => t('count'), 'field' => 'count', 'sort' => 'desc')
  );
  $query .= tablesort_sql($header);

  $result = pager_query($query, 50, 0, $query_cnt);

  while ($referrer = db_fetch_array($result)) {
    $rows[] = array('<a href="'. $referrer['url'] .'">'. substr($referrer['url'], 0, 100) .'</a>', format_date($referrer['last_view'], 'small'), $referrer['count']);
  }
  if ($pager = theme('pager', NULL, 50, 0, tablesort_pager())) {
    $rows[] = array(array('data' => $pager, 'colspan' => 3));
  }

  $output .= theme('table', $header, $rows);

  print theme('page', $output, $title);
}

/**
 * Menu callback; presents the "Most Popular Content" page.
 */
function statistics_admin_topnodes() {
  print theme('page', statistics_admin_topnodes_table());
}

/**
 * Menu callback; presents the "Access logs" page.
 *
 * @param $type
 *   - "user": display accesses for a particular user.
 *   - "host": display accesses originated at a given IP.
 *   - "node": display only accesses of a particular node.
 *   - "all": display all accesses.
 *
 * @param $value
 *   The user, host, or node to filter by.
 */
function statistics_admin_displaylog($type = 'all', $value = 0) {
  switch ($type) {
    case 'user':
      $user = user_load(array('uid' => $value));
      $title = t('Recent access logs for "%name"', array('%name' => $user->name));
      $output = statistics_admin_accesslog_table(1, $user->uid);
      break;
    case 'node':
      $node = node_load(array('nid' => $value));
      $title = t('Recent access logs for "%title"', array('%title' => $node->title));
      $output = statistics_admin_accesslog_table(2, $value);
      break;
    case 'host':
      $title = t('Recent access logs for "%hostname"', array('%hostname' => $value));
      $output = statistics_admin_accesslog_table(3, $value);
      break;
    default:
      $title = t('Recent access logs');
      $output = statistics_admin_accesslog_table(0, 0);
  }

  print theme('page', $output, $title);
}

/**
 * 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.  User must have the "access statistics" permissions to be able to view these counts.'));
  $output .= form_group(t('Content viewing counter settings'), $group);

  // 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));
  $group = 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.  Requires enabled content viewing counters.'));
  $group .= 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.  Requires enabled content viewing counters.'));
  $group .= 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.  Requires enabled content viewing counters.'));
  $output .= form_group(t('"Popular content" block settings'), $group);

  // Popular content page settings
  $numbers = array('0' => t('Disabled')) + drupal_map_assoc(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25));
  $group = form_textfield(t('Name for link to user page'), 'statistics_userpage_link', variable_get('statistics_userpage_link', ''), 20, 40, t("This node generates a user page listing your site's most popular content.  If you specify a name here, a link to the \"Popular content\" page will be added automatically."));
  $group .= form_select(t("Number of day's top views to display"), 'statistics_userpage_day_cnt', variable_get('statistics_userpage_day_cnt', 0), $numbers, t('How many content items to display in the "day" list.  Requires enabled content viewing counters.'));
  $group .= form_select(t('Number of all time top views to display'), 'statistics_userpage_all_cnt', variable_get('statistics_userpage_all_cnt', 0), $numbers, t('How many content items to display in the "all time" list.  Requires enabled content viewing counters.'));
  $group .= form_select(t('Number of most recent views to display'), 'statistics_userpage_last_cnt', variable_get('statistics_userpage_last_cnt', 0), $numbers, t('How many posts to display in the "recently viewed" list.  Requires enabled content viewing counters.'));
  $output .= form_group(t('"Popular content" page settings'), $group);

  return $output;
}

/**
 * Saves the values entered in the "config statistics" administration form.
 */
function statistics_save_statistics($edit) {
  variable_set('statistics_display_counter', $edit['statistics_display_counter']);
}

/**
 * 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 '. time() .' - timestamp > '. 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("SELECT s.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) {
  if ($op == 'list') {
    if (variable_get('statistics_count_content_views', 0)) {
      $blocks[0]['info'] = t('Popular content');
    }
    return $blocks;
  }
  else if (user_access('access content')) {
    switch ($delta) {
      case 0:
        $content = array();

        $daytop = variable_get('statistics_block_top_day_num', 0);
        if ($daytop) {
          $content[] = node_title_list(statistics_title_list('daycount', $daytop), t("Today's:"));
        }

        $alltimetop = variable_get('statistics_block_top_all_num', 0);
        if ($alltimetop) {
          $content[] = node_title_list(statistics_title_list('totalcount', $alltimetop), t('All time:'));
        }

        $lasttop = variable_get('statistics_block_top_last_num', 0);
        if ($lasttop) {
          $content[] = node_title_list(statistics_title_list('timestamp', $lasttop), t('Last viewed:'));
        }
        $output = implode($content, '<br />');

        $block['subject'] = variable_get('statistics_block_top_title', t('Popular content'));
        $block['content'] = $output;
        break;
    }

    return $block;
  }
}

/**
 * Menu callback; presents the "Top Nodes" summary page.
 */
function statistics_page() {
  $output = '';

  // build day's most popular content list if enabled
  if ($displaycount = variable_get('statistics_userpage_day_cnt', 0)) {
    $table = '<table border="0" cellpadding="4" cellspacing="4" style="width: 100%;">';
    $table .= statistics_summary('daycount', $displaycount);
    $table .= '</table>';

    $output .= theme('box', t("Day's most popular content:"), $table, 'main');
  }

  // build all time most popular content list if enabled
  if ($displaycount = variable_get('statistics_userpage_all_cnt', 0)) {
    $table = '<table border="0" cellpadding="4" cellspacing="4" style="width: 100%;">';
    $table .= statistics_summary('totalcount', $displaycount);
    $table .= '</table>';

    $output .= theme('box', t('All time most popular content:'), $table, 'main');
  }

  // build last viewed content list if enabled
  if ($displaycount = variable_get('statistics_userpage_last_cnt', 0)) {
    $table = '<table border="0" cellpadding="4" cellspacing="4" style="width: 100%;">';
    $table .= statistics_summary('timestamp', $displaycount);
    $table .= '</table>';

    $output .= theme('box', t('Last viewed content:'), $table, 'main');
  }

  print theme('page', $output);
}

function statistics_summary($dbfield, $dbrows) {
  /* valid dbfields: totalcount, daycount, timestamp */

  $output = '';
  $result = db_query_range('SELECT n.nid, n.title FROM {node_counter} s INNER JOIN {node} n ON s.nid = n.nid ORDER BY %s DESC', $dbfield, 0, $dbrows);
  while ($nid = db_fetch_array($result)) {
    $content = node_load(array('nid' => $nid['nid']));
    $links = link_node($content, 1);

    $output .= '<tr><td><strong>'. l($nid['title'], 'node/view/'. $nid['nid'], array('title' => t('View this posting.'))) .'</strong></td><td style="text-align: right;"><small>'. t('Submitted by %a on %b', array('%a' => format_name($content), '%b' => format_date($content->created, 'large'))) .'</small></td></tr>';
    $output .= '<tr><td colspan="2"><div style="margin-left: 20px;">'. check_output($content->teaser) .'</div></td></tr>';
    $output .= '<tr><td style="text-align: right;" colspan="2">[ '. theme('links', $links) .' ]<br /><br /></td></tr>';
  }

  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);
  }
}

?>