Projet

Général

Profil

Paste
Télécharger (18,7 ko) Statistiques
| Branche: | Révision:

root / drupal7 / modules / statistics / statistics.module @ 01dfd3b5

1 85ad3d82 Assos Assos
<?php
2
3
/**
4
 * @file
5
 * Logs and displays access statistics for a site.
6
 */
7
8
/**
9
 * Implements hook_help().
10
 */
11
function statistics_help($path, $arg) {
12
  switch ($path) {
13
    case 'admin/help#statistics':
14
      $output = '';
15
      $output .= '<h3>' . t('About') . '</h3>';
16
      $output .= '<p>' . t('The Statistics module shows you how often a given page is viewed, who viewed it, the previous page the user visited (referrer URL), and when it was viewed. These statistics are useful in determining how users are visiting and navigating your site. For more information, see the online handbook entry for the <a href="@statistics">Statistics module</a>.', array('@statistics' => url('http://drupal.org/documentation/modules/statistics/'))) . '</p>';
17
      $output .= '<h3>' . t('Uses') . '</h3>';
18
      $output .= '<dl>';
19
      $output .= '<dt>' . t('Managing logs') . '</dt>';
20
      $output .= '<dd>' . t('To enable collection of statistics, the <em>Enable access log</em> checkbox on the <a href="@statistics-settings">Statistics settings page</a> must be checked. The <em>Discard access logs older than</em> setting on the settings page specifies the length of time entries are kept in the log before they are deleted. This setting requires a correctly configured <a href="@cron">cron maintenance task</a> to run.', array('@statistics-settings' => url('admin/config/system/statistics'), '@cron' => 'http://drupal.org/cron')) . '</dd>';
21
      $output .= '<dt>' . t('Viewing site usage') . '</dt>';
22
      $output .= '<dd>' . t('The Statistics module can help you break down details about your users and how they are using the site. The module offers four reports:');
23
      $output .= '<ul><li>' . t('<a href="@recent-hits">Recent hits</a> displays information about the latest activity on your site, including the URL and title of the page that was accessed, the user name (if available) and the IP address of the viewer.', array('@recent-hits' => url('admin/reports/hits'))) . '</li>';
24
      $output .= '<li>' . t('<a href="@top-referrers">Top referrers</a> displays where visitors came from (referrer URL).', array('@top-referrers' => url('admin/reports/referrers'))) . '</li>';
25
      $output .= '<li>' . t('<a href="@top-pages">Top pages</a> displays a list of pages ordered by how often they were viewed.', array('@top-pages' => url('admin/reports/pages'))) . '</li>';
26
      $output .= '<li>' . t('<a href="@top-visitors">Top visitors</a> shows you the most active visitors for your site and allows you to ban abusive visitors.', array('@top-visitors' => url('admin/reports/visitors'))) . '</li></ul>';
27
      $output .= '<dt>' . t('Displaying popular content') . '</dt>';
28
      $output .= '<dd>' . t('The module includes a <em>Popular content</em> block that displays the most viewed pages today and for all time, and the last content viewed. To use the block, enable <em>Count content views</em> on the <a href="@statistics-settings">statistics settings page</a>, and then you can enable and configure the block on the <a href="@blocks">blocks administration page</a>.', array('@statistics-settings' => url('admin/config/system/statistics'), '@blocks' => url('admin/structure/block'))) . '</dd>';
29
      $output .= '<dt>' . t('Page view counter') . '</dt>';
30
      $output .= '<dd>' . t('The Statistics module includes a counter for each page that increases whenever the page is viewed. To use the counter, enable <em>Count content views</em> on the <a href="@statistics-settings">statistics settings page</a>, and set the necessary <a href="@permissions">permissions</a> (<em>View content hits</em>) so that the counter is visible to the users.', array('@statistics-settings' => url('admin/config/system/statistics'), '@permissions' => url('admin/people/permissions', array('fragment' => 'module-statistics')))) . '</dd>';
31
      $output .= '</dl>';
32
      return $output;
33
    case 'admin/config/system/statistics':
34
      return '<p>' . t('Settings for the statistical information that Drupal will keep about the site. See <a href="@statistics">site statistics</a> for the actual information.', array('@statistics' => url('admin/reports/hits'))) . '</p>';
35
    case 'admin/reports/hits':
36
      return '<p>' . t("This page displays the site's most recent hits.") . '</p>';
37
    case 'admin/reports/referrers':
38
      return '<p>' . t('This page displays all external referrers, or external references to your website.') . '</p>';
39
    case 'admin/reports/visitors':
40
      return '<p>' . t("When you ban a visitor, you prevent the visitor's IP address from accessing your site. Unlike blocking a user, banning a visitor works even for anonymous users. This is most commonly used to block resource-intensive bots or web crawlers.") . '</p>';
41
  }
42
}
43
44
45
/**
46
 * Implements hook_exit().
47
 *
48
 * Gathers statistics for page accesses.
49
 */
