Projet

Général

Profil

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

root / drupal7 / modules / statistics / statistics.module @ bfb52287

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
    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
      $node->content['#attached']['js'] = array(
122
        drupal_get_path('module', 'statistics') . '/statistics.js' => array(
123
          'scope' => 'footer'
124
        ),
125
      );
126
      $settings = array('data' => array('nid' => $node->nid), 'url' => url(drupal_get_path('module', 'statistics') . '/statistics.php'));
127
      $node->content['#attached']['js'][] = array(
128
        'data' => array('statistics' => $settings),
129
        'type' => 'setting',
130
      );
131
    }
132
  }
133
134
  if ($view_mode != 'rss') {
135
    if (user_access('view post access counter')) {
136
      $statistics = statistics_get($node->nid);
137
      if ($statistics) {
138
        $links['statistics_counter']['title'] = format_plural($statistics['totalcount'], '1 read', '@count reads');
139
        $node->content['links']['statistics'] = array(
140
          '#theme' => 'links__node__statistics',
141
          '#links' => $links,
142
          '#attributes' => array('class' => array('links', 'inline')),
143
        );
144
      }
145
    }
146
  }
147
}
148
149
/**
150
 * Implements hook_menu().
151
 */
152
function statistics_menu() {
153
  $items['admin/reports/hits'] = array(
154
    'title' => 'Recent hits',
155
    'description' => 'View pages that have recently been visited.',
156
    'page callback' => 'statistics_recent_hits',
157
    'access arguments' => array('access statistics'),
158
    'file' => 'statistics.admin.inc',
159
  );
160
  $items['admin/reports/pages'] = array(
161
    'title' => 'Top pages',
162
    'description' => 'View pages that have been hit frequently.',
163
    'page callback' => 'statistics_top_pages',
164
    'access arguments' => array('access statistics'),
165
    'weight' => 1,
166
    'file' => 'statistics.admin.inc',
167
  );
168
  $items['admin/reports/visitors'] = array(
169
    'title' => 'Top visitors',
170
    'description' => 'View visitors that hit many pages.',
171
    'page callback' => 'statistics_top_visitors',
172
    'access arguments' => array('access statistics'),
173
    'weight' => 2,
174
    'file' => 'statistics.admin.inc',
175
  );
176
  $items['admin/reports/referrers'] = array(
177
    'title' => 'Top referrers',
178
    'description' => 'View top referrers.',
179
    'page callback' => 'statistics_top_referrers',
180
    'access arguments' => array('access statistics'),
181
    'file' => 'statistics.admin.inc',
182
  );
183
  $items['admin/reports/access/%'] = array(
184
    'title' => 'Details',
185
    'description' => 'View access log.',
186
    'page callback' => 'statistics_access_log',
187
    'page arguments' => array(3),
188
    'access arguments' => array('access statistics'),
189
    'file' => 'statistics.admin.inc',
190
  );
191
  $items['admin/config/system/statistics'] = array(
192
    'title' => 'Statistics',
193
    'description' => 'Control details about what and how your site logs access statistics.',
194
    'page callback' => 'drupal_get_form',
195
    'page arguments' => array('statistics_settings_form'),
196
    'access arguments' => array('administer statistics'),
197
    'file' => 'statistics.admin.inc',
198
    'weight' => -15,
199
  );
200
  $items['user/%user/track/navigation'] = array(
201
    'title' => 'Track page visits',
202
    'page callback' => 'statistics_user_tracker',
203
    'access callback' => 'user_access',
204
    'access arguments' => array('access statistics'),
205
    'type' => MENU_LOCAL_TASK,
206
    'weight' => 2,
207
    'file' => 'statistics.pages.inc',
208
  );
209
  $items['node/%node/track'] = array(
210
    'title' => 'Track',
211
    'page callback' => 'statistics_node_tracker',
212
    'access callback' => 'user_access',
213
    'access arguments' => array('access statistics'),
214
    'type' => MENU_LOCAL_TASK,
215
    'weight' => 2,
216
    'file' => 'statistics.pages.inc',
217
  );
218
219
  return $items;
220
}
221
222
/**
223
 * Implements hook_user_cancel().
224
 */
