statistics.module 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. <?php
  2. /**
  3. * @file
  4. * Logs and displays content statistics for a site.
  5. */
  6. use Drupal\Core\Entity\EntityInterface;
  7. use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
  8. use Drupal\Core\Routing\RouteMatchInterface;
  9. use Drupal\Core\Url;
  10. use Drupal\node\NodeInterface;
  11. use Drupal\statistics\StatisticsViewsResult;
  12. /**
  13. * Implements hook_help().
  14. */
  15. function statistics_help($route_name, RouteMatchInterface $route_match) {
  16. switch ($route_name) {
  17. case 'help.page.statistics':
  18. $output = '';
  19. $output .= '<h3>' . t('About') . '</h3>';
  20. $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 <a href=":statistics_do">online documentation for the Statistics module</a>.', [':statistics_do' => 'https://www.drupal.org/documentation/modules/statistics/']) . '</p>';
  21. $output .= '<h3>' . t('Uses') . '</h3>';
  22. $output .= '<dl>';
  23. $output .= '<dt>' . t('Displaying popular content') . '</dt>';
  24. $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 page</a>, and then you can enable and configure the block on the <a href=":blocks">Block layout page</a>.', [':statistics-settings' => \Drupal::url('statistics.settings'), ':blocks' => (\Drupal::moduleHandler()->moduleExists('block')) ? \Drupal::url('block.admin_display') : '#']) . '</dd>';
  25. $output .= '<dt>' . t('Page view counter') . '</dt>';
  26. $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 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.', [':statistics-settings' => \Drupal::url('statistics.settings'), ':permissions' => \Drupal::url('user.admin_permissions', [], ['fragment' => 'module-statistics'])]) . '</dd>';
  27. $output .= '</dl>';
  28. return $output;
  29. case 'statistics.settings':
  30. return '<p>' . t('Settings for the statistical information that Drupal will keep about the site.') . '</p>';
  31. }
  32. }
  33. /**
  34. * Implements hook_ENTITY_TYPE_view() for node entities.
  35. */
  36. function statistics_node_view(array &$build, EntityInterface $node, EntityViewDisplayInterface $display, $view_mode) {
  37. if (!$node->isNew() && $view_mode == 'full' && node_is_page($node) && empty($node->in_preview)) {
  38. $build['#attached']['library'][] = 'statistics/drupal.statistics';
  39. $settings = ['data' => ['nid' => $node->id()], 'url' => \Drupal::request()->getBasePath() . '/' . drupal_get_path('module', 'statistics') . '/statistics.php'];
  40. $build['#attached']['drupalSettings']['statistics'] = $settings;
  41. }
  42. }
  43. /**
  44. * Implements hook_node_links_alter().
  45. */
  46. function statistics_node_links_alter(array &$links, NodeInterface $entity, array &$context) {
  47. if ($context['view_mode'] != 'rss') {
  48. $links['#cache']['contexts'][] = 'user.permissions';
  49. if (\Drupal::currentUser()->hasPermission('view post access counter')) {
  50. $statistics = \Drupal::service('statistics.storage.node')->fetchView($entity->id());
  51. if ($statistics) {
  52. $statistics_links['statistics_counter']['title'] = \Drupal::translation()->formatPlural($statistics->getTotalCount(), '1 view', '@count views');
  53. $links['statistics'] = [
  54. '#theme' => 'links__node__statistics',
  55. '#links' => $statistics_links,
  56. '#attributes' => ['class' => ['links', 'inline']],
  57. ];
  58. }
  59. $links['#cache']['max-age'] = \Drupal::config('statistics.settings')->get('display_max_age');
  60. }
  61. }
  62. }
  63. /**
  64. * Implements hook_cron().
  65. */
  66. function statistics_cron() {
  67. $storage = \Drupal::service('statistics.storage.node');
  68. $storage->resetDayCount();
  69. $max_total_count = $storage->maxTotalCount();
  70. \Drupal::state()->set('statistics.node_counter_scale', 1.0 / max(1.0, $max_total_count));
  71. }
  72. /**
  73. * Returns the most viewed content of all time, today, or the last-viewed node.
  74. *
  75. * @param string $dbfield
  76. * The database field to use, one of:
  77. * - 'totalcount': Integer that shows the top viewed content of all time.
  78. * - 'daycount': Integer that shows the top viewed content for today.
  79. * - 'timestamp': Integer that shows only the last viewed node.
  80. * @param int $dbrows
  81. * The number of rows to be returned.
  82. *
  83. * @return SelectQuery|false
  84. * A query result containing the node ID, title, user ID that owns the node,
  85. * and the username for the selected node(s), or FALSE if the query could not
  86. * be executed correctly.
  87. */
  88. function statistics_title_list($dbfield, $dbrows) {
  89. if (in_array($dbfield, ['totalcount', 'daycount', 'timestamp'])) {
  90. $query = db_select('node_field_data', 'n');
  91. $query->addTag('node_access');
  92. $query->join('node_counter', 's', 'n.nid = s.nid');
  93. $query->join('users_field_data', 'u', 'n.uid = u.uid');
  94. return $query
  95. ->fields('n', ['nid', 'title'])
  96. ->fields('u', ['uid', 'name'])
  97. ->condition($dbfield, 0, '<>')
  98. ->condition('n.status', 1)
  99. // @todo This should be actually filtering on the desired node status
  100. // field language and just fall back to the default language.
  101. ->condition('n.default_langcode', 1)
  102. ->condition('u.default_langcode', 1)
  103. ->orderBy($dbfield, 'DESC')
  104. ->range(0, $dbrows)
  105. ->execute();
  106. }
  107. return FALSE;
  108. }
  109. /**
  110. * Retrieves a node's "view statistics".
  111. *
  112. * @deprecated in Drupal 8.2.x, will be removed before Drupal 9.0.0.
  113. * Use \Drupal::service('statistics.storage.node')->fetchView($id).
  114. */
  115. function statistics_get($id) {
  116. if ($id > 0) {
  117. /** @var \Drupal\statistics\StatisticsViewsResult $statistics */
  118. $statistics = \Drupal::service('statistics.storage.node')->fetchView($id);
  119. // For backwards compatibility, return FALSE if an invalid node ID was
  120. // passed in.
  121. if (!($statistics instanceof StatisticsViewsResult)) {
  122. return FALSE;
  123. }
  124. return [
  125. 'totalcount' => $statistics->getTotalCount(),
  126. 'daycount' => $statistics->getDayCount(),
  127. 'timestamp' => $statistics->getTimestamp(),
  128. ];
  129. }
  130. }
  131. /**
  132. * Implements hook_ENTITY_TYPE_predelete() for node entities.
  133. */
  134. function statistics_node_predelete(EntityInterface $node) {
  135. // Clean up statistics table when node is deleted.
  136. $id = $node->id();
  137. return \Drupal::service('statistics.storage.node')->deleteViews($id);
  138. }
  139. /**
  140. * Implements hook_ranking().
  141. */
  142. function statistics_ranking() {
  143. if (\Drupal::config('statistics.settings')->get('count_content_views')) {
  144. return [
  145. 'views' => [
  146. 'title' => t('Number of views'),
  147. 'join' => [
  148. 'type' => 'LEFT',
  149. 'table' => 'node_counter',
  150. 'alias' => 'node_counter',
  151. 'on' => 'node_counter.nid = i.sid',
  152. ],
  153. // Inverse law that maps the highest view count on the site to 1 and 0
  154. // to 0. Note that the ROUND here is necessary for PostgreSQL and SQLite
  155. // in order to ensure that the :statistics_scale argument is treated as
  156. // a numeric type, because the PostgreSQL PDO driver sometimes puts
  157. // values in as strings instead of numbers in complex expressions like
  158. // this.
  159. 'score' => '2.0 - 2.0 / (1.0 + node_counter.totalcount * (ROUND(:statistics_scale, 4)))',
  160. 'arguments' => [':statistics_scale' => \Drupal::state()->get('statistics.node_counter_scale') ?: 0],
  161. ],
  162. ];
  163. }
  164. }
  165. /**
  166. * Implements hook_preprocess_HOOK() for block templates.
  167. */
  168. function statistics_preprocess_block(&$variables) {
  169. if ($variables['configuration']['provider'] == 'statistics') {
  170. $variables['attributes']['role'] = 'navigation';
  171. }
  172. }
  173. /**
  174. * Implements hook_block_alter().
  175. *
  176. * Removes the "popular" block from display if the module is not configured
  177. * to count content views.
  178. */
  179. function statistics_block_alter(&$definitions) {
  180. $statistics_count_content_views = \Drupal::config('statistics.settings')->get('count_content_views');
  181. if (empty($statistics_count_content_views)) {
  182. unset($definitions['statistics_popular_block']);
  183. }
  184. }