statistics.module 8.19 KB
Newer Older
1 2
<?php

Dries's avatar
 
Dries committed
3 4
/**
 * @file
5
 * Logs and displays content statistics for a site.
Dries's avatar
 
Dries committed
6 7
 */

8
use Drupal\Core\Entity\EntityInterface;
9
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
10
use Drupal\Core\Routing\RouteMatchInterface;
11
use Drupal\node\NodeInterface;
12

Dries's avatar
 
Dries committed
13
/**
14
 * Implements hook_help().
Dries's avatar
 
Dries committed
15
 */
16
function statistics_help($route_name, RouteMatchInterface $route_match) {
17 18
  switch ($route_name) {
    case 'help.page.statistics':
19 20
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
21
      $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 <a href="!statistics_do">the online documentation for the Statistics module</a>.', array('!statistics_do' => 'https://drupal.org/documentation/modules/statistics/')) . '</p>';
22 23 24
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Displaying popular content') . '</dt>';
25
      $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">Block layout page</a>.', array('!statistics-settings' => \Drupal::url('statistics.settings'), '!blocks' => \Drupal::url('block.admin_display'))) . '</dd>';
26
      $output .= '<dt>' . t('Page view counter') . '</dt>';
27
      $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' => \Drupal::url('statistics.settings'), '!permissions' => \Drupal::url('user.admin_permissions', array(), array('fragment' => 'module-statistics')))) . '</dd>';
28
      $output .= '</dl>';
29
      return $output;
30 31

    case 'statistics.settings':
32
      return '<p>' . t('Settings for the statistical information that Drupal will keep about the site.') . '</p>';
33 34 35
  }
}

Dries's avatar
 
Dries committed
36
/**
37
 * Implements hook_ENTITY_TYPE_view() for node entities.
Dries's avatar
 
Dries committed
38
 */
39
function statistics_node_view(array &$build, EntityInterface $node, EntityViewDisplayInterface $display, $view_mode) {
40
  if (!$node->isNew() && $view_mode == 'full' && node_is_page($node) && empty($node->in_preview)) {
41
    $build['statistics_content_counter']['#attached']['library'][] = 'statistics/drupal.statistics';
42
    $settings = array('data' => array('nid' => $node->id()), 'url' => _url(drupal_get_path('module', 'statistics') . '/statistics.php'));
43
    $build['statistics_content_counter']['#attached']['drupalSettings']['statistics'] = $settings;
44
  }
45
}
46

47 48 49 50 51
/**
 * Implements hook_node_links_alter().
 */
function statistics_node_links_alter(array &$node_links, NodeInterface $entity, array &$context) {
  if ($context['view_mode'] != 'rss') {
52
    if (\Drupal::currentUser()->hasPermission('view post access counter')) {
53
      $statistics = statistics_get($entity->id());
54
      if ($statistics) {
55
        $links['statistics_counter']['title'] = \Drupal::translation()->formatPlural($statistics['totalcount'], '1 view', '@count views');
56
        $node_links['statistics'] = array(
57 58 59 60
          '#theme' => 'links__node__statistics',
          '#links' => $links,
          '#attributes' => array('class' => array('links', 'inline')),
        );
61
      }
62
    }
63
  }
64 65
}

Dries's avatar
 
Dries committed
66
/**
67
 * Implements hook_cron().
Dries's avatar
 
Dries committed
68
 */
69
function statistics_cron() {
70
  $statistics_timestamp = \Drupal::state()->get('statistics.day_timestamp') ?: 0;
71

72
  if ((REQUEST_TIME - $statistics_timestamp) >= 86400) {
73
    // Reset day counts.
74 75 76
    db_update('node_counter')
      ->fields(array('daycount' => 0))
      ->execute();
77
    \Drupal::state()->set('statistics.day_timestamp', REQUEST_TIME);
78
  }
79 80

  // Calculate the maximum of node views, for node search ranking.
81
  \Drupal::state()->set('statistics.node_counter_scale', 1.0 / max(1.0, db_query('SELECT MAX(totalcount) FROM {node_counter}')->fetchField()));
82 83
}

