statistics.module 51 KB
Newer Older
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
<?php
// $Id$

function statistics_init() {
  global $recent_activity;

  /*
  ** The following logic determines what the current throttle level should
  **  be, and can be disabled by the admin.  If enabled, the rand() function
  **  returns a number between 0 and N, N being specified by the admin. If
  **  0 is returned, the throttle logic is run, adding on additional database
  **  query.  Otherwise, the following logic is skipped.  This mechanism is
  **  referred to in the admin page as the 'probability limiter', roughly
  **  limiting throttle related database calls to 1 in N.
  */
  if ((variable_get("statistics_enable_auto_throttle", 0)) && (!rand(0, variable_get("statistics_probability_limiter", 9)))) {
    /*
    ** Note:  The rand() function is supported by PHP 3+.  However, prior to
    ** PHP 4.2.0 it needs to be seeded with a call to srand().  It is important
    ** that this only happens once, so this should be managed by the Drupal
    ** engine, not this module.  The Drupal engine should use phpversion() to
    ** detect and automatically seed pre-4.2.0 systems.
    */

    $throttle = throttle_status();
    // if we're at throttle level 5, we don't do anything
    if ($throttle < 5) {
      $multiplier = variable_get("statistics_throttle_multiplier", 60);
      // count all hits in past sixty seconds
Dries's avatar
   
Dries committed
30
      $result = db_query("SELECT COUNT(timestamp) AS hits FROM {accesslog} WHERE timestamp >= %d", (time() - 60));
31
32
33
34
35
36
      $recent_activity = db_fetch_array($result);
      throttle_update($recent_activity["hits"]);
    }
  }
}

Dries's avatar
   
Dries committed
37
// Exit hook, runs at the end of every page request
38
39
40
41
42
43
44
function statistics_exit() {
  global $user;

  if (variable_get("statistics_enable_node_counter", 0)) {
    // node view counters are enabled
    if ((arg(0) == "node") && (arg(1) == "view") && arg(2)) {
      // a node has been viewed, so updated the node's counters
Dries's avatar
   
Dries committed
45
      db_query("UPDATE {statistics} SET daycount = daycount + 1, totalcount = totalcount + 1, timestamp = %d WHERE nid = %d", time(), arg(2));
46
47
48
      // 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
Dries's avatar
   
Dries committed
49
        db_query("INSERT INTO {statistics} (nid, daycount, totalcount) VALUES(%d, 1, 1)", arg(2));
50
51
52
53
54
55
56
57
58
59
      }
    }
  }

  if ((variable_get("statistics_enable_access_log", 0)) && (throttle_status() < 5)) {
    // statistical logs are enabled
    $referrer = referer_uri();
    $hostname = getenv("REMOTE_ADDR");
    // log this page access
    if ((arg(0) == "node") && (arg(1) == "view") && arg(2)) {
Dries's avatar
   
Dries committed
60
      db_query("INSERT INTO {accesslog} (nid, url, hostname, uid, timestamp) values(%d, '%s', '%s', %d, %d)", arg(2), $referrer, $hostname, $user->uid, time());
61
62
    }
    else {
Dries's avatar
   
Dries committed
63
      db_query("INSERT INTO {accesslog} (url, hostname, uid, timestamp) values('%s', '%s', %d, %d)", $referrer, $hostname, $user->uid, time());
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
    }
  }
}

/* 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 counts per node (if enabled)
  **   access userlist              - see list of online users
  */
  return array("administer statistics module", "administer statistics", "access statistics", "access userlist");
}


