statistics.module 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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' => Url::fromRoute('statistics.settings')->toString(), ':blocks' => (\Drupal::moduleHandler()->moduleExists('block')) ? Url::fromRoute('block.admin_display')->toString() : '#']) . '</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' => Url::fromRoute('statistics.settings')->toString(), ':permissions' => Url::fromRoute('user.admin_permissions', [], ['fragment' => 'module-statistics'])->toString()]) . '</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. * @deprecated in drupal:8.6.0 and is removed from drupal:9.0.0.
  89. * Use \Drupal\statistics\NodeStatisticsDatabaseStorage::fetchAll() instead.
  90. */
  91. function statistics_title_list($dbfield, $dbrows) {
  92. @trigger_error('statistics_title_list() is deprecated in Drupal 8.6.0 and will be removed before Drupal 9.0.0. Use \Drupal\statistics\NodeStatisticsDatabaseStorage::fetchAll() instead.', E_USER_DEPRECATED);
  93. if (in_array($dbfield, ['totalcount', 'daycount', 'timestamp'])) {
  94. $query = \Drupal::database()->select('node_field_data', 'n');
  95. $query->addTag('node_access');
  96. $query->join('node_counter', 's', 'n.nid = s.nid');
  97. $query->join('users_field_data', 'u', 'n.uid = u.uid');
  98. return $query
  99. ->fields('n', ['nid', 'title'])
  100. ->fields('u', ['uid', 'name'])
  101. ->condition($dbfield, 0, '<>')
  102. ->condition('n.status', 1)
  103. // @todo This should be actually filtering on the desired node status
  104. // field language and just fall back to the default language.
  105. ->condition('n.default_langcode', 1)
  106. ->condition('u.default_langcode', 1)
  107. ->orderBy($dbfield, 'DESC')
  108. ->range(0, $dbrows)
  109. ->execute();
  110. }
  111. return FALSE;
  112. }
  113. /**
  114. * Retrieves a node's "view statistics".
  115. *
  116. * @deprecated in drupal:8.2.0 and is removed from drupal:9.0.0. Use
  117. * \Drupal::service('statistics.storage.node')->fetchView($id) instead.
  118. *
  119. * @see https://www.drupal.org/node/2778245
  120. */
  121. function statistics_get($id) {
  122. @trigger_error("statistics_get() is deprecated in drupal:8.2.0 and is removed from drupal:9.0.0. Use Drupal::service('statistics.storage.node')->fetchView() instead. See https://www.drupal.org/node/2778245", E_USER_DEPRECATED);
  123. if ($id > 0) {
  124. /** @var \Drupal\statistics\StatisticsViewsResult $statistics */
  125. $statistics = \Drupal::service('statistics.storage.node')->fetchView($id);
  126. // For backwards compatibility, return FALSE if an invalid node ID was
  127. // passed in.
  128. if (!($statistics instanceof StatisticsViewsResult)) {
  129. return FALSE;
  130. }
  131. return [
  132. 'totalcount' => $statistics->getTotalCount(),
  133. 'daycount' => $statistics->getDayCount(),
  134. 'timestamp' => $statistics->getTimestamp(),
  135. ];
  136. }
  137. }
  138. /**
  139. * Implements hook_ENTITY_TYPE_predelete() for node entities.
  140. */
  141. function statistics_node_predelete(EntityInterface $node) {
  142. // Clean up statistics table when node is deleted.
  143. $id = $node->id();
  144. return \Drupal::service('statistics.storage.node')->deleteViews($id);
  145. }
  146. /**
  147. * Implements hook_ranking().
  148. */
  149. function statistics_ranking() {
  150. if (\Drupal::config('statistics.settings')->get('count_content_views')) {
  151. return [
  152. 'views' => [
  153. 'title' => t('Number of views'),
  154. 'join' => [
  155. 'type' => 'LEFT',
  156. 'table' => 'node_counter',
  157. 'alias' => 'node_counter',
  158. 'on' => 'node_counter.nid = i.sid',
  159. ],
  160. // Inverse law that maps the highest view count on the site to 1 and 0
  161. // to 0. Note that the ROUND here is necessary for PostgreSQL and SQLite
  162. // in order to ensure that the :statistics_scale argument is treated as
  163. // a numeric type, because the PostgreSQL PDO driver sometimes puts
  164. // values in as strings instead of numbers in complex expressions like
  165. // this.
  166. 'score' => '2.0 - 2.0 / (1.0 + node_counter.totalcount * (ROUND(:statistics_scale, 4)))',
  167. 'arguments' => [':statistics_scale' => \Drupal::state()->get('statistics.node_counter_scale') ?: 0],
  168. ],
  169. ];
  170. }
  171. }
  172. /**
  173. * Implements hook_preprocess_HOOK() for block templates.
  174. */
  175. function statistics_preprocess_block(&$variables) {
  176. if ($variables['configuration']['provider'] == 'statistics') {
  177. $variables['attributes']['role'] = 'navigation';
  178. }
  179. }
  180. /**
  181. * Implements hook_block_alter().
  182. *
  183. * Removes the "popular" block from display if the module is not configured
  184. * to count content views.
  185. */
  186. function statistics_block_alter(&$definitions) {
  187. $statistics_count_content_views = \Drupal::config('statistics.settings')->get('count_content_views');
  188. if (empty($statistics_count_content_views)) {
  189. unset($definitions['statistics_popular_block']);
  190. }
  191. }