225
function statistics_user_cancel($edit, $account, $method) {
226
  switch ($method) {
227
    case 'user_cancel_reassign':
228
      db_update('accesslog')
229
        ->fields(array('uid' => 0))
230
        ->condition('uid', $account->uid)
231
        ->execute();
232
      break;
233
  }
234
}
235
236
/**
237
 * Implements hook_user_delete().
238
 */
239
function statistics_user_delete($account) {
240
  db_delete('accesslog')
241
    ->condition('uid', $account->uid)
242
    ->execute();
243
}
244
245
/**
246
 * Implements hook_cron().
247
 */
248
function statistics_cron() {
249
  $statistics_timestamp = variable_get('statistics_day_timestamp', '');
250
251
  if ((REQUEST_TIME - $statistics_timestamp) >= 86400) {
252
    // Reset day counts.
253
    db_update('node_counter')
254
      ->fields(array('daycount' => 0))
255
      ->execute();
256
    variable_set('statistics_day_timestamp', REQUEST_TIME);
257
  }
258
259
  // Clean up expired access logs (if applicable).
260
  if (variable_get('statistics_flush_accesslog_timer', 259200) > 0) {
261
    db_delete('accesslog')
262
      ->condition('timestamp', REQUEST_TIME - variable_get('statistics_flush_accesslog_timer', 259200), '<')
263
      ->execute();
264
  }
265
}
266
267
/**
268
 * Returns the most viewed content of all time, today, or the last-viewed node.
269
 *
270
 * @param $dbfield
271
 *   The database field to use, one of:
272
 *   - 'totalcount': Integer that shows the top viewed content of all time.
273
 *   - 'daycount': Integer that shows the top viewed content for today.
274
 *   - 'timestamp': Integer that shows only the last viewed node.
275
 * @param $dbrows
276
 *   The number of rows to be returned.
277
 *
278
 * @return SelectQuery|FALSE
279
 *   A query result containing the node ID, title, user ID that owns the node,
280
 *   and the username for the selected node(s), or FALSE if the query could not
281
 *   be executed correctly.
282
 */
283
function statistics_title_list($dbfield, $dbrows) {
284
  if (in_array($dbfield, array('totalcount', 'daycount', 'timestamp'))) {
285
    $query = db_select('node', 'n');
286
    $query->addTag('node_access');
287
    $query->join('node_counter', 's', 'n.nid = s.nid');
288
    $query->join('users', 'u', 'n.uid = u.uid');
289
290
    return $query
291
      ->fields('n', array('nid', 'title'))
292
      ->fields('u', array('uid', 'name'))
293
      ->condition($dbfield, 0, '<>')
294
      ->condition('n.status', 1)
295
      ->orderBy($dbfield, 'DESC')
296
      ->range(0, $dbrows)
297
      ->execute();
298
  }
299
  return FALSE;
300
}
301
302
303
/**
304
 * Retrieves a node's "view statistics".
305
 *
306
 * @param $nid
307
 *   The node ID.
308
 *
309
 * @return
310
 *   An associative array containing:
311
 *   - totalcount: Integer for the total number of times the node has been
312
 *     viewed.
313
 *   - daycount: Integer for the total number of times the node has been viewed
314
 *     "today". For the daycount to be reset, cron must be enabled.
315
 *   - timestamp: Integer for the timestamp of when the node was last viewed.
316
 */
317
function statistics_get($nid) {
318
319
  if ($nid > 0) {
320
    // Retrieve an array with both totalcount and daycount.
321
    return db_query('SELECT totalcount, daycount, timestamp FROM {node_counter} WHERE nid = :nid', array(':nid' => $nid), array('target' => 'slave'))->fetchAssoc();
322
  }
323
}
324
325
/**
326
 * Implements hook_block_info().
327
 */
328
function statistics_block_info() {
329
  $blocks = array();
330
331
  if (variable_get('statistics_count_content_views', 0)) {
332
    $blocks['popular']['info'] = t('Popular content');
333
    // Too dynamic to cache.
334
    $blocks['popular']['cache'] = DRUPAL_NO_CACHE;
335
  }
336
  return $blocks;
337
}
338
339
/**
340
 * Implements hook_block_configure().
341
 */
342
function statistics_block_configure($delta = '') {
343
  // Popular content block settings
344
  $numbers = array('0' => t('Disabled')) + drupal_map_assoc(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25, 30, 40));
345
  $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.'));
346
  $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.'));
347
  $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.'));
348
  return $form;