50
function statistics_exit() {
51
  global $user;
52
53
  // When serving cached pages with the 'page_cache_without_database'
54
  // configuration, system variables need to be loaded. This is a major
55
  // performance decrease for non-database page caches, but with Statistics
56
  // module, it is likely to also have 'statistics_enable_access_log' enabled,
57
  // in which case we need to bootstrap to the session phase anyway.
58
  drupal_bootstrap(DRUPAL_BOOTSTRAP_VARIABLES);
59
60
  if (variable_get('statistics_count_content_views', 0) && !variable_get('statistics_count_content_views_ajax', 0)) {
61
    // We are counting content views.
62
    if (arg(0) == 'node' && is_numeric(arg(1)) && arg(2) == NULL) {
63
      // A node has been viewed, so update the node's counters.
64
      db_merge('node_counter')
65
        ->key(array('nid' => arg(1)))
66
        ->fields(array(
67
          'daycount' => 1,
68
          'totalcount' => 1,
69
          'timestamp' => REQUEST_TIME,
70
        ))
71
        ->expression('daycount', 'daycount + 1')
72
        ->expression('totalcount', 'totalcount + 1')
73
        ->execute();
74
    }
75
  }
76
  if (variable_get('statistics_enable_access_log', 0)) {
77
    // For anonymous users unicode.inc will not have been loaded.
78
    include_once DRUPAL_ROOT . '/includes/unicode.inc';
79
    // Log this page access.
80
    db_insert('accesslog')
81
      ->fields(array(
82
        'title' => truncate_utf8(strip_tags(drupal_get_title()), 255),
83
        'path' => truncate_utf8($_GET['q'], 255),
84
        'url' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '',
85
        'hostname' => ip_address(),
86
        'uid' => $user->uid,
87
        'sid' => session_id(),
88
        'timer' => (int) timer_read('page'),
89
        'timestamp' => REQUEST_TIME,
90
      ))
91
      ->execute();
92
  }
93
}
94
95
/**
96
 * Implements hook_permission().
97
 */
98
function statistics_permission() {
99
  return array(
100
    'administer statistics' => array(
101
      'title' => t('Administer statistics'),
102
    ),
103
    'access statistics' => array(
104
      'title' => t('View content access statistics'),
105
    ),
106
    'view post access counter' => array(
107
      'title' => t('View content hits'),
108
    ),
109
  );
110
}
111
112
/**
113
 * Implements hook_node_view().
114
 */
115
function statistics_node_view($node, $view_mode) {
116
  // Attach Ajax node count statistics if configured.
117
  if (variable_get('statistics_count_content_views', 0) && variable_get('statistics_count_content_views_ajax', 0)) {
118
    if (!empty($node->nid) && $view_mode == 'full' && node_is_page($node) && empty($node->in_preview)) {
119 582db59d Assos Assos
      $statistics = drupal_get_path('module', 'statistics') . '/statistics.js';
120
      $node->content['#attached']['js'][$statistics] = array(
121
        'scope' => 'footer',
122 85ad3d82 Assos Assos
      );
123
      $settings = array('data' => array('nid' => $node->nid), 'url' => url(drupal_get_path('module', 'statistics') . '/statistics.php'));
124
      $node->content['#attached']['js'][] = array(
125
        'data' => array('statistics' => $settings),
126
        'type' => 'setting',
127
      );
128
    }
129
  }
130
131
  if ($view_mode != 'rss') {
132
    if (user_access('view post access counter')) {
133
      $statistics = statistics_get($node->nid);
134
      if ($statistics) {
135
        $links['statistics_counter']['title'] = format_plural($statistics['totalcount'], '1 read', '@count reads');
136
        $node->content['links']['statistics'] = array(
137
          '#theme' => 'links__node__statistics',
138
          '#links' => $links,
139
          '#attributes' => array('class' => array('links', 'inline')),
140
        );
141
      }
142
    }
143
  }
144
}
145
146
/**
147
 * Implements hook_menu().
148
 */