/* 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 the top nodes for this site.")));
    }
  }

Dries's avatar
   
Dries committed
106
107
108
  if ($type == "system") {
    if ((user_access("administer statistics module") || (user_access("administer statistics")))) {

Dries's avatar
   
Dries committed
109
110
111
112
113
114
115
116
117
118
      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, 1); //hidden
      menu("admin/statistics/log/user", t("track user"), "statistics_admin", 0, 1); //hidden
      menu("admin/statistics/log/host", t("track host"), "statistics_admin", 0, 1); //hidden
      menu("admin/statistics/top nodes page", t("configure 'top nodes' page"), "statistics_admin", 5);
      menu("admin/statistics/help", t("help"), "statistics_help", 9);
Dries's avatar
   
Dries committed
119
120

      // block configuration:
Dries's avatar
   
Dries committed
121
122
      menu("admin/system/block/top nodes block", t("configure 'top nodes' block"), "statistics_admin", 5);
      menu("admin/system/block/whos online block", t("configure 'who is online' block"), "statistics_admin", 5);
Dries's avatar
   
Dries committed
123
    }
Dries's avatar
   
Dries committed
124
  }
125
126
127
128
129

  return $links;
}


Dries's avatar
   
Dries committed
130
function statistics_help($section = "admin/help#statistics") {
Dries's avatar
   
Dries committed
131
132
133
  $output = "";

  switch ($section) {
Dries's avatar
   
Dries committed
134
    case 'admin/help#statistics':
Dries's avatar
   
Dries committed
135
      $output .= "<h3>Introduction</h3>";
Dries's avatar
   
Dries committed
136
      $output .= "<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 <b>disabled</b> by default.<p>";
Dries's avatar
   
Dries committed
137
138
139
140
141
142
      $output .= "<p>The module counts how many times, and from where -- using HTTP referrer -- each of your nodes is viewed. Once we have that count the module can do the following with it:";
      $output .= "<ul>";
      $output .= "<li>The count can be displayed in the node's link section next to \"# comments\".</li>";
      $output .= "<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>";
      $output .= "<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.  Each section in the page has a title, which you can change, as well as being able to change the number of stories to be displayed.</li>";
      $output .= "<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>";
Dries's avatar
   
Dries committed
143
      $output .= "<li>An auto-throttle, congestion controling mechanism can be used on your site if you have enabled the %throttle.</li>";
Dries's avatar
   
Dries committed
144
145
146
147
148
149
      $output .= "</ul>";
      $output .= "<p>Notes on using the statistics:</p>";
      $output .= "<ul>";
      $output .= "<li>If you enable the node view counters, 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>";
      $output .= "<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>";
      $output .= "</ul>";
Dries's avatar
   
Dries committed
150
151
      $output .= "<p>As with any new module, the statistics module needs to be %modules before you can use it.  Also refer to the %permissions, as this module supports four separate permissions.</p>";
      $output .= "<h3>%referers</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>";
Dries's avatar
   
Dries committed
152
153
      $output .= "<h3>%access</h3><p>This admin page gives you an at-a-glance look at your top nodes.  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>";
      $output .= "<h3>Configuring the statistics module</h3><p>There are some configuration options added to the main %configuration section:</p>";
Dries's avatar
   
Dries committed
154
155
156
157
158
159
160
161
162
      $output .= "<ul>";
      $output .= "<li><i>enable access log</i> -- allows you to turn the access log on and off.  This log is used to store things like referrers and who's online.  Enabling the log adds one database call per page displayed by Drupal.</li>";
      $output .= "<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>";
      $output .= "<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>";
      $output .= "<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>";
      $output .= "</ul>";
      $output .= "<h3>Top nodes block</h3>";
      $output .= "<p>This module creates a block that can display the day's top viewed nodes, the all time top viewed nodes and the last nodes viewed.  Each of these links can be enabled or disabled individually, and the number of nodes displayed for each can be configured with a drop down menu.  If you disable all sections of this block, it will not appear.</p>";
      $output .= "<p>The administrative \"top nodes block\" screen also allows you to assign a name to the block.</p>";
Dries's avatar
   
Dries committed
163
      $output .= "<p>Don't forget to enable the block %here-block.</p>";
Dries's avatar
   
Dries committed
164
165
166
167
168

      $output .= "<h3>Top nodes page</h3>";
      $output .= "<p>This module creates a user page that can display summaries of the day's top viewed nodes, the all time top nodes and the last nodes viewed.  Each of these summaries can be enabled or disabled individually, and the number of nodes displayed for each can be configured with a drop down menu.</p>";
      $output .= "<p>The administrative \"top nodes page\" screen also allows you to assign a name for the automatically generated link to the user page.  If no name is set, the link will not be displayed.</p>";
      $output .= "<h3>Who's online block</h3><p>This module creates a block that can display how many user's and guests are currently online.  You are able to configure the name of the block, the name of a sub-block for displaying names of user's currently online, how recently a user must have been active to be considered online, the maximum characters to display from a user's name and the maximum number of user names to display.</p>";
Dries's avatar
   
Dries committed
169
170
      $output .= "<p>Don't forget to enable the block %here-block.</p>";
      $output .= "<h3>Permissions</h3><p>This module has four permissions that need to be configured in %permissions.</p>";
Dries's avatar
   
Dries committed
171
172
173
174
175
176
177
178
179
180
181
182
183
      $output .= "<ul>";
      $output .= "<li><i>access statistics</i> - enable for user roles that get to see individual node counts.  (This does not define access to the block)</li>";
      $output .= "<li><i>access userlist</i> - enable for user roles that get to see the list of user's that are currently online within the \"Who's online\" block.</li>";
      $output .= "<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>";
      $output .= "</ul>";
      $output .= "<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>";
      $output .= "<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>";
      $output .= "<ul>";
      $output .= "<li>The <i>totalcount</i> is a count of the total number of times that node has been viewed.</li>";
      $output .= "<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>";
      $output .= "<li>The <i>timestamp</i> is a timestamp of when that node was last viewed.</li>";
      $output .= "</ul>";
      $output .= "<p>The module automatically adds '# reads' to each node's link section (if enabled).</p>";
Dries's avatar
   
Dries committed
184
      $output .= "<h3>Top stories</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 nodes of all time, the top viewed nodes of today, the last viewed nodes.  You can pass in:</p>";
Dries's avatar
   
Dries committed
185
186
187
188
189
190
191
192
      $output .= "<ul>";
      $output .= "<li><i>totalcount</i> - This will return an array with links to the top viewed nodes of all time.<br />Example:  <code>statistics_title_list(\"totalcount\", \"5\");</code><br /><br /></li>";
      $output .= "<li><i>daycount</i> - This will return an array with links to the top viewed nodes for today.<br />Example:  <code>statistics_title_list(\"daycount\",\"5\");</code><br /><br /></li>";
      $output .= "<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>";
      $output .= "</ul>";
      $output .= "<p>\$dbrows is the number or rows you want returned in your array.</p>";
      $output .= "<h3>Throttle</h3><p>The function <code>throttle_status()</code> will return a number from 0 to 5.  0 means that there is no throttle enabled at this time.  Each number above that is a progressively more throttled system...  To disable a feature when a site first begins to get busy, disable it at a throttle of 2 or 3.  To hold on to the bitter end, wait until 4 or 5.</p>";
      $output .= "<p>To implement the throttle, you should do something like this:<pre>       \$throttle = 0;
193
194
195
196
197
198
199
200
201
202
       /* verify that the statitistics module is installed */
       if (function_exists(throttle_status) {
         \$throttle = throttle_status()
       }
       if (\$throttle >= \$my_throttle_value) {
         // throttle limit reached, disable stuff
       }
       else {
         // throttle limit not reached, execute normally
       }</pre></p>";
Dries's avatar
   
Dries committed
203
204
      $output .= "<p>Note: Even though the configuration for the throttle is handled by the throttle module, the throttle logic itself is part of the statistics module.  The configuration has been separated in order to make things easier for the average site that will not be utilizing the throttling mechanism.  More information about how the throttle works can be found on the throttle module help page.  (Find the throttle help page %here-help if you have enabled the throttle module).</p>";
      $output = t($output, array("%throttle" => l(t("throttle module"), "admin/system/modules"), "%modules" => l(t("enabled"), "admin/system/modules"), "%permissions" => l(t("permissions section"), "admin/user/permission"), "%referers" => l(t("referrers log"), "admin/statistics/referrers"), "%access" => l(t("access log"), "admin/statistics/log"), "%configuration" => l(t("administer") ." &raquo; ". t("configuration"), "admin/system/modules/statistics"), "%here-block" => l(t("here"), "admin/system/block"), "%here-help" => l(t("here"), "admin/help#throttle")));
Dries's avatar
   
Dries committed
205
      break;
Dries's avatar
   
Dries committed
206
    case 'admin/system/modules#description':
Dries's avatar
   
Dries committed
207
      $output = t("Logs access statistics for your site.");
Dries's avatar
   
Dries committed
208
209
      break;
    case 'admin/system/modules/statistics':
Dries's avatar
   
Dries committed
210
      $output = t("Settings for the statistical information that Drupal will keep about the site. See %statistics for the actual information.", array("%statistics" => l(t("site statistics"), "admin/statistics")));
Dries's avatar
   
Dries committed
211
212
      break;
    case 'admin/statistics':
Dries's avatar
   
Dries committed
213
      $output = t("This page gives you an at-a-glance look at your top nodes.  It is useful for understanding what content on your site is the most popular.");
Dries's avatar
   
Dries committed
214
215
      break;
    case 'admin/statistics/referrers':
Dries's avatar
   
Dries committed
216
      $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.");
Dries's avatar
   
Dries committed
217
218
      break;
    case 'admin/statistics/referrers/internal':
Dries's avatar
   
Dries committed
219
      $output = t("This page shows you only 'internal referrers'. Links pointing to your web site, from within your web site.");
Dries's avatar
   
Dries committed
220
221
      break;
    case 'admin/statistics/referrers/external':
Dries's avatar
   
Dries committed
222
      $output = t("This page shows you only 'external referrers'. Links pointing to your web site from outside your web site.");
Dries's avatar
   
Dries committed
223
224
225
226
227
      break;
    case 'admin/statistics/log':
    case 'admin/statistics/log/node':
    case 'admin/statistics/log/user':
    case 'admin/statistics/log/host':
Dries's avatar
   
Dries committed
228
      $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>.");
Dries's avatar
   
Dries committed
229
230
      break;
    case 'admin/statistics/top nodes page':
Dries's avatar
   
Dries committed
231
      $output = t("The statistics module creates a user page that can display summaries of the day's top viewed nodes, the all time top nodes and the last nodes viewed.  Each of these summaries can be enabled or disabled individually, and the number of nodes displayed for each can be configured with a drop down menu.");
Dries's avatar
   
Dries committed
232
      break;
Dries's avatar
   
Dries committed
233
    case 'admin/system/block/top nodes block':
Dries's avatar
   
Dries committed
234
      $output = t("The statistics module exports a block that can display the top viewed nodes of the day, the all time top viewed nodes and the last nodes viewed.  Each of these links can be enabled or disabled individually, and the number of nodes displayed for each can be configured with a drop down menu. If you disable all sections of this block, it will not appear.");
Dries's avatar
   
Dries committed
235
      break;
Dries's avatar
   
Dries committed
236
    case 'admin/system/block/whos online block':
Dries's avatar
   
Dries committed
237
      $output = t("The statistics module exports a block that can display how many user's and guests are currently online.  You can configure the name of the block, the name of a sub-block for displaying names of user's currently online, how recently a user must have been active to be considered online, the maximum characters to display from a user's name and the maximum number of user names to display.");
Dries's avatar
   
Dries committed
238
239
      break;
  }
