summaryrefslogtreecommitdiffstats
path: root/core/modules/statistics/statistics.module
blob: 7b1528161c4651b044191e341d63af1df74069ff (plain)
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
<?php

/**
 * @file
 * Logs and displays content statistics for a site.
 */

use Drupal\Core\Entity\EntityInterface;
use Drupal\entity\Plugin\Core\Entity\EntityDisplay;

/**
 * Implements hook_help().
 */
function statistics_help($path, $arg) {
  switch ($path) {
    case 'admin/help#statistics':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('The Statistics module shows you how often content is viewed. This is useful in determining which pages of your site are most popular. 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>';
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Displaying popular content') . '</dt>';
      $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>';
      $output .= '<dt>' . t('Page view counter') . '</dt>';
      $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>';
      $output .= '</dl>';
      return $output;
    case 'admin/config/system/statistics':
      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>';
  }
}

/**
 * Implements hook_permission().
 */
function statistics_permission() {
  return array(
    'administer statistics' => array(
      'title' => t('Administer statistics'),
    ),
    'view post access counter' => array(
      'title' => t('View content hits'),
    ),
  );
}

/**
 * Implements hook_node_view().
 */
function statistics_node_view(EntityInterface $node, EntityDisplay $display, $view_mode) {
  if (!empty($node->nid) && $view_mode == 'full' && node_is_page($node) && empty($node->in_preview)) {
    $node->content['#attached']['library'][] = array('statistics', 'drupal.statistics');
    $settings = array('data' => array('nid' => $node->nid), 'url' => url(drupal_get_path('module', 'statistics') . '/statistics.php'));
    $node->content['#attached']['js'][] = array(
      'data' => array('statistics' => $settings),
      'type' => 'setting',
    );
  }

  if ($view_mode != 'rss') {
    if (user_access('view post access counter')) {
      $statistics = statistics_get($node->nid);
      if ($statistics) {
        $links['statistics_counter']['title'] = format_plural($statistics['totalcount'], '1 view', '@count views');
        $node->content['links']['statistics'] = array(
          '#theme' => 'links__node__statistics',
          '#links' => $links,
          '#attributes' => array('class' => array('links', 'inline')),
        );
      }
    }
  }
}

/**
 * Implements hook_menu().
 */
function statistics_menu() {
  $items['admin/config/system/statistics'] = array(
    'title' => 'Statistics',
    'description' => 'Control details about what and how your site logs content statistics.',
    'route_name' => 'statistics_settings',
    'access arguments' => array('administer statistics'),
    'weight' => -15,
  );
  return $items;
}

/**
 * Implements hook_cron().
 */
function statistics_cron() {
  $statistics_timestamp = state()->get('statistics.day_timestamp') ?: 0;

  if ((REQUEST_TIME - $statistics_timestamp) >= 86400) {
    // Reset day counts.
    db_update('node_counter')
      ->fields(array('daycount' => 0))
      ->execute();
    state()->set('statistics.day_timestamp', REQUEST_TIME);
  }
}

/**
 * Returns the most viewed content of all time, today, or the last-viewed node.
 *
 * @param string $dbfield
 *   The database field to use, one of:
 *   - 'totalcount': Integer that shows the top viewed content of all time.
 *   - 'daycount': Integer that shows the top viewed content for today.
 *   - 'timestamp': Integer that shows only the last viewed node.
 * @param int $dbrows
 *   The number of rows to be returned.
 *
 * @return SelectQuery|FALSE
 *   A query result containing the node ID, title, user ID that owns the node,
 *   and the username for the selected node(s), or FALSE if the query could not
 *   be executed correctly.
 */
function statistics_title_list($dbfield, $dbrows) {
  if (in_array($dbfield, array('totalcount', 'daycount', 'timestamp'))) {
    $query = db_select('node', 'n');
    $query->addTag('node_access');
    $query->join('node_counter', 's', 'n.nid = s.nid');
    $query->join('users', 'u', 'n.uid = u.uid');

    return $query
      ->fields('n', array('nid', 'title'))
      ->fields('u', array('uid', 'name'))
      ->condition($dbfield, 0, '<>')
      ->condition('n.status', 1)
      ->orderBy($dbfield, 'DESC')
      ->range(0, $dbrows)
      ->execute();
  }
  return FALSE;
}


/**
 * Retrieves a node's "view statistics".
 *
 * @param $nid
 *   The node ID.
 *
 * @return
 *   An associative array containing:
 *   - totalcount: Integer for the total number of times the node has been
 *     viewed.
 *   - daycount: Integer for the total number of times the node has been viewed
 *     "today". For the daycount to be reset, cron must be enabled.
 *   - timestamp: Integer for the timestamp of when the node was last viewed.
 */
function statistics_get($nid) {

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

/**
 * Generates a link to a path, truncating the displayed text to a given width.
 *
 * @param string $path
 *   The path to generate the link for.
 * @param int $width
 *   The width to set the displayed text of the path.
 *
 * @return string
 *   A string as a link, truncated to the width, linked to the given $path.
 */
function _statistics_link($path, $width = 35) {
  $title = drupal_container()->get('path.alias_manager')->getPathAlias($path);
  $title = truncate_utf8($title, $width, FALSE, TRUE);
  return l($title, $path);
}

/**
 * Formats an item for display, including both the item title and the link.
 *
 * @param string $title
 *   The text to link to a path; will be truncated to a maximum width of 35.
 * @param string $path
 *   The path to link to; will default to '/'.
 *
 * @return string
 *   An HTML string with $title linked to the $path.
 */
function _statistics_format_item($title, $path) {
  $path = ($path ? $path : '/');
  $output  = ($title ? "$title<br />" : '');
  $output .= _statistics_link($path);
  return $output;
}

/**
 * Implements hook_node_predelete().
 */
function statistics_node_predelete(EntityInterface $node) {
  // clean up statistics table when node is deleted
  db_delete('node_counter')
    ->condition('nid', $node->nid)
    ->execute();
}

/**
 * Implements hook_ranking().
 */
function statistics_ranking() {
  if (config('statistics.settings')->get('count_content_views')) {
    return array(
      'views' => array(
        'title' => t('Number of views'),
        'join' => array(
          'type' => 'LEFT',
          'table' => 'node_counter',
          'alias' => 'node_counter',
          'on' => 'node_counter.nid = i.sid',
        ),
        // Inverse law that maps the highest view count on the site to 1 and 0 to 0.
        'score' => '2.0 - 2.0 / (1.0 + node_counter.totalcount * CAST(:scale AS DECIMAL))',
        'arguments' => array(':scale' => state()->get('statistics.node_counter_scale') ?: 0),
      ),
    );
  }
}

/**
 * Implements hook_update_index().
 */
function statistics_update_index() {
  state()->set('statistics.node_counter_scale', 1.0 / max(1, db_query('SELECT MAX(totalcount) FROM {node_counter}')->fetchField()));
}

/**
 * Implements hook_preprocess_HOOK() for block.html.twig.
 */
function statistics_preprocess_block(&$variables) {
  if ($variables['configuration']['module'] == 'statistics') {
    $variables['attributes']['role'] = 'navigation';
  }
}

/**
 * Implements hook_library_info().
 */
function statistics_library_info() {
  $libraries['drupal.statistics'] = array(
    'title' => 'Statistics',
    'version' => VERSION,
    'js' => array(
      drupal_get_path('module', 'statistics') . '/statistics.js' => array(
        'scope' => 'footer'
      ),
    ),
    'dependencies' => array(
      array('system', 'jquery'),
      array('system', 'drupal'),
      array('system', 'drupalSettings'),
    ),
  );

  return $libraries;
}

/**
 * Implements hook_block_alter().
 *
 * Removes the "popular" block from display if the module is not configured
 * to count content views.
 */
function statistics_block_alter(&$definitions) {
  $statistics_count_content_views = config('statistics.settings')->get('count_content_views');
  if (empty($statistics_count_content_views)) {
    unset($definitions['statistics_popular_block']);
  }
}