statistics.module 29.2 KB
Newer Older
1 2 3
<?php
// $Id$

4
// Exit hook, runs at the end of every page request
5
function statistics_exit() {
Dries's avatar
Dries committed
6
  global $user, $recent_activity;
7

8 9
  if (variable_get("statistics_count_content_views", 0)) {
    // we are counting content views
10 11
    if ((arg(0) == "node") && (arg(1) == "view") && arg(2)) {
      // a node has been viewed, so updated the node's counters
12
      db_query("UPDATE {node_counter} SET daycount = daycount + 1, totalcount = totalcount + 1, timestamp = %d WHERE nid = %d", time(), arg(2));
13 14 15
      // 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
16
        db_query("INSERT INTO {node_counter} (nid, daycount, totalcount, timestamp) VALUES(%d, 1, 1, %d)", arg(2), time());
17 18 19 20
      }
    }
  }

21
  if ((variable_get("statistics_enable_access_log", 0)) && (module_invoke("throttle", "status") < 5)) {
22 23
    // statistical logs are enabled
    $referrer = referer_uri();
24 25
    $hostname = $_SERVER['REMOTE_ADDR'];

26 27
    // log this page access
    if ((arg(0) == "node") && (arg(1) == "view") && arg(2)) {
28
      db_query("INSERT INTO {accesslog} (nid, url, hostname, uid, timestamp) values(%d, '%s', '%s', %d, %d)", arg(2), $referrer, $hostname, $user->uid, time());
29 30
    }
    else {
31
      db_query("INSERT INTO {accesslog} (url, hostname, uid, timestamp) values('%s', '%s', %d, %d)", $referrer, $hostname, $user->uid, time());
32 33 34 35 36 37 38 39 40 41
    }
  }
}

/* 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
42 43
  **   access statistics            - see how many times individual content has
  **                                  been viewed (if enabled)
44
  */
45
  return array("administer statistics module", "administer statistics", "access statistics");
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
}


/* 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) {
70
      $links[] = l(t($userlink), "statistics", array("title" => t("View this site's most popular content.")));
71 72 73
    }
  }

74 75 76
  if ($type == "system") {
    if ((user_access("administer statistics module") || (user_access("administer statistics")))) {

77 78 79 80 81
      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");
82 83 84
      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);
Dries's avatar
Dries committed
85
      menu("admin/statistics/help", t("help"), "statistics_help_page", 9);
86
    }
Dries's avatar
Dries committed
87 88

    if (user_access("access content")) {
89
      menu("statistics", t("view most popular content"), "statistics_page", 0, MENU_HIDE);
Dries's avatar
Dries committed
90
    }
91
  }
92 93 94 95 96

  return $links;
}


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

  switch ($section) {
101
    case 'admin/help#statistics':
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
      $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>
119
      <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>
120 121 122 123 124
      <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>
125 126 127 128
      <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>
129 130 131 132 133 134 135 136
      </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>
137 138
      <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>
139
      </ul>
140 141
      <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>
      <h2>Statistics module (for developers)</h2><h3>Accessing statistics</h3><p>To get a node's \"view statistics\" make a call to the function <em>statistics_get(\$nid)</em>.  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>
142
      <ul>
143 144 145
      <li>The <em>totalcount</em> is a count of the total number of times that node has been viewed.</li>
      <li>The <em>daycount</em> 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 <em>timestamp</em> is a timestamp of when that node was last viewed.</li>
146 147 148
      </ul>
      <p>The module automatically adds '# reads' to each node's link section (if enabled).</p>
      <h3>Most popular content</h3>
149
      <p>The statistics module provides a function '<em>statistics_title_list(\$dbfield, \$dbrows)</em>' 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>
150
      <ul>
151 152 153
      <li><em>totalcount</em> - 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><em>daycount</em> - 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><em>timestamp</em> - This will return a array with links to the last viewed node.<br />Example:  <code>statistics_title_list(\"timestamp\",\"5\");</code></li>
154 155
      </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")));
156
      break;
157
    case 'admin/system/modules#description':
158
      $output = t("Logs access statistics for your site.");
159 160
      break;
    case 'admin/system/modules/statistics':
161
      $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")));
162 163
      break;
    case 'admin/statistics':
164
      $output = t("This page gives you an at-a-glance look at your most popular content.");
165 166
      break;
    case 'admin/statistics/referrers':
167
      $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.");
168 169
      break;
    case 'admin/statistics/referrers/internal':
170
      $output = t("This page shows you only 'internal referrers'. Links pointing to your web site, from within your web site.");
171 172
      break;
    case 'admin/statistics/referrers/external':
173
      $output = t("This page shows you only 'external referrers'. Links pointing to your web site from outside your web site.");
174 175 176 177 178
      break;
    case 'admin/statistics/log':
    case 'admin/statistics/log/node':
    case 'admin/statistics/log/user':
    case 'admin/statistics/log/host':
179
      $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 <em>track user</em>.");
180 181
      break;
  }
182
  return $output;
183 184
}

Dries's avatar
Dries committed
185
function statistics_help_page() {
186
  print theme("page", statistics_help());
Dries's avatar
Dries committed
187 188
}

189 190 191 192 193 194

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

195 196
  if (empty($op)) {
    $op = arg(2);
Dries's avatar
Dries committed
197
  }
198 199 200 201 202 203 204 205 206 207 208

  /* 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();
209
  }
210 211

  print theme("page", $output);
212 213 214
}


215
function statistics_admin_topnodes_table() {
216

217 218 219 220 221 222 223
  $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"))
  );
224
  $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";
225
  $sql .= tablesort_sql($header);
226
  $result = pager_query($sql, 20); // WHERE s.%s <> '0'
227 228 229 230

  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]"));
  }
Dries's avatar
Dries committed
231
  if ($pager = theme("pager", NULL, 20, 0, tablesort_pager())) {
232 233
    $rows[] = array(array("data" => $pager, "colspan" => 5));
  }
234

235
  return theme("table", $header, $rows);
236 237 238 239 240 241 242 243 244
}


function statistics_admin_accesslog_table($type, $id) {

  if ($type == 1) {
    /* retrieve user access logs */
    if ($id) {
      /* retrieve recent access logs for user $id */
245
      $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);