Dries's avatar
   
Dries committed
240
  return $output;
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
}


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

  /* Only allow people with sufficient access. */
  if ((user_access("administer statistics module")) || (user_access("administer statistics"))) {

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

    /* non-configuration admin pages */
    switch ($op) {
      case "statistics":
Dries's avatar
   
Dries committed
259
        return statistics_admin_topnodes();
260
      case "referrers":
Dries's avatar
   
Dries committed
261
        return statistics_top_refer();
262
      case "log":
Dries's avatar
   
Dries committed
263
        return statistics_admin_displaylog();
264
265
266
267
268
    }

    /* configuration admin pages */
    if (user_access("administer statistics module")) {
      switch (stripslashes($op)) {
Dries's avatar
   
Dries committed
269
        case t("Submit \"top nodes\" block changes"):
270
          statistics_save_topnodes_block($edit);
Dries's avatar
   
Dries committed
271
          $output .= status(t("saved 'top nodes' block changes."));
Dries's avatar
   
Dries committed
272
        case t("Submit \"who's online\" block changes"):
273
          statistics_save_online_block($edit);
Dries's avatar
   
Dries committed
274
          $output .= status(t("saved 'who's online' block changes."));
Dries's avatar
   
Dries committed
275
        case t("Submit \"top nodes\" page changes"):
276
          statistics_save_userconfig($edit);
Dries's avatar
   
Dries committed
277
          $output .= status(t("saved 'top nodes' page changes."));
278
        case "top nodes page":
Dries's avatar
   
Dries committed
279
          $output .= statistics_admin_userpage_config(array(
280
281
282
283
284
285
286
287
            "statistics_userpage_link" => variable_get("statistics_userpage_link", ""),
            "statistics_userpage_day_head" => variable_get("statistics_userpage_day_head", "Todays top"),
            "statistics_userpage_day_cnt" => variable_get("statistics_userpage_day_cnt", 0),
            "statistics_userpage_all_head" => variable_get("statistics_userpage_all_head", "All time top"),
            "statistics_userpage_all_cnt" => variable_get("statistics_userpage_all_cnt", 0),
            "statistics_userpage_last_head" => variable_get("statistics_userpage_last_head", "Last read"),
            "statistics_userpage_last_cnt" => variable_get("statistics_userpage_last_cnt", 0)
          ));
Dries's avatar
   
Dries committed
288
          break;
Dries's avatar
   
Dries committed
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
        case "block":
          if (arg(3) == "top nodes block") {
              $output .= statistics_config_topnodes_block(array(
                "statistics_block_top_title" => variable_get("statistics_block_top_title", "Top nodes"),
                "statistics_block_top_day_head" => variable_get("statistics_block_top_day_head", "<b>Todays top:</b>"),
                "statistics_block_top_day_num" => variable_get("statistics_block_top_day_num", 0),
                "statistics_block_top_all_head" => variable_get("statistics_block_top_all_head", "<b>All time top:</b>"),
                "statistics_block_top_all_num" => variable_get("statistics_block_top_all_num", 0),
                "statistics_block_top_last_head" => variable_get("statistics_block_top_last_head" ,"<b>Last:</b>"),
                "statistics_block_top_last_num" => variable_get("statistics_block_top_last_num", 0)
              ));
           }
           elseif (arg(3) == "whos online block") {
              $output .= statistics_config_online_block(array(
                "statistics_block_online_title" => variable_get("statistics_block_online_title", "Who's online"),
                "statistics_block_online_subtitle" => variable_get("statistics_block_online_subtitle", "Online users:"),
                "statistics_block_online_time" => variable_get("statistics_block_online_time", 2700),
                "statistics_block_online_max_len" => variable_get("statistics_block_online_max_len", 15),
                "statistics_block_online_max_cnt" => variable_get("statistics_block_online_max_cnt", 10)
              ));
              break;
           }
311
        default:
Dries's avatar
   
Dries committed
312
          $output .= statistics_admin_topnodes();
313
314
      }
    }
Dries's avatar
   
Dries committed
315
    return $output;
316
317
318
319
  }
}


