summaryrefslogtreecommitdiff
path: root/modules/statistics.module
blob: 997a81ee06324a25b96baa7a237d2bd2cf974e70 (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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
<?php
// $Id$

// Exit hook, runs at the end of every page request
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 updated 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()) {
        // must create a new row to store counter's for 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());
    }
  }
}

/* Permissions hook, defines module's permissions */
function statistics_perm() {
  /*
  ** statistics module defines the following permissions:
  **   administer statistics module - full administrative control of module
  **   administer statistics        - view statistics / referrer log
  **   access statistics            - see how many times individual content has
  **                                  been viewed (if enabled)
  */
  return array("administer statistics module", "administer statistics", "access statistics");
}


/* Link hook, defines module's links */
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/statistics/log/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") {
    if ((user_access("administer statistics module") || (user_access("administer statistics")))) {

      menu("admin/statistics", t("statistics"), "statistics_admin", 6);
      menu("admin/statistics/referrers", t("referrer log"), "statistics_admin");
      menu("admin/statistics/referrers/internal", t("internal referrers only"), "statistics_admin");
      menu("admin/statistics/referrers/external", t("external referrers only"), "statistics_admin");
      menu("admin/statistics/log", t("access log"), "statistics_admin");
      menu("admin/statistics/log/node", t("track node"), "statistics_admin", 0, MENU_HIDE);
      menu("admin/statistics/log/user", t("track user"), "statistics_admin", 0, MENU_HIDE);
      menu("admin/statistics/log/host", t("track host"), "statistics_admin", 0, MENU_HIDE);
      menu("admin/statistics/help", t("help"), "statistics_help_page", 9);
    }

    if (user_access("access content")) {
      menu("statistics", t("view most popular content"), "statistics_page", 0, MENU_HIDE);
    }
  }

  return $links;
}