Dries's avatar
 
Dries committed
84
/**
85
 * Returns the most viewed content of all time, today, or the last-viewed node.
Dries's avatar
 
Dries committed
86
 *
87 88 89 90 91 92 93
 * @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.
Dries's avatar
 
Dries committed
94
 *
95 96 97 98
 * @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.
Dries's avatar
 
Dries committed
99
 */
100
function statistics_title_list($dbfield, $dbrows) {
101
  if (in_array($dbfield, array('totalcount', 'daycount', 'timestamp'))) {
102
    $query = db_select('node_field_data', 'n');
103 104
    $query->addTag('node_access');
    $query->join('node_counter', 's', 'n.nid = s.nid');
105
    $query->join('users_field_data', 'u', 'n.uid = u.uid');
106 107 108 109 110 111

    return $query
      ->fields('n', array('nid', 'title'))
      ->fields('u', array('uid', 'name'))
      ->condition($dbfield, 0, '<>')
      ->condition('n.status', 1)
112 113 114
      // @todo This should be actually filtering on the desired node status
      //   field language and just fall back to the default language.
      ->condition('n.default_langcode', 1)
115
      ->condition('u.default_langcode', 1)
116 117 118
      ->orderBy($dbfield, 'DESC')
      ->range(0, $dbrows)
      ->execute();
119 120
  }
  return FALSE;
121 122
}

Dries's avatar
 
Dries committed
123

Dries's avatar
 
Dries committed
124 125 126 127
/**
 * Retrieves a node's "view statistics".
 *
 * @param $nid
128
 *   The node ID.
Dries's avatar
 
Dries committed
129 130
 *
 * @return
131 132 133 134 135 136
 *   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.
Dries's avatar
 
Dries committed
137
 */
138 139 140
function statistics_get($nid) {

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

146
/**
147
 * Implements hook_ENTITY_TYPE_predelete() for node entities.
148
 */
149
function statistics_node_predelete(EntityInterface $node) {
150
  // clean up statistics table when node is deleted
151
  db_delete('node_counter')
152
    ->condition('nid', $node->id())
153
    ->execute();
154
}
155 156

/**
157
 * Implements hook_ranking().
158 159
 */
function statistics_ranking() {
160
  if (\Drupal::config('statistics.settings')->get('count_content_views')) {
161 162 163
    return array(
      'views' => array(
        'title' => t('Number of views'),
164 165 166 167 168 169
        'join' => array(
          'type' => 'LEFT',
          'table' => 'node_counter',
          'alias' => 'node_counter',
          'on' => 'node_counter.nid = i.sid',
        ),
170 171 172 173 174 175
        // Inverse law that maps the highest view count on the site to 1 and 0
        // to 0. Note that the CAST here is necessary for PostgreSQL, because
        // the PostgreSQL PDO driver sometimes puts values in as strings
        // instead of numbers in complex expressions like this.
        'score' => '2.0 - 2.0 / (1.0 + node_counter.totalcount * (CAST (:statistics_scale AS DECIMAL(10,4))))',
        'arguments' => array(':statistics_scale' => \Drupal::state()->get('statistics.node_counter_scale') ?: 0),
176 177 178 179
      ),
    );
  }
}
180

181
/**
182
 * Implements hook_preprocess_HOOK() for block templates.
183 184
 */
function statistics_preprocess_block(&$variables) {
185
  if ($variables['configuration']['provider'] == 'statistics') {
186
    $variables['attributes']['role'] = 'navigation';
187 188
  }
}
189

190 191 192 193 194 195 196
/**
 * 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) {
197
  $statistics_count_content_views = \Drupal::config('statistics.settings')->get('count_content_views');
198 199 200 201
  if (empty($statistics_count_content_views)) {
    unset($definitions['statistics_popular_block']);
  }
}