Projet

Général

Profil

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

root / drupal7 / modules / statistics / statistics.module @ 7dbec6b0

1
<?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
    drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION);
78

    
79
    // For anonymous users unicode.inc will not have been loaded.
80
    include_once DRUPAL_ROOT . '/includes/unicode.inc';
81
    // Log this page access.
82
    db_insert('accesslog')
83
      ->fields(array(
84
        'title' => truncate_utf8(strip_tags(drupal_get_title()), 255),
85
        'path' => truncate_utf8($_GET['q'], 255),
86
        'url' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '',
87
        'hostname' => ip_address(),
88
        'uid' => $user->uid,
89
        'sid' => session_id(),
90
        'timer' => (int) timer_read('page'),
91
        'timestamp' => REQUEST_TIME,
92
      ))
93
      ->execute();
94
  }
95
}
96

    
97
/**
98
 * Implements hook_permission().
99
 */
100
function statistics_permission() {
101
  return array(
102
    'administer statistics' => array(
103
      'title' => t('Administer statistics'),
104
    ),
105
    'access statistics' => array(
106
      'title' => t('View content access statistics'),
107
    ),
108
    'view post access counter' => array(
109
      'title' => t('View content hits'),
110
    ),
111
  );
112
}
113

    
114
/**
115
 * Implements hook_node_view().
116
 */
117
function statistics_node_view($node, $view_mode) {
118
  // Attach Ajax node count statistics if configured.
119
  if (variable_get('statistics_count_content_views', 0) && variable_get('statistics_count_content_views_ajax', 0)) {
120
    if (!empty($node->nid) && $view_mode == 'full' && node_is_page($node) && empty($node->in_preview)) {
121
      $statistics = drupal_get_path('module', 'statistics') . '/statistics.js';
122
      $node->content['#attached']['js'][$statistics] = array(
123
        'scope' => 'footer',
124
      );
125
      $settings = array('data' => array('nid' => $node->nid), 'url' => url(drupal_get_path('module', 'statistics') . '/statistics.php'));
126
      $node->content['#attached']['js'][] = array(
127
        'data' => array('statistics' => $settings),
128
        'type' => 'setting',
129
      );
130
    }
131
  }
132

    
133
  if ($view_mode != 'rss') {
134
    if (user_access('view post access counter')) {
135
      $statistics = statistics_get($node->nid);
136
      if ($statistics) {
137
        $links['statistics_counter']['title'] = format_plural($statistics['totalcount'], '1 read', '@count reads');
138
        $node->content['links']['statistics'] = array(
139
          '#theme' => 'links__node__statistics',
140
          '#links' => $links,
141
          '#attributes' => array('class' => array('links', 'inline')),
142
        );
143
      }
144
    }
145
  }
146
}
147

    
148
/**
149
 * Implements hook_menu().
150
 */
151
function statistics_menu() {
152
  $items['admin/reports/hits'] = array(
153
    'title' => 'Recent hits',
154
    'description' => 'View pages that have recently been visited.',
155
    'page callback' => 'statistics_recent_hits',
156
    'access arguments' => array('access statistics'),
157
    'file' => 'statistics.admin.inc',
158
  );
159
  $items['admin/reports/pages'] = array(
160
    'title' => 'Top pages',
161
    'description' => 'View pages that have been hit frequently.',
162
    'page callback' => 'statistics_top_pages',
163
    'access arguments' => array('access statistics'),
164
    'weight' => 1,
165
    'file' => 'statistics.admin.inc',
166
  );
167
  $items['admin/reports/visitors'] = array(
168
    'title' => 'Top visitors',
169
    'description' => 'View visitors that hit many pages.',
170
    'page callback' => 'statistics_top_visitors',
171
    'access arguments' => array('access statistics'),
172
    'weight' => 2,
173
    'file' => 'statistics.admin.inc',
174
  );
175
  $items['admin/reports/referrers'] = array(
176
    'title' => 'Top referrers',
177
    'description' => 'View top referrers.',
178
    'page callback' => 'statistics_top_referrers',
179
    'access arguments' => array('access statistics'),
180
    'file' => 'statistics.admin.inc',
181
  );
182
  $items['admin/reports/access/%'] = array(
183
    'title' => 'Details',
184
    'description' => 'View access log.',
185
    'page callback' => 'statistics_access_log',
186
    'page arguments' => array(3),
187
    'access arguments' => array('access statistics'),
188
    'file' => 'statistics.admin.inc',
189
  );
190
  $items['admin/config/system/statistics'] = array(
191
    'title' => 'Statistics',
192
    'description' => 'Control details about what and how your site logs access statistics.',
193
    'page callback' => 'drupal_get_form',
194
    'page arguments' => array('statistics_settings_form'),
195
    'access arguments' => array('administer statistics'),
196
    'file' => 'statistics.admin.inc',
197
    'weight' => -15,
198
  );
199
  $items['user/%user/track/navigation'] = array(
200
    'title' => 'Track page visits',
201
    'page callback' => 'statistics_user_tracker',
202
    'access callback' => 'user_access',
203
    'access arguments' => array('access statistics'),
204
    'type' => MENU_LOCAL_TASK,
205
    'weight' => 2,
206
    'file' => 'statistics.pages.inc',
207
  );
208
  $items['node/%node/track'] = array(
209
    'title' => 'Track',
210
    'page callback' => 'statistics_node_tracker',
211
    'access callback' => 'user_access',
212
    'access arguments' => array('access statistics'),
213
    'type' => MENU_LOCAL_TASK,
214
    'weight' => 2,
215
    'file' => 'statistics.pages.inc',
216
  );
217

    
218
  return $items;
219
}
220

    
221
/**
222
 * Implements hook_user_cancel().
223
 */