Dries's avatar
   
Dries committed
320
function statistics_admin_topnodes_table() {
321

Dries's avatar
   
Dries committed
322
323
324
325
326
327
328
329
330
  $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 {statistics} s INNER JOIN {node} n USING (nid)";
  $sql .= tablesort_sql($header);
Dries's avatar
   
Dries committed
331
  $result = pager_query($sql, 20); // WHERE s.%s <> '0'
332
333
334
335

  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
336
  if ($pager = pager_display(NULL, 20, 0, "admin", tablesort_pager())) {
Dries's avatar
   
Dries committed
337
338
    $rows[] = array(array("data" => $pager, "colspan" => 5));
  }
339
340
341
342
343
344
345
346
347
348
349

  return 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 */
Dries's avatar
   
Dries committed
350
      $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);
351
352
353
    }
    else {
      /* retrieve recent access logs for all users */
Dries's avatar
   
Dries committed
354
      $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";
355
356
357
358
    }
  }
  else if ($type == 2) {
    /* retrieve recent access logs for node $id */
Dries's avatar
   
Dries committed
359
    $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.nid = ". check_query($id);
360
361
362
  }
  else if ($type == 3) {
    /* retrieve recent access logs for hostname $id */
Dries's avatar
   
Dries committed
363
    $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) ."'";
364
365
366
  }
  else {
    /* retrieve all recent access logs */
Dries's avatar
   
Dries committed
367
    $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";
368
369
  }

Dries's avatar
   
Dries committed
370
  $header = array(
Dries's avatar
   
Dries committed
371
    array("data" => t("timestamp"), "field" => "timestamp", "sort" => "desc"),
Dries's avatar
   
Dries committed
372
373
374
375
376
377
378
379
    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);
Dries's avatar
   
Dries committed
380

Dries's avatar
   
Dries committed
381
  $result = pager_query($sql, 50);
382
383
384
385
386
387
388
389
390
391
  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();
    }

Dries's avatar
   
Dries committed
392
    $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") : ""));
393
394
  }

Dries's avatar
   
Dries committed
395
  if ($pager = pager_display(NULL, 50, 0, "admin", tablesort_pager())) {
396
397
398
399
400
401
402
403
    $rows[] = array(array("data" => $pager, "colspan" => 8));
  }

  return table($header, $rows);
}