246 247 248
    }
    else {
      /* retrieve recent access logs for all users */
249
      $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";
250 251 252 253
    }
  }
  else if ($type == 2) {
    /* retrieve recent access logs for node $id */
254
    $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);
255 256 257
  }
  else if ($type == 3) {
    /* retrieve recent access logs for hostname $id */
258
    $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) ."'";
259 260 261
  }
  else {
    /* retrieve all recent access logs */
262
    $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";
263 264
  }

265
  $header = array(
266
    array("data" => t("timestamp"), "field" => "timestamp", "sort" => "desc"),
267 268 269 270 271 272 273 274
    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);
275

276
  $result = pager_query($sql, 50);
277 278 279 280
  while ($log = db_fetch_object($result)) {
    $user = user_load(array("uid" => $log->uid));

    if ($log->url) {
281
      $url = "<a href=\"$log->url\" title=\"$log->url\">". (strlen($log->url) > 28 ? truncate_utf8($log->url, 28) . '...' : $log->url) ."</a>";
282 283 284 285 286
    }
    else {
      $url = message_na();
    }

287
    $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") : ""));
288 289
  }

Dries's avatar
Dries committed
290
  if ($pager = theme("pager", NULL, 50, 0, tablesort_pager())) {
291 292 293
    $rows[] = array(array("data" => $pager, "colspan" => 8));
  }

294
  return theme("table", $header, $rows);
295 296 297 298
}

function statistics_top_refer() {

299
  $view = arg(3) ? arg(3) : "all";
300 301

  if ($view == "all") {
302 303
    $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 <> ''";
304 305
  }
  elseif ($view == "internal") {
306 307
    $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"]) ."%'";
308
    $describe = t("Top internal referrers of the past %interval");
309 310 311
  }
  else {
    /* default to external */
312 313
    $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"]) ."%'";
314
    $describe = t("Top external referrers of the past %interval");
315 316
  }

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

319
  $header = array(
320 321
    array("data" => t("URL"), "field" => "url"),
    array("data" => t("last view"), "field" => "last_view"),
322 323 324
    array("data" => t("count"), "field" => "count", "sort" => "desc")
  );
  $query .= tablesort_sql($header);
325

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

  while ($referrer = db_fetch_array($result)) {
329
    $rows[] = array("<a href=\"". $referrer["url"] ."\">". truncate_utf8($referrer["url"], 100) ."</a>", format_date($referrer["last_view"], "small"), $referrer["count"]);
330
  }
Dries's avatar
Dries committed
331
  if ($pager = theme("pager", NULL, 50, 0, tablesort_pager())) {
332
    $rows[] = array(array("data" => $pager, "colspan" => 3));
333 334
  }

335
  $output .= theme("table", $header, $rows);
336 337 338 339 340 341

  return $output;

}