224
function statistics_user_cancel($edit, $account, $method) {
225
  switch ($method) {
226
    case 'user_cancel_reassign':
227
      db_update('accesslog')
228
        ->fields(array('uid' => 0))
229
        ->condition('uid', $account->uid)
230
        ->execute();
231
      break;
232
  }
233
}
234

    
235
/**
236
 * Implements hook_user_delete().
237
 */
238
function statistics_user_delete($account) {
239
  db_delete('accesslog')
240
    ->condition('uid', $account->uid)
241
    ->execute();
242
}
243

    
244
/**
245
 * Implements hook_cron().
246
 */
247
function statistics_cron() {
248
  $statistics_timestamp = variable_get('statistics_day_timestamp', 0);
249

    
250
  if ((REQUEST_TIME - $statistics_timestamp) >= 86400) {
251
    // Reset day counts.
252
    db_update('node_counter')
253
      ->fields(array('daycount' => 0))
254
      ->execute();
255
    variable_set('statistics_day_timestamp', REQUEST_TIME);
256
  }
257

    
258
  // Clean up expired access logs (if applicable).
259
  if (variable_get('statistics_flush_accesslog_timer', 259200) > 0) {
260
    db_delete('accesslog')
261
      ->condition('timestamp', REQUEST_TIME - variable_get('statistics_flush_accesslog_timer', 259200), '<')
262
      ->execute();
263
  }
264
}
265

    
266
/**
267
 * Returns the most viewed content of all time, today, or the last-viewed node.
268
 *
269
 * @param $dbfield
270
 *   The database field to use, one of:
271
 *   - 'totalcount': Integer that shows the top viewed content of all time.
272
 *   - 'daycount': Integer that shows the top viewed content for today.
273
 *   - 'timestamp': Integer that shows only the last viewed node.
274
 * @param $dbrows
275
 *   The number of rows to be returned.
276
 *
277
 * @return SelectQuery|FALSE
278
 *   A query result containing the node ID, title, user ID that owns the node,
279
 *   and the username for the selected node(s), or FALSE if the query could not
280
 *   be executed correctly.
281
 */
282
function statistics_title_list($dbfield, $dbrows) {
283
  if (in_array($dbfield, array('totalcount', 'daycount', 'timestamp'))) {
284
    $query = db_select('node', 'n');
285
    $query->addTag('node_access');
286
    $query->join('node_counter', 's', 'n.nid = s.nid');
287
    $query->join('users', 'u', 'n.uid = u.uid');
288

    
289
    return $query
290
      ->fields('n', array('nid', 'title'))
291
      ->fields('u', array('uid', 'name'))
292
      ->condition($dbfield, 0, '<>')
293
      ->condition('n.status', 1)
294
      ->orderBy($dbfield, 'DESC')
295
      ->range(0, $dbrows)
296
      ->execute();
297
  }
298
  return FALSE;
299
}
300

    
301

    
302
/**
303
 * Retrieves a node's "view statistics".
304
 *
305
 * @param $nid
306
 *   The node ID.
307
 *
308
 * @return
309
 *   An associative array containing:
310
 *   - totalcount: Integer for the total number of times the node has been
311
 *     viewed.
312
 *   - daycount: Integer for the total number of times the node has been viewed
313
 *     "today". For the daycount to be reset, cron must be enabled.
314
 *   - timestamp: Integer for the timestamp of when the node was last viewed.
315
 */
316
function statistics_get($nid) {
317

    
318
  if ($nid > 0) {
319
    // Retrieve an array with both totalcount and daycount.
320
    return db_query('SELECT totalcount, daycount, timestamp FROM {node_counter} WHERE nid = :nid', array(':nid' => $nid), array('target' => 'slave'))->fetchAssoc();
321
  }
322
}
323

    
324
/**
325
 * Implements hook_block_info().
326
 */
327
function statistics_block_info() {
328
  $blocks = array();
329

    
330
  if (variable_get('statistics_count_content_views', 0)) {
331
    $blocks['popular']['info'] = t('Popular content');
332
    // Too dynamic to cache.
333
    $blocks['popular']['cache'] = DRUPAL_NO_CACHE;
334
  }
335
  return $blocks;
336
}
337

    
338
/**
339
 * Implements hook_block_configure().
340
 */