149
function statistics_menu() {
150
  $items['admin/reports/hits'] = array(
151
    'title' => 'Recent hits',
152
    'description' => 'View pages that have recently been visited.',
153
    'page callback' => 'statistics_recent_hits',
154
    'access arguments' => array('access statistics'),
155
    'file' => 'statistics.admin.inc',
156
  );
157
  $items['admin/reports/pages'] = array(
158
    'title' => 'Top pages',
159
    'description' => 'View pages that have been hit frequently.',
160
    'page callback' => 'statistics_top_pages',
161
    'access arguments' => array('access statistics'),
162
    'weight' => 1,
163
    'file' => 'statistics.admin.inc',
164
  );
165
  $items['admin/reports/visitors'] = array(
166
    'title' => 'Top visitors',
167
    'description' => 'View visitors that hit many pages.',
168
    'page callback' => 'statistics_top_visitors',
169
    'access arguments' => array('access statistics'),
170
    'weight' => 2,
171
    'file' => 'statistics.admin.inc',
172
  );
173
  $items['admin/reports/referrers'] = array(
174
    'title' => 'Top referrers',
175
    'description' => 'View top referrers.',
176
    'page callback' => 'statistics_top_referrers',
177
    'access arguments' => array('access statistics'),
178
    'file' => 'statistics.admin.inc',
179
  );
180
  $items['admin/reports/access/%'] = array(
181
    'title' => 'Details',
182
    'description' => 'View access log.',
183
    'page callback' => 'statistics_access_log',
184
    'page arguments' => array(3),
185
    'access arguments' => array('access statistics'),
186
    'file' => 'statistics.admin.inc',
187
  );
188
  $items['admin/config/system/statistics'] = array(
189
    'title' => 'Statistics',
190
    'description' => 'Control details about what and how your site logs access statistics.',
191
    'page callback' => 'drupal_get_form',
192
    'page arguments' => array('statistics_settings_form'),
193
    'access arguments' => array('administer statistics'),
194
    'file' => 'statistics.admin.inc',
195
    'weight' => -15,
196
  );
197
  $items['user/%user/track/navigation'] = array(
198
    'title' => 'Track page visits',
199
    'page callback' => 'statistics_user_tracker',
200
    'access callback' => 'user_access',
201
    'access arguments' => array('access statistics'),
202
    'type' => MENU_LOCAL_TASK,
203
    'weight' => 2,
204
    'file' => 'statistics.pages.inc',
205
  );
206
  $items['node/%node/track'] = array(
207
    'title' => 'Track',
208
    'page callback' => 'statistics_node_tracker',
209
    'access callback' => 'user_access',
210
    'access arguments' => array('access statistics'),
211
    'type' => MENU_LOCAL_TASK,
212
    'weight' => 2,
213
    'file' => 'statistics.pages.inc',
214
  );
215
216
  return $items;
217
}
218
219
/**
220
 * Implements hook_user_cancel().
221
 */
222
function statistics_user_cancel($edit, $account, $method) {
223
  switch ($method) {
224
    case 'user_cancel_reassign':
225
      db_update('accesslog')
226
        ->fields(array('uid' => 0))
227
        ->condition('uid', $account->uid)
228
        ->execute();
229
      break;
230
  }
231
}
232
233
/**
234
 * Implements hook_user_delete().
235
 */
236
function statistics_user_delete($account) {
237
  db_delete('accesslog')
238
    ->condition('uid', $account->uid)
239
    ->execute();
240
}
241
242
/**
243
 * Implements hook_cron().
244
 */