function statistics_help($section = "admin/help#statistics") {
  $output = "";

  switch ($section) {
    case 'admin/help#statistics':
      $output .= 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 '<i>all</i>' statistics, '<i>external</i>' statistics or '<i>internal</i>' 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><i>enable access log</i> -- 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><i>discard access logs older than</i> -- 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><i>enable node view counter</i> -- 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><i>display node view counters</i> -- 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><i>access statistics</i> - enable for user roles that get to see view counts for individual content.  (This does not define access to the block)</li>
      <li><i>administer statistics module</i> - enable for user roles that get to configure the statistics module.</li><li><i>administer statistics</i> - enable for user roles that get to view the referrer statistics.</li>
      </ul>
      <p>If '<i>administer statistics</i>' and '<i>access statistics</i>' are both enabled, the user will see a link from each node to that node's referrer statistics (if enabled).</p>
      <h2>Statistics module (for developers)</h2><h3>Accessing statistics</h3><p>To get a node's \"view statistics\" make a call to the function <i>statistics_get(\$nid)</i>.  When you pass in a Node ID (\$nid), the function returns an array with three entires:  [0]=totalcount, [1]=daycount, [2]=timestamp.  For example, you could use this function call to add node view counts to your theme.</p>
      <ul>
      <li>The <i>totalcount</i> is a count of the total number of times that node has been viewed.</li>
      <li>The <i>daycount</i> is a count of the total number of times that node has been viewed \"today\".  For the daycount to be reset, cron must be enabled.</li>
      <li>The <i>timestamp</i> is a timestamp of when that node was last viewed.</li>
      </ul>
      <p>The module automatically adds '# reads' to each node's link section (if enabled).</p>
      <h3>Most popular content</h3>
      <p>The statistics module provides a function '<i>statistics_title_list(\$dbfield, \$dbrows)</i>' to return an array of links to any of the following: the top viewed content of all time, the top viewed content of today, and the last viewed content.  You can pass in:</p>
      <ul>
      <li><i>totalcount</i> - This will return an array with links to the top viewed content of all time.<br />Example:  <code>statistics_title_list(\"totalcount\", \"5\");</code><br /><br /></li>
      <li><i>daycount</i> - This will return an array with links to the top viewed content for today.<br />Example:  <code>statistics_title_list(\"daycount\",\"5\");</code><br /><br /></li>
      <li><i>timestamp</i> - This will return a array with links to the last viewed node.<br />Example:  <code>statistics_title_list(\"timestamp\",\"5\");</code></li>
      </ul>
      <p>\$dbrows is the number or rows you want returned in your array.</p>", array("%modules" => url("admin/system/modules"), "%permissions" => url("admin/user/permission"), "%referers" => url("admin/statistics/referrers"), "%access" => url("admin/statistics/log"), "%configuration" => url("admin/system/modules/statistics"), "%block" => url("admin/system/block")));
      break;
    case 'admin/system/modules#description':
      $output = t("Logs access statistics for your site.");
      break;
    case 'admin/system/modules/statistics':
      $output = 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/statistics")));
      break;
    case 'admin/statistics':
      $output = t("This page gives you an at-a-glance look at your most popular content.");
      break;
    case 'admin/statistics/referrers':
      $output = t("This page shows you site-wide referrer statistics.  You can see 'all referrers', 'external referrers' or 'internal referrers'. Referrers are web sites, both your site, and other peoples, that point to your web site.");
      break;
    case 'admin/statistics/referrers/internal':
      $output = t("This page shows you only 'internal referrers'. Links pointing to your web site, from within your web site.");
      break;
    case 'admin/statistics/referrers/external':
      $output = t("This page shows you only 'external referrers'. Links pointing to your web site from outside your web site.");
      break;
    case 'admin/statistics/log':
    case 'admin/statistics/log/node':
    case 'admin/statistics/log/user':
    case 'admin/statistics/log/host':
      $output = t("This pages shows you who is accessing your web site.  You can see the hostnames, referrers.  In particular, it is easy to inspect a user's navigation history/trail by clicking on <i>track user</i>.");
      break;
  }
  return $output;
}

function statistics_help_page() {
  print theme("page", statistics_help());
}


/* Administration hook, defines module's administrative page */
function statistics_admin() {
  $op = $_POST["op"];
  $edit = $_POST["edit"];

  if (empty($op)) {
    $op = arg(2);
  }

  /* non-configuration admin pages */
  switch ($op) {
    case "referrers":
      $output = statistics_top_refer();
      break;
    case "log":
      $output = statistics_admin_displaylog();
      break;
    default:
      $output = statistics_admin_topnodes();
  }

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


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/statistics/log/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/statistics/log/node/$log->nid") : ""), ($user->uid ? l(t("track user"), "admin/statistics/log/user/$user->uid") : ""), ($log->hostname ? l(t("track host"), "admin/statistics/log/host/$log->hostname") : ""));
  }

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

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

function statistics_top_refer() {

  $view = arg(3) ? arg(3) : "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 <> ''";
  }
  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");
  }

  $output = "<h3>". strtr($describe, array("%interval" => format_interval(variable_get("statistics_flush_accesslog_timer", 259200)))) ."</h3>";

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

  return $output;

}


function statistics_admin_topnodes() {

  $output = "<h3>". t("Popular content") ."</h3>\n";
  $output .= statistics_admin_topnodes_table();

  return $output;
}


function statistics_admin_displaylog() {

  $type = arg(3);
  $value = arg(4);

  switch ($type) {
    case "user":
      $user = user_load(array("uid" => $value));
      $output = "<h3>". t("Recent access logs for '%name'", array("%name" => $user->name)) ."</h3>\n";
      $output .= statistics_admin_accesslog_table(1, $user->uid);
      break;
    case "node":
      $node = node_load(array("nid" => $value));
      $output = "<h3>". t("Recent access logs for '%title'", array("%title" => $node->title)) ."</h3>\n";
      $output .= statistics_admin_accesslog_table(2, $value);
      break;
    case "host":
      $output = "<h3>". t("Recent access logs for '%hostname'", array("%hostname" => $value)) ."</h3>\n";
      $output .= statistics_admin_accesslog_table(3, $value);
      break;
    default:
      $output = "<h3>". t("Recent access logs") ."</h3>\n";
      $output .= statistics_admin_accesslog_table(0, 0);
  }

  return $output;
}


// settings for the statistics module
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_merge(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_merge(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"]);
}


/* cron hook, performs automatic functions */
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));
}


/* Display linked title based on field name */
function statistics_title_list($dbfield, $dbrows) {
  /* valid dbfields: totalcount, daycount, timestamp */
  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);
}


/* Function to retreive current page counter value. */
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;
}


/* Block hook */
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;
  }
}


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

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

?>