Drupal investigation

statistics.module 8.0KB

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