245
function statistics_cron() {
246 5587145e Assos Assos
  $statistics_timestamp = variable_get('statistics_day_timestamp', 0);
247 85ad3d82 Assos Assos
248
  if ((REQUEST_TIME - $statistics_timestamp) >= 86400) {
249
    // Reset day counts.
250
    db_update('node_counter')
251
      ->fields(array('daycount' => 0))
252
      ->execute();
253
    variable_set('statistics_day_timestamp', REQUEST_TIME);
254
  }
255
256
  // Clean up expired access logs (if applicable).
257
  if (variable_get('statistics_flush_accesslog_timer', 259200) > 0) {
258
    db_delete('accesslog')
259
      ->condition('timestamp', REQUEST_TIME - variable_get('statistics_flush_accesslog_timer', 259200), '<')
260
      ->execute();
261
  }
262
}
263
264
/**
265
 * Returns the most viewed content of all time, today, or the last-viewed node.
266
 *
267
 * @param $dbfield
268
 *   The database field to use, one of:
269
 *   - 'totalcount': Integer that shows the top viewed content of all time.
270
 *   - 'daycount': Integer that shows the top viewed content for today.
271
 *   - 'timestamp': Integer that shows only the last viewed node.
272
 * @param $dbrows
273
 *   The number of rows to be returned.
274
 *
275
 * @return SelectQuery|FALSE
276
 *   A query result containing the node ID, title, user ID that owns the node,
277
 *   and the username for the selected node(s), or FALSE if the query could not
278
 *   be executed correctly.
279
 */
280
function statistics_title_list($dbfield, $dbrows) {
281
  if (in_array($dbfield, array('totalcount', 'daycount', 'timestamp'))) {
282
    $query = db_select('node', 'n');
283
    $query->addTag('node_access');
284
    $query->join('node_counter', 's', 'n.nid = s.nid');
285
    $query->join('users', 'u', 'n.uid = u.uid');
286
287
    return $query
288
      ->fields('n', array('nid', 'title'))
289
      ->fields('u', array('uid', 'name'))
290
      ->condition($dbfield, 0, '<>')
291
      ->condition('n.status', 1)
292
      ->orderBy($dbfield, 'DESC')
293
      ->range(0, $dbrows)
294
      ->execute();
295
  }
296
  return FALSE;
297
}
298
299
300
/**
301
 * Retrieves a node's "view statistics".
302
 *
303
 * @param $nid
304
 *   The node ID.
305
 *
306
 * @return
307
 *   An associative array containing:
308
 *   - totalcount: Integer for the total number of times the node has been
309
 *     viewed.
310
 *   - daycount: Integer for the total number of times the node has been viewed
311
 *     "today". For the daycount to be reset, cron must be enabled.
312
 *   - timestamp: Integer for the timestamp of when the node was last viewed.
313
 */
314
function statistics_get($nid) {
315
316
  if ($nid > 0) {
317
    // Retrieve an array with both totalcount and daycount.
318
    return db_query('SELECT totalcount, daycount, timestamp FROM {node_counter} WHERE nid = :nid', array(':nid' => $nid), array('target' => 'slave'))->fetchAssoc();
319
  }
320
}
321
322
/**
323
 * Implements hook_block_info().
324
 */
325
function statistics_block_info() {
326
  $blocks = array();
327
328
  if (variable_get('statistics_count_content_views', 0)) {
329
    $blocks['popular']['info'] = t('Popular content');
330
    // Too dynamic to cache.
331
    $blocks['popular']['cache'] = DRUPAL_NO_CACHE;
332
  }
333
  return $blocks;
334
}
335
336
/**
337
 * Implements hook_block_configure().
338
 */
339
function statistics_block_configure($delta = '') {
340
  // Popular content block settings
341
  $numbers = array('0' => t('Disabled')) + drupal_map_assoc(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25, 30, 40));
342
  $form['statistics_block_top_day_num'] = array('#type' => 'select', '#title' => t("Number of day's top views to display"), '#default_value' => variable_get('statistics_block_top_day_num', 0), '#options' => $numbers, '#description' => t('How many content items to display in "day" list.'));
343
  $form['statistics_block_top_all_num'] = array('#type' => 'select', '#title' => t('Number of all time views to display'), '#default_value' => variable_get('statistics_block_top_all_num', 0), '#options' => $numbers, '#description' => t('How many content items to display in "all time" list.'));
344
  $form['statistics_block_top_last_num'] = array('#type' => 'select', '#title' => t('Number of most recent views to display'), '#default_value' => variable_get('statistics_block_top_last_num', 0), '#options' => $numbers, '#description' => t('How many content items to display in "recently viewed" list.'));
345
  return $form;
346
}
347
348
/**
349
 * Implements hook_block_save().
350
 */