function statistics_top_refer() {

Dries's avatar
   
Dries committed
404
  $view = arg(3) ? arg(3) : "all";
405
406

  if ($view == "all") {
Dries's avatar
   
Dries committed
407
408
    $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 <> ''";
409
410
  }
  elseif ($view == "internal") {
Dries's avatar
   
Dries committed
411
412
    $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"]) ."%'";
413
414
415
416
    $describe = "internal ";
  }
  else {
    /* default to external */
Dries's avatar
   
Dries committed
417
418
    $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"]) ."%'";
419
420
421
422
423
    $describe = "external ";
  }

  $output = "<h3>". t("Top $describe referrers of the past %interval", array("%interval" => format_interval(variable_get("statistics_flush_accesslog_timer", 259200)))) ."</h3>";

Dries's avatar
   
Dries committed
424
  $header = array(
Dries's avatar
   
Dries committed
425
426
    array("data" => t("URL"), "field" => "url"),
    array("data" => t("last view"), "field" => "last_view"),
Dries's avatar
   
Dries committed
427
428
429
    array("data" => t("count"), "field" => "count", "sort" => "desc")
  );
  $query .= tablesort_sql($header);
Dries's avatar
   
Dries committed
430

Dries's avatar
   
Dries committed
431
  $result = pager_query($query, 50, 0, $query_cnt);
432
433

  while ($referrer = db_fetch_array($result)) {
Dries's avatar
   
Dries committed
434
435
436
437
    $rows[] = array("<a href=\"". $referrer["url"] ."\">". substr($referrer["url"], 0, 100) ."</a>", format_date($referrer["last_view"], "small"), $referrer["count"]);
  }
  if ($pager = pager_display(NULL, 50, 0, "admin", tablesort_pager())) {
    $rows[] = array(array("data" => $pager, "colspan" => 3));
438
439
440
441
442
443
444
445
446
  }

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

  return $output;

}


Dries's avatar
   