342
function statistics_admin_topnodes() {
343

344
  $output = "<h3>". t("Popular content") ."</h3>\n";
345
  $output .= statistics_admin_topnodes_table();
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

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


380
// settings for the statistics module
381
function statistics_settings() {
382 383
  // 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."));
384 385

  $period = drupal_map_assoc(array(3600, 10800, 21600, 32400, 43200, 86400, 172800, 259200, 604800, 1209600, 2419200, 4838400, 9676800), "format_interval");
386 387
  $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);
388

389 390
  // 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."));
391
  $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."));
392
  $output .= form_group(t("Content viewing counter settings"), $group);
393

394
  // Popular content block settings
395
  $numbers = array("0" => t("Disabled")) + drupal_map_assoc(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25, 30, 40));
396 397 398
  $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."));
399
  $output .= form_group(t("\"Popular content\" block settings"), $group);
400

401
  // Popular content page settings
402
  $numbers = array("0" => t("Disabled")) + drupal_map_assoc(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25));
403
  $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."));
404 405 406
  $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."));
407
  $output .= form_group(t("\"Popular content\" page settings"), $group);
408

409
  return $output;
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
}


/* 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 */
425
    db_query("UPDATE {node_counter} SET daycount = '0'");
426 427 428 429
    variable_set("statistics_day_timestamp", time());
  }

  /* clean expired access logs */
430
  db_query("DELETE FROM {accesslog} WHERE ". time() ." - timestamp > ". variable_get("statistics_flush_accesslog_timer", 259200));
431 432 433 434 435 436
}


/* Display linked title based on field name */
function statistics_title_list($dbfield, $dbrows) {
  /* valid dbfields: totalcount, daycount, timestamp */
437
  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);
438 439 440 441 442 443 444 445
}


/* Function to retreive current page counter value. */
function statistics_get($nid) {

  if ($nid > 0) {
    /* retrieves an array with both totalcount and daycount */
446
    $statistics = db_fetch_array(db_query("SELECT totalcount, daycount, timestamp FROM {node_counter} WHERE nid = %d", $nid));
447 448 449 450 451 452 453 454 455
  }

  return $statistics;
}


/* Block hook */
function statistics_block($op = "list", $delta = 0) {
  if ($op == "list") {
456
    if (variable_get("statistics_count_content_views", 0)) {
457
      $blocks[0]["info"] = t("Popular content");
458 459 460
    }
    return $blocks;
  }
461
  else if (user_access("access content")) {
462
    switch ($delta) {
463
      case 0:
464 465
        $content = array();

466
        $daytop = variable_get("statistics_block_top_day_num", 0);
467
        if ($daytop) {
Dries's avatar
Dries committed
468
          $content[] = node_title_list(statistics_title_list("daycount", $daytop), t("Today's:"));
469 470
        }

471
        $alltimetop = variable_get("statistics_block_top_all_num", 0);
472
        if ($alltimetop) {
Dries's avatar
Dries committed
473
          $content[] = node_title_list(statistics_title_list("totalcount", $alltimetop), t("All time:"));
474 475
        }

476
        $lasttop = variable_get("statistics_block_top_last_num", 0);
477
        if ($lasttop) {
Dries's avatar
Dries committed
478
          $content[] = node_title_list(statistics_title_list("timestamp", $lasttop), t("Last viewed:"));
479 480 481
        }
        $output = implode($content, "<br />");

482
        $block["subject"] = variable_get("statistics_block_top_title", t("Popular content"));
483
        $block["content"] = $output;
484 485 486 487 488 489 490 491 492
        break;
    }

    return $block;
  }
}


function statistics_page() {
493
  $output = "";
494

495 496 497 498 499
  // 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>";
500

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

504 505 506 507 508
  // 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>";
509

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

513 514 515 516 517
  // 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>";
518

519
    $output .= theme("box", t("Last viewed content:"), $table, "main");
520
  }
521 522

  print theme("page", $output);
523 524 525 526 527 528 529
}


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

  $output = "";
530
  $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);
531 532 533 534
  while ($nid = db_fetch_array($result)) {
    $content = node_load(array("nid" => $nid["nid"]));
    $links = link_node($content, 1);

535
    $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>";
536 537 538 539 540 541 542 543 544 545 546
    $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
547
    db_query("DELETE FROM {node_counter} WHERE nid = %d", $node->nid);
548 549 550 551
  }
}

?>