349
}
350
351
/**
352
 * Implements hook_block_save().
353
 */
354
function statistics_block_save($delta = '', $edit = array()) {
355
  variable_set('statistics_block_top_day_num', $edit['statistics_block_top_day_num']);
356
  variable_set('statistics_block_top_all_num', $edit['statistics_block_top_all_num']);
357
  variable_set('statistics_block_top_last_num', $edit['statistics_block_top_last_num']);
358
}
359
360
/**
361
 * Implements hook_block_view().
362
 */
363
function statistics_block_view($delta = '') {
364
  if (user_access('access content')) {
365
    $content = array();
366
367
    $daytop = variable_get('statistics_block_top_day_num', 0);
368
    if ($daytop && ($result = statistics_title_list('daycount', $daytop)) && ($node_title_list = node_title_list($result, t("Today's:")))) {
369
      $content['top_day'] = $node_title_list;
370
      $content['top_day']['#suffix'] = '<br />';
371
    }
372
373
    $alltimetop = variable_get('statistics_block_top_all_num', 0);
374
    if ($alltimetop && ($result = statistics_title_list('totalcount', $alltimetop)) && ($node_title_list = node_title_list($result, t('All time:')))) {
375
      $content['top_all'] = $node_title_list;
376
      $content['top_all']['#suffix'] = '<br />';
377
    }
378
379
    $lasttop = variable_get('statistics_block_top_last_num', 0);
380
    if ($lasttop && ($result = statistics_title_list('timestamp', $lasttop)) && ($node_title_list = node_title_list($result, t('Last viewed:')))) {
381
      $content['top_last'] = $node_title_list;
382
      $content['top_last']['#suffix'] = '<br />';
383
    }
384
385
    if (count($content)) {
386
      $block['content'] = $content;
387
      $block['subject'] = t('Popular content');
388
      return $block;
389
    }
390
  }
391
}
392
393
/**
394
 * Generates a link to a path, truncating the displayed text to a given width.
395
 *
396
 * @param $path
397
 *   The path to generate the link for.
398
 * @param $width
399
 *   The width to set the displayed text of the path.
400
 *
401
 * @return
402
 *   A string as a link, truncated to the width, linked to the given $path.
403
 */
404
function _statistics_link($path, $width = 35) {
405
  $title = drupal_get_path_alias($path);
406
  $title = truncate_utf8($title, $width, FALSE, TRUE);
407
  return l($title, $path);
408
}
409
410
/**
411
 * Formats an item for display, including both the item title and the link.
412
 *
413
 * @param $title
414
 *   The text to link to a path; will be truncated to a maximum width of 35.
415
 * @param $path
416
 *   The path to link to; will default to '/'.
417
 *
418
 * @return
419
 *   An HTML string with $title linked to the $path.
420
 */
421
function _statistics_format_item($title, $path) {
422
  $path = ($path ? $path : '/');
423
  $output  = ($title ? "$title<br />" : '');
424
  $output .= _statistics_link($path);
425
  return $output;
426
}
427
428
/**
429
 * Implements hook_node_delete().
430
 */
431
function statistics_node_delete($node) {
432
  // clean up statistics table when node is deleted
433
  db_delete('node_counter')
434
    ->condition('nid', $node->nid)
435
    ->execute();
436
}
437
438
/**
439
 * Implements hook_ranking().
440
 */
441
function statistics_ranking() {
442
  if (variable_get('statistics_count_content_views', 0)) {
443
    return array(
444
      'views' => array(
445
        'title' => t('Number of views'),
446
        'join' => array(
447
          'type' => 'LEFT',
448
          'table' => 'node_counter',
449
          'alias' => 'node_counter',
450
          'on' => 'node_counter.nid = i.sid',
451
        ),
452
        // Inverse law that maps the highest view count on the site to 1 and 0 to 0.
453
        'score' => '2.0 - 2.0 / (1.0 + node_counter.totalcount * CAST(:scale AS DECIMAL))',
454
        'arguments' => array(':scale' => variable_get('node_cron_views_scale', 0)),
455
      ),
456
    );
457
  }
458
}
459
460
/**
461
 * Implements hook_update_index().
462
 */
463
function statistics_update_index() {
464
  variable_set('node_cron_views_scale', 1.0 / max(1, db_query('SELECT MAX(totalcount) FROM {node_counter}')->fetchField()));
465
}