341
function statistics_block_configure($delta = '') {
342
  // Popular content block settings
343
  $numbers = array('0' => t('Disabled')) + drupal_map_assoc(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25, 30, 40));
344
  $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.'));
345
  $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.'));
346
  $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.'));
347
  return $form;
348
}
349

    
350
/**
351
 * Implements hook_block_save().
352
 */
353
function statistics_block_save($delta = '', $edit = array()) {
354
  variable_set('statistics_block_top_day_num', $edit['statistics_block_top_day_num']);
355
  variable_set('statistics_block_top_all_num', $edit['statistics_block_top_all_num']);
356
  variable_set('statistics_block_top_last_num', $edit['statistics_block_top_last_num']);
357
}
358

    
359
/**
360
 * Implements hook_block_view().
361
 */
362
function statistics_block_view($delta = '') {
363
  if (user_access('access content')) {
364
    $content = array();
365

    
366
    $daytop = variable_get('statistics_block_top_day_num', 0);
367
    if ($daytop && ($result = statistics_title_list('daycount', $daytop)) && ($node_title_list = node_title_list($result, t("Today's:")))) {
368
      $content['top_day'] = $node_title_list;
369
      $content['top_day']['#suffix'] = '<br />';
370
    }
371

    
372
    $alltimetop = variable_get('statistics_block_top_all_num', 0);
373
    if ($alltimetop && ($result = statistics_title_list('totalcount', $alltimetop)) && ($node_title_list = node_title_list($result, t('All time:')))) {
374
      $content['top_all'] = $node_title_list;
375
      $content['top_all']['#suffix'] = '<br />';
376
    }
377

    
378
    $lasttop = variable_get('statistics_block_top_last_num', 0);
379
    if ($lasttop && ($result = statistics_title_list('timestamp', $lasttop)) && ($node_title_list = node_title_list($result, t('Last viewed:')))) {
380
      $content['top_last'] = $node_title_list;
381
      $content['top_last']['#suffix'] = '<br />';
382
    }
383

    
384
    if (count($content)) {
385
      $block['content'] = $content;
386
      $block['subject'] = t('Popular content');
387
      return $block;
388
    }
389
  }
390
}
391

    
392
/**
393
 * Generates a link to a path, truncating the displayed text to a given width.
394
 *
395
 * @param $path
396
 *   The path to generate the link for.
397
 * @param $width
398
 *   The width to set the displayed text of the path.
399
 *
400
 * @return
401
 *   A string as a link, truncated to the width, linked to the given $path.
402
 */
403
function _statistics_link($path, $width = 35) {
404
  $title = drupal_get_path_alias($path);
405
  $title = truncate_utf8($title, $width, FALSE, TRUE);
406
  return l($title, $path);
407
}
408

    
409
/**
410
 * Formats an item for display, including both the item title and the link.
411
 *
412
 * @param $title
413
 *   The text to link to a path; will be truncated to a maximum width of 35.
414
 * @param $path
415
 *   The path to link to; will default to '/'.
416
 *
417
 * @return
418
 *   An HTML string with $title linked to the $path.
419
 */
420
function _statistics_format_item($title, $path) {
421
  $path = ($path ? $path : '/');
422
  $output  = ($title ? "$title<br />" : '');
423
  $output .= _statistics_link($path);
424
  return $output;
425
}
426

    
427
/**
428
 * Implements hook_node_delete().
429
 */
430
function statistics_node_delete($node) {
431
  // clean up statistics table when node is deleted
432
  db_delete('node_counter')
433
    ->condition('nid', $node->nid)
434
    ->execute();
435
}
436

    
437
/**
438
 * Implements hook_ranking().
439
 */
440
function statistics_ranking() {
441
  if (variable_get('statistics_count_content_views', 0)) {
442
    return array(
443
      'views' => array(
444
        'title' => t('Number of views'),
445
        'join' => array(
446
          'type' => 'LEFT',
447
          'table' => 'node_counter',
448
          'alias' => 'node_counter',
449
          'on' => 'node_counter.nid = i.sid',
450
        ),
451
        // Inverse law that maps the highest view count on the site to 1 and 0 to 0.
452
        'score' => '2.0 - 2.0 / (1.0 + node_counter.totalcount * CAST(:scale AS DECIMAL))',
453
        'arguments' => array(':scale' => variable_get('node_cron_views_scale', 0)),
454
      ),
455
    );
456
  }
457
}
458

    
459
/**
460
 * Implements hook_update_index().
461
 */
462
function statistics_update_index() {
463
  variable_set('node_cron_views_scale', 1.0 / max(1, db_query('SELECT MAX(totalcount) FROM {node_counter}')->fetchField()));
464
}