Dries committed
447
function statistics_admin_topnodes() {
448

Dries's avatar
   
Dries committed
449
450
  $output = "<h3>". t("Top nodes") ."</h3>\n";
  $output .= statistics_admin_topnodes_table();
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

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


/* Displays the block configuration administration form */
function statistics_config_topnodes_block($edit) {

  $form = form_textfield(t("Block name"), "statistics_block_top_title", $edit["statistics_block_top_title"], 20, 40, t("This module generates a block with top nodes.  You may assign a name for this block."));

  $form .= "<hr />";

  $form .= form_textfield(t("Today's top nodes title"), "statistics_block_top_day_head", $edit["statistics_block_top_day_head"], 20, 40, t("Specify a name for the \"day's top\" section of the block generated by this module.  HTML tags permitted."));
  $form .= form_select(t("Number of day's top views to display"), "statistics_block_top_day_num", $edit["statistics_block_top_day_num"], array("0" => t("Disabled"), "1" => "1", "2" => "2", "3" => "3", "4" => "4", "5" => "5", "6" => "6", "7" => "7", "8" => "8", "9" => "9", "10" => "10", "15" => "15", "20" => "20", "25" => "25", "30" => "30", "40" => "40"), t("Set how many \"today's top\" nodes to display on the block generated by this module."));

  $form .= "<hr />";

  $form .= form_textfield(t("All time top nodes title"), "statistics_block_top_all_head", $edit["statistics_block_top_all_head"], 20, 40, t("Specify a name for the \"all time top\" section of the block generated by this module.  HTML tags permitted."));
  $form .= form_select(t("Number of all time views to display"), "statistics_block_top_all_num", $edit["statistics_block_top_all_num"], array("0" => t("Disabled"), "1" => "1", "2" => "2", "3" => "3", "4" => "4", "5" => "5", "6" => "6", "7" => "7", "8" => "8", "9" => "9", "10" => "10", "15" => "15", "20" => "20", "25" => "25", "30" => "30", "40" => "40"), t("Set how many \"all time top\" nodes to display on the block generated by this module."));

  $form .= "<hr />";

  $form .= form_textfield(t("Most recent views heading"), "statistics_block_top_last_head", $edit["statistics_block_top_last_head"], 20, 40, t("Specify a name for the \"last views\" section of the block generated by this module.  HTML tags permitted."));
  $form .= form_select(t("Number of most recent views to display"), "statistics_block_top_last_num", $edit["statistics_block_top_last_num"], array("0" => t("Disabled"), "1" => "1", "2" => "2", "3" => "3", "4" => "4", "5" => "5", "6" => "6", "7" => "7", "8" => "8", "9" => "9", "10" => "10", "15" => "15", "20" => "20", "25" => "25", "30" => "30", "40" => "40"), t("Set how many \"last viewed\" nodes to display on the block generated by this module."));

  $form .= "<hr />";

Dries's avatar
   
Dries committed
507
  $form .= form_submit(t("Submit \"top nodes\" block changes"));
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523

  return form($form);
}


/* Displays the block configuration administration form */
function statistics_config_online_block($edit) {

  $form = form_textfield(t("Block name"), "statistics_block_online_title", $edit["statistics_block_online_title"], 20, 40, t("This module generates a block displaying how many users/guests are online.  You may assign a name for this block."));
  $form .= form_textfield(t("Sub-block name"), "statistics_block_online_subtitle", $edit["statistics_block_online_subtitle"], 20, 40, t("This module generates a sub-block listing the names of currently online users.  You may assign a name for this block."));

  $period = array(30 => format_interval(30), 60 => format_interval(60), 120 => format_interval(120), 180 => format_interval(180), 300 => format_interval(300), 600 => format_interval(600), 900 => format_interval(900), 1800 => format_interval(1800), 2700 => format_interval(2700), 3600 => format_interval(3600), 5400 => format_interval(5400), 7200 => format_interval(7200), 10800 => format_interval(10800), 21600 => format_interval(21600), 43200 => format_interval(43200), 86400 => format_interval(86400));
  $form .= form_select(t("Activity threshold"), "statistics_block_online_time", $edit["statistics_block_online_time"], $period, "How long ago a user (or guest) must have been active to be considered online.");
  $form .= form_select(t("Maximum characters of user's name to display"), "statistics_block_online_max_len", $edit["statistics_block_online_max_len"], array("1" => "1", "5" => "5", "10" => "10", "15" => "15", "20" => "20", "25" => "25", "30" => "30", "35" => "35", "40" => "40", "45" => "45", "50" => "50", "55" => "55", "60" => "60"), t("What is the maximum characters of a user's name to to display in the sub-block."));
  $form .= form_select(t("How many online users to list"), "statistics_block_online_max_cnt", $edit["statistics_block_online_max_cnt"], array("0" => "0", "1" => "1", "2" => "2", "3" => "3", "4" => "4", "5" => "5", "6" => "6", "7" => "7", "8" => "8", "9" => "9", "10" => "10", "15" => "15", "20" => "20", "50" => "50", "100" => "100"), t("How many online user's names to display in the sub-block."));

Dries's avatar
   
Dries committed
524
  $form .= form_submit(t("Submit \"who's online\" block changes"));
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539

  return form($form);
}


/* Displays the user page configuration administration form */
function statistics_admin_userpage_config($edit) {

  $form = form_textfield(t("Name for link to user page"), "statistics_userpage_link", $edit["statistics_userpage_link"], 20, 40, t("This node generates a user page with top nodes.  If you wish a link added automatically, specify a name."));
  $form .= "<hr />";

  $form .= form_textfield(t("Today's top nodes title"), "statistics_userpage_day_head", $edit["statistics_userpage_day_head"], 20, 40, t("Specify a name for the \"day's top\" section of the user page generated by this module."));
  $form .= form_select(t("Number of nodes to display for \"day's top\""), "statistics_userpage_day_cnt", $edit["statistics_userpage_day_cnt"], array("0" => t("Disabled"), "1" => "1", "2" => "2", "3" => "3", "4" => "4", "5" => "5", "6" => "6", "7" => "7", "8" => "8", "9" => "9", "10" => "10", "15" => "15", "20" => "20", "25" => "25"), t("Set how many \"day's top\" nodes to display on the user page generated by this module."));
  $form .= "<hr />";

Dries's avatar
   
Dries committed
540
  $form .= form_textfield(t("All time top nodes title"), "statistics_userpage_all_head", $edit["statistics_userpage_all_head"], 20, 40, t("Specify a name for the \"all time top\" section of the user page generated by this module."));
541
542
543
  $form .= form_select(t("Number of nodes to display for \"all time\""), "statistics_userpage_all_cnt", $edit["statistics_userpage_all_cnt"], array("0" => t("Disabled"), "1" => "1", "2" => "2", "3" => "3", "4" => "4", "5" => "5", "6" => "6", "7" => "7", "8" => "8", "9" => "9", "10" => "10", "15" => "15", "20" => "20", "25" => "25"), t("Set how many \"all time top\" nodes to display on the user page generated by this module."));
  $form .= "<hr />";

Dries's avatar
   
Dries committed
544
  $form .= form_textfield(t("Last viewed nodes title"), "statistics_userpage_last_head", $edit["statistics_userpage_last_head"], 20, 40, t("Specify a name for the \"last viewed\" section of the user page generated by this module."));
545
546
547
  $form .= form_select(t("Number of nodes to display for \"last views\""), "statistics_userpage_last_cnt", $edit["statistics_userpage_last_cnt"], array("0" => t("Disabled"), "1" => "1", "2" => "2", "3" => "3", "4" => "4", "5" => "5", "6" => "6", "7" => "7", "8" => "8", "9" => "9", "10" => "10", "15" => "15", "20" => "20", "25" => "25"), t("Set how many \"last viewed\" nodes to display on the user page generated by this module."));
  $form .= "<hr />";

Dries's avatar
   
Dries committed
548
  $form .= form_submit(t("Submit \"top nodes\" page changes"));
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613

  return form($form);
}


/* Adds configure option to the main configure site admin page */
function statistics_settings() {
  /* access log options */
  $output = form_select(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 = array(3600 => format_interval(3600), 10800 => format_interval(10800), 21600 => format_interval(21600), 32400 => format_interval(32400), 43200 => format_interval(43200), 86400 => format_interval(86400), 172800 => format_interval(172800), 259200 => format_interval(259200), 604800 => format_interval(604800), 1209600 => format_interval(1209600), 2419200 => format_interval(2419200), 4838400 => format_interval(4838400), 9676800 => format_interval(9676800));
  $output .= 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_select(t("Enable node view counters"), "statistics_enable_node_counter", variable_get("statistics_enable_node_counter", 0), array("1" => t("Enabled"), "0" => t("Disabled")), t("Increment node view counter each time a node is viewed."));
  $output .= form_select(t("Display node view counters"), "statistics_display_counter", variable_get("statistics_display_counter", ""), array("1" => t("Enabled"), "0" => t("Disabled")), t("Display how many times each node has been viewed.  User must have the 'access statistics' permissions."));

  return $output;
}


/* Saves the values entered in the "blockconfig" administration form */
function statistics_save_topnodes_block($edit) {
  variable_set("statistics_block_top_title", $edit["statistics_block_top_title"]);
  variable_set("statistics_block_top_day_head", $edit["statistics_block_top_day_head"]);
  variable_set("statistics_block_top_day_num", $edit["statistics_block_top_day_num"]);
  variable_set("statistics_block_top_all_head", $edit["statistics_block_top_all_head"]);
  variable_set("statistics_block_top_all_num", $edit["statistics_block_top_all_num"]);
  variable_set("statistics_block_top_last_head", $edit["statistics_block_top_last_head"]);
  variable_set("statistics_block_top_last_num", $edit["statistics_block_top_last_num"]);
}


/* Saves the values entered in the "blockconfig" administration form */
function statistics_save_online_block($edit) {
  variable_set("statistics_block_online_title", $edit["statistics_block_online_title"]);
  variable_set("statistics_block_online_subtitle", $edit["statistics_block_online_subtitle"]);
  variable_set("statistics_block_online_time", $edit["statistics_block_online_time"]);
  variable_set("statistics_block_online_max_len", $edit["statistics_block_online_max_len"]);
  variable_set("statistics_block_online_max_cnt", $edit["statistics_block_online_max_cnt"]);
}


/* Saves the values entered in the "userpage" administration form */
function statistics_save_userconfig($edit) {
  variable_set("statistics_userpage_link", $edit["statistics_userpage_link"]);
  variable_set("statistics_userpage_day_head", $edit["statistics_userpage_day_head"]);
  variable_set("statistics_userpage_day_cnt", $edit["statistics_userpage_day_cnt"]);
  variable_set("statistics_userpage_all_head", $edit["statistics_userpage_all_head"]);
  variable_set("statistics_userpage_all_cnt", $edit["statistics_userpage_all_cnt"]);
  variable_set("statistics_userpage_last_head", $edit["statistics_userpage_last_head"]);
  variable_set("statistics_userpage_last_cnt", $edit["statistics_userpage_last_cnt"]);
}


/* 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 */
Dries's avatar
   
Dries committed
614
    db_query("UPDATE {statistics} SET daycount='0'");
615
616
617
618
    variable_set("statistics_day_timestamp", time());
  }

  /* clean expired access logs */
Dries's avatar
   
Dries committed
619
  db_query("DELETE FROM {accesslog} WHERE ". time() ." - timestamp > ". variable_get("statistics_flush_accesslog_timer", 259200));
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674

  $throttle = variable_get("statistics_throttle_level", 0);
  /* check if throttle is currently on and if it's time to drop level */
  if (($throttle) && ((time() - variable_get("statistics_throttle_cron_timer", 10800)) > variable_get("statistics_throttle_cron_timestamp", 0))) {
    /* If throttle is on, back off one notch to test server load */
    variable_set("statistics_throttle_level", $throttle - 1);
    variable_set("statistics_throttle_cron_timestamp", time());
    watchdog("warning", t("cron: decreasing throttle to level '%level' to test server load.", array("%level" => ($throttle - 1))));
  }
}