351
function statistics_block_save($delta = '', $edit = array()) {
352
  variable_set('statistics_block_top_day_num', $edit['statistics_block_top_day_num']);
353
  variable_set('statistics_block_top_all_num', $edit['statistics_block_top_all_num']);
354
  variable_set('statistics_block_top_last_num', $edit['statistics_block_top_last_num']);
355
}
356
357
/**
358
 * Implements hook_block_view().
359
 */
360
function statistics_block_view($delta = '') {
361
  if (user_access('access content')) {
362
    $content = array();
363
364
    $daytop = variable_get('statistics_block_top_day_num', 0);
365
    if ($daytop && ($result = statistics_title_list('daycount', $daytop)) && ($node_title_list = node_title_list($result, t("Today's:")))) {
366
      $content['top_day'] = $node_title_list;
367
      $content['top_day']['#suffix'] = '<br />';
368
    }
369
370
    $alltimetop = variable_get('statistics_block_top_all_num', 0);
371
    if ($alltimetop && ($result = statistics_title_list('totalcount', $alltimetop)) && ($node_title_list = node_title_list($result, t('All time:')))) {
372
      $content['top_all'] = $node_title_list;
373
      $content['top_all']['#suffix'] = '<br />';
374
    }
375
376
    $lasttop = variable_get('statistics_block_top_last_num', 0);
377
    if ($lasttop && ($result = statistics_title_list('timestamp', $lasttop)) && ($node_title_list = node_title_list($result, t('Last viewed:')))) {
378
      $content['top_last'] = $node_title_list;
379
      $content['top_last']['#suffix'] = '<br />';
380
    }
381
382
    if (count($content)) {
383
      $block['content'] = $content;
384
      $block['subject'] = t('Popular content');
385
      return $block;
386
    }
387
  }
388
}
389
390
/**
391
 * Generates a link to a path, truncating the displayed text to a given width.
392
 *
393
 * @param $path
394
 *   The path to generate the link for.
395
 * @param $width
396
 *   The width to set the displayed text of the path.
397
 *
398
 * @return
399
 *   A string as a link, truncated to the width, linked to the given $path.
400
 */
401
function _statistics_link($path, $width = 35) {
402
  $title = drupal_get_path_alias($path);
403
  $title = truncate_utf8($title, $width, FALSE, TRUE);
404
  return l($title, $path);
405
}
406
407
/**
408
 * Formats an item for display, including both the item title and the link.
409
 *
410
 * @param $title
411
 *   The text to link to a path; will be truncated to a maximum width of 35.
412
 * @param $path
413
 *   The path to link to; will default to '/'.
414
 *
415
 * @return
416
 *   An HTML string with $title linked to the $path.
417
 */
418
function _statistics_format_item($title, $path) {
419
  $path = ($path ? $path : '/');
420
  $output  = ($title ? "$title<br />" : '');
421
  $output .= _statistics_link($path);
422
  return $output;
423
}
424
425
/**
426
 * Implements hook_node_delete().
427
 */
428
function statistics_node_delete($node) {
429
  // clean up statistics table when node is deleted
430
  db_delete('node_counter')
431
    ->condition('nid', $node->nid)
432
    ->execute();
433
}
434
435
/**
436
 * Implements hook_ranking().
437
 */
438
function statistics_ranking() {
439
  if (variable_get('statistics_count_content_views', 0)) {
440
    return array(
441
      'views' => array(
442
        'title' => t('Number of views'),
443
        'join' => array(
444
          'type' => 'LEFT',
445
          'table' => 'node_counter',
446
          'alias' => 'node_counter',
447
          'on' => 'node_counter.nid = i.sid',
448
        ),
449
        // Inverse law that maps the highest view count on the site to 1 and 0 to 0.
450
        'score' => '2.0 - 2.0 / (1.0 + node_counter.totalcount * CAST(:scale AS DECIMAL))',
451
        'arguments' => array(':scale' => variable_get('node_cron_views_scale', 0)),
452
      ),
453
    );
454
  }
455
}
456
457
/**
458
 * Implements hook_update_index().
459
 */
460
function statistics_update_index() {
461
  variable_set('node_cron_views_scale', 1.0 / max(1, db_query('SELECT MAX(totalcount) FROM {node_counter}')->fetchField()));
462
}