Skip to content
statistics.module 9.84 KiB
Newer Older
Dries Buytaert's avatar
 
Dries Buytaert committed
/**
 * @file
 * Logs and displays content statistics for a site.
Dries Buytaert's avatar
 
Dries Buytaert committed
 */

use Drupal\Core\Entity\EntityInterface;
use Drupal\entity\Entity\EntityDisplay;
Dries Buytaert's avatar
 
Dries Buytaert committed
/**
Dries Buytaert's avatar
 
Dries Buytaert committed
 */
function statistics_help($path, $arg) {
  switch ($path) {
Dries Buytaert's avatar
 
Dries Buytaert committed
    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>';
    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>';
Dries Buytaert's avatar
 
Dries Buytaert committed
/**
Dries Buytaert's avatar
 
Dries Buytaert committed
 */
function statistics_permission() {
    'administer statistics' => array(
      'title' => t('Administer statistics'),
      'title' => t('View content hits'),
Dries Buytaert's avatar
 
Dries Buytaert committed
/**
Dries Buytaert's avatar
 
Dries Buytaert committed
 */
function statistics_node_view(EntityInterface $node, EntityDisplay $display, $view_mode) {
  if (!$node->isNew() && $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->id()), '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 (Drupal::currentUser()->hasPermission('view post access counter')) {
      $statistics = statistics_get($node->id());
        $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')),
        );
Dries Buytaert's avatar
 
Dries Buytaert committed
/**
Dries Buytaert's avatar
 
Dries Buytaert committed
 */
  $items['admin/config/system/statistics'] = array(
    'description' => 'Control details about what and how your site logs content statistics.',
    'route_name' => 'statistics.settings',
    'access arguments' => array('administer statistics'),
Dries Buytaert's avatar
 
Dries Buytaert committed
  return $items;
}

Dries Buytaert's avatar
 
Dries Buytaert committed
/**
Dries Buytaert's avatar
 
Dries Buytaert committed
 */
function statistics_cron() {
  $statistics_timestamp = \Drupal::state()->get('statistics.day_timestamp') ?: 0;
  if ((REQUEST_TIME - $statistics_timestamp) >= 86400) {
    db_update('node_counter')
      ->fields(array('daycount' => 0))
      ->execute();
    \Drupal::state()->set('statistics.day_timestamp', REQUEST_TIME);
Dries Buytaert's avatar
 
Dries Buytaert committed
/**
 * Returns the most viewed content of all time, today, or the last-viewed node.
Dries Buytaert's avatar
 
Dries Buytaert committed
 *
 * @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 Buytaert's avatar
 
Dries Buytaert committed
 *
 * @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 Buytaert's avatar
 
Dries Buytaert committed
 */
function statistics_title_list($dbfield, $dbrows) {
  if (in_array($dbfield, array('totalcount', 'daycount', 'timestamp'))) {
    $query = db_select('node_field_data', '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)
      // @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)
      ->orderBy($dbfield, 'DESC')
      ->range(0, $dbrows)
      ->execute();
Dries Buytaert's avatar
 
Dries Buytaert committed

Dries Buytaert's avatar
 
Dries Buytaert committed
/**
 * Retrieves a node's "view statistics".
 *
 * @param $nid
Dries Buytaert's avatar
 
Dries Buytaert committed
 *
 * @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.
Dries Buytaert's avatar
 
Dries Buytaert committed
 */
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();
Dries Buytaert's avatar
 
Dries Buytaert committed
/**
 * 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.
Dries Buytaert's avatar
 
Dries Buytaert committed
 */
function _statistics_link($path, $width = 35) {
  $title = \Drupal::service('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 />" : '');
  return $output;
Dries Buytaert's avatar
 
Dries Buytaert committed
}

function statistics_node_predelete(EntityInterface $node) {
  // clean up statistics table when node is deleted
    ->condition('nid', $node->id())
  if (\Drupal::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' => \Drupal::state()->get('statistics.node_counter_scale') ?: 0),
  \Drupal::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',
    'js' => array(
      drupal_get_path('module', 'statistics') . '/statistics.js' => array(
        'scope' => 'footer'
      ),
    ),
    'dependencies' => array(
      array('system', 'jquery'),
      array('system', 'drupal'),
      array('system', 'drupalSettings'),

/**
 * 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 = \Drupal::config('statistics.settings')->get('count_content_views');
  if (empty($statistics_count_content_views)) {
    unset($definitions['statistics_popular_block']);
  }
}