/* Displays the "Top nodes" block */
function statistics_display_topnodes_block() {

  $content = array();

  $daytop = variable_get("statistics_block_top_day_num", "");
  if ($daytop) {
    $content[] = node_title_list(statistics_title_list("daycount", $daytop), variable_get("statistics_block_top_day_head", ""));
  }

  $alltimetop = variable_get("statistics_block_top_all_num", "");
  if ($alltimetop) {
    $content[] = node_title_list(statistics_title_list("totalcount", $alltimetop), variable_get("statistics_block_top_all_head", ""));
  }

  $lasttop = variable_get("statistics_block_top_last_num", "");
  if ($lasttop) {
    $content[] = node_title_list(statistics_title_list("timestamp", $lasttop), variable_get("statistics_block_top_last_head", ""));
  }

  $output = implode($content, "<br />");

  return $output;
}


/* This displays the "Who's online" block */
function statistics_display_online_block() {
  global $id, $recent_activity;

  if (user_access("access content")) {
    $throttle = throttle_status();
    $multiplier = variable_get("statistics_throttle_multiplier", 60);

    /* don't do any database lookups if on maximum throttle */
    if ($throttle < 5) {
      /* count users with activity in the past defined period */
      $time_period = variable_get("statistics_block_online_time", 2700);

      /*
      ** This call gathers all the info we need on users/guests in a single
      ** database call, thus is quite efficient.
      */
Dries's avatar
   
Dries committed
675
      $result = db_query("SELECT COUNT(DISTINCT hostname) AS count, uid, MAX(timestamp) AS max_timestamp FROM {accesslog} WHERE timestamp >= %d GROUP BY uid ORDER BY max_timestamp DESC", (time() - $time_period));
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695

      $users = $guests = 0;
      /* Count number of users & guests currently online based on db query */
      while ($users_online = db_fetch_array($result)) {
        if ($users_online["uid"]) {
          /* Has uid, so is a registered user */
          $user_list[$users] = $users_online[uid];
          $users++;
        }
        else {
          /*
          ** There's only going to be one return with a uid of 0, and that's
          ** the guest(s). Hence, the count of this field is the total number
          ** of guests currently online.
          */
          $guests = $users_online["count"];
        }
      }

      /* format the output with proper grammar */
Dries's avatar
   
Dries committed
696
697
698
699
700
701
      if ($users == 1 && $guests == 1) {
        $output .= t("There is currently %members and %visitors online.", array("%members" => format_plural($users, "1 user", "%count users"), "%visitors" => format_plural($guests, "1 guest", "%count guests")));
      }
      else {
        $output .= t("There are currently %members and %visitors online.", array("%members" => format_plural($users, "1 user", "%count users"), "%visitors" => format_plural($guests, "1 guest", "%count guests")));
      }
702
703
704
705
706
707
708
709

      if (user_access("access userlist") && $users) {
        /* Display a list of currently online users */
        $max_users = variable_get("statistics_block_online_max_cnt", 10);
        $uid = reset($user_list);
        while (($uid) && ($max_users)) {
          $user = user_load(array("uid" => $uid));
          /* When displaying name, be sure it's not more than defined max length */
Dries's avatar
Dries committed
710
          $items[] = format_name($user);
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
          $uid = next($user_list);
          /*
          ** When $max_users reaches zero, we break out even if there are
          ** more online (as defined by the admin)
          */
          $max_users--;
        }

        $output .= "<br /><br />";
        $output .= theme("theme_item_list", $items, variable_get("statistics_block_online_subtitle", "Online users:"));
      }
    }
    else {
      /* default message when fully throttled */
      $output = t("This site is currently sustaining more than %total page views a minute.", array("%total" => ($throttle * $multiplier)));
    }
    return $output;
  }
}


/* Display linked title based on field name */
function statistics_title_list($dbfield, $dbrows) {
  /* valid dbfields: totalcount, daycount, timestamp */
Dries's avatar
   
Dries committed
735
  return db_query_range("SELECT s.nid, n.title, u.uid, u.name FROM {statistics} 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);
736
737
738
739
740
741
742
743
}


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

  if ($nid > 0) {
    /* retrieves an array with both totalcount and daycount */
Dries's avatar
   
Dries committed
744
    $statistics = db_fetch_array(db_query("SELECT totalcount, daycount, timestamp FROM {statistics} WHERE nid = %d", $nid));
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
  }

  return $statistics;

}


/* Block hook */
function statistics_block($op = "list", $delta = 0) {
  if ($op == "list") {
    if (variable_get("statistics_enable_node_counter", 0)) {
      $blocks[0]["info"] = t("Top nodes");
    }
    if (variable_get("statistics_enable_access_log", 0)) {
      $blocks[1]["info"] = t("Who's online");
    }
    return $blocks;
  }
Dries's avatar
   
Dries committed
763
  else if (user_access("access content")) {
Dries's avatar
   
Dries committed
764
    switch ($delta) {
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
      case 0:
        $block["subject"] = variable_get("statistics_block_top_title", t("Popular content"));
        $block["content"] = statistics_display_topnodes_block();
        break;

      case 1:
        $block["subject"] = variable_get("statistics_block_online_title", t("Who's online"));
        $block["content"] = statistics_display_online_block();
        break;
    }

    return $block;
  }
}


function statistics_page() {


  if (user_access("access content")) {
    theme("header");
    statistics_page_user();
    theme("footer");
  }
  else {
    theme("header");
    theme("box", t("Access denied"), message_access());
    theme("footer");
  }
}


/* Generates the statistics user page */
function statistics_page_user($uid = 0, $date = 0, $all = 0) {

  if (!$date) {
    $date = time();
  }

  if ($displaycount = variable_get("statistics_userpage_day_cnt", 10)) {
    $output = "<table border=\"0\" cellpadding=\"4\" cellspacing=\"4\" style=\"width: 100%;\">";
    $output .= statistics_summary("daycount", $displaycount);
    $output .= "</table>";

    theme("box", t(variable_get("statistics_userpage_day_head", "")), $output, "main");
  }


  if ($displaycount = variable_get("statistics_userpage_all_cnt", "10")) {
    $output = "<table border=\"0\" cellpadding=\"4\" cellspacing=\"4\" style=\"width: 100%;\">";
    $output .= statistics_summary("totalcount", $displaycount);
    $output .= "</table>";

    theme("box", t(variable_get("statistics_userpage_all_head", "")), $output, "main");
  }

  if ($displaycount = variable_get("statistics_userpage_last_cnt", "10")) {
    $output = "<table border=\"0\" cellpadding=\"4\" cellspacing=\"4\" style=\"width: 100%;\">";
    $output .= statistics_summary("timestamp", $displaycount);
    $output .= "</table>";

    theme("box", t(variable_get("statistics_userpage_last_head", "")), $output, "main");
  }
}


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

  $output = "";
Dries's avatar
   
Dries committed
835
  $result = db_query_range("SELECT n.nid, n.title FROM {statistics} s INNER JOIN {node} n ON s.nid = n.nid ORDER BY %s DESC", $dbfield, 0, $dbrows);
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
  while ($nid = db_fetch_array($result)) {
    $content = node_load(array("nid" => $nid["nid"]));
    $links = link_node($content, 1);

    $output .= "<tr><td><b>". l($nid["title"], "node/view/". $nid["nid"], array("title" => t("View this posting."))) ."</b></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
Dries's avatar
   
Dries committed
852
    db_query("DELETE FROM {statistics} WHERE nid = %d", $node->nid);
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
  }
}

/* internal throttle function - do not call from other modules */
function throttle_update($recent_activity) {
  $throttle = throttle_status();
  $multiplier = variable_get("statistics_throttle_multiplier", 60);

  for ($i = 0; $i <= 5; $i++) {
    if (($i * $multiplier) <= $recent_activity) {
      $throttle_new = $i;
    }
  }

  if ($throttle_new != $throttle) {
    /*
    ** reduce throttle if new throttle would be 3+ less than current throttle,
    ** (all other throttle reduction done by _cron hook), increase throttle if
    **  new throttle would be greater than current throttle.
    */
    if (($throttle_new < ($throttle - 2)) || ($throttle_new > $throttle)) {
      /* update throttle level */
      variable_set("statistics_throttle_level", $throttle_new);
      /*
      ** update the global timestamp, preventing cron.php from jumping in
      ** too quickly, allowing for user defined period to first pass.
      */
      variable_set("statistics_throttle_cron_timestamp", time());
      /* log the change */
      if ($throttle_new < $throttle) {
        watchdog("message", "message: '". $recent_activity ."' hits in past minute; throttle decreased to level ". $throttle_new);
      }
      else {
        watchdog("warning", "warning: '". $recent_activity ."' hits in past minute; throttle increased to level ". $throttle_new);
      }
    }
  }
}

/***********************
 *  Auto-throttle API  *
 ***********************/

/* external throttle functions - call this from other modules, themes, etc */
function throttle_status() {
  static $throttle;

  $throttle = variable_get("statistics_throttle_level", 0);

  return $throttle;
}

?>