history.module 5.82 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Records which users have read which content.
6 7 8 9 10 11
 *
 * @todo
 * - Generic helper for _forum_user_last_visit() + history_read().
 * - Generic helper for node_mark().
 */

12
use Drupal\Core\Entity\EntityInterface;
13
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
14
use Drupal\Core\Routing\RouteMatchInterface;
15
use Drupal\user\UserInterface;
16 17 18 19 20 21 22 23 24

/**
 * Entities changed before this time are always shown as read.
 *
 * Entities changed within this time may be marked as new, updated, or read,
 * depending on their state for the current user. Defaults to 30 days ago.
 */
define('HISTORY_READ_LIMIT', REQUEST_TIME - 30 * 24 * 60 * 60);

25 26 27
/**
 * Implements hook_help().
 */
28
function history_help($route_name, RouteMatchInterface $route_match) {
29 30
  switch ($route_name) {
    case 'help.page.history':
31
      $output = '<h3>' . t('About') . '</h3>';
32
      $output .= '<p>' . t('The History module keeps track of which content a user has read. It marks content as <em>new</em> or <em>updated</em> depending on the last time the user viewed it. History records that are older than one month are removed during cron, which means that content older than one month is always considered <em>read</em>. The History module does not have a user interface but it provides a filter to <a href=":views-help">Views</a> to show new or updated content. For more information, see the <a href=":url">online documentation for the History module</a>.', [':views-help' => (\Drupal::moduleHandler()->moduleExists('views')) ? \Drupal::url('help.page', ['name' => 'views']) : '#', ':url' => 'https://www.drupal.org/documentation/modules/history']) . '</p>';
33 34 35 36
      return $output;
  }
}

37 38 39 40 41 42 43 44 45 46 47
/**
 * Retrieves the timestamp for the current user's last view of a specified node.
 *
 * @param int $nid
 *   A node ID.
 *
 * @return int
 *   If a node has been previously viewed by the user, the timestamp in seconds
 *   of when the last view occurred; otherwise, zero.
 */
function history_read($nid) {
48
  $history = history_read_multiple([$nid]);
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
  return $history[$nid];
}

/**
 * Retrieves the last viewed timestamp for each of the passed node IDs.
 *
 * @param array $nids
 *   An array of node IDs.
 *
 * @return array
 *   Array of timestamps keyed by node ID. If a node has been previously viewed
 *   by the user, the timestamp in seconds of when the last view occurred;
 *   otherwise, zero.
 */
function history_read_multiple($nids) {
64
  $history = &drupal_static(__FUNCTION__, []);
65

66
  $return = [];
67

68
  $nodes_to_read = [];
69 70 71 72 73 74 75 76 77 78 79 80
  foreach ($nids as $nid) {
    if (isset($history[$nid])) {
      $return[$nid] = $history[$nid];
    }
    else {
      // Initialize value if current user has not viewed the node.
      $nodes_to_read[$nid] = 0;
    }
  }

  if (empty($nodes_to_read)) {
    return $return;
81 82
  }

83
  $result = db_query('SELECT nid, timestamp FROM {history} WHERE uid = :uid AND nid IN ( :nids[] )', [
84
    ':uid' => \Drupal::currentUser()->id(),
85
    ':nids[]' => array_keys($nodes_to_read),
86
  ]);
87 88 89 90 91 92
  foreach ($result as $row) {
    $nodes_to_read[$row->nid] = (int) $row->timestamp;
  }
  $history += $nodes_to_read;

  return $return + $nodes_to_read;
93 94 95 96 97 98 99 100 101 102 103 104 105 106
}

/**
 * Updates 'last viewed' timestamp of the specified entity for the current user.
 *
 * @param $nid
 *   The node ID that has been read.
 * @param $account
 *   (optional) The user account to update the history for. Defaults to the
 *   current user.
 */
function history_write($nid, $account = NULL) {

  if (!isset($account)) {
107
    $account = \Drupal::currentUser();
108 109
  }

110
  if ($account->isAuthenticated()) {
111
    db_merge('history')
112
      ->keys([
113
        'uid' => $account->id(),
114
        'nid' => $nid,
115 116
      ])
      ->fields(['timestamp' => REQUEST_TIME])
117
      ->execute();
118
    // Update static cache.
119
    $history = &drupal_static('history_read_multiple', []);
120 121
    $history[$nid] = REQUEST_TIME;
  }
122 123 124 125 126 127 128 129 130 131 132
}

/**
 * Implements hook_cron().
 */
function history_cron() {
  db_delete('history')
    ->condition('timestamp', HISTORY_READ_LIMIT, '<')
    ->execute();
}

133
/**
134
 * Implements hook_ENTITY_TYPE_view_alter() for node entities.
135
 */
136
function history_node_view_alter(array &$build, EntityInterface $node, EntityViewDisplayInterface $display) {
137
  // Update the history table, stating that this user viewed this node.
138 139 140 141 142 143 144 145 146
  if ($display->getOriginalMode() === 'full') {
    $build['#cache']['contexts'][] = 'user.roles:authenticated';
    if (\Drupal::currentUser()->isAuthenticated()) {
      // When the window's "load" event is triggered, mark the node as read.
      // This still allows for Drupal behaviors (which are triggered on the
      // "DOMContentReady" event) to add "new" and "updated" indicators.
      $build['#attached']['library'][] = 'history/mark-as-read';
      $build['#attached']['drupalSettings']['history']['nodesToMarkAsRead'][$node->id()] = TRUE;
    }
147 148 149 150
  }

}

151
/**
152
 * Implements hook_ENTITY_TYPE_delete() for node entities.
153
 */
154
function history_node_delete(EntityInterface $node) {
155
  db_delete('history')
156
    ->condition('nid', $node->id())
157 158 159 160 161 162
    ->execute();
}

/**
 * Implements hook_user_cancel().
 */
163
function history_user_cancel($edit, UserInterface $account, $method) {
164 165 166
  switch ($method) {
    case 'user_cancel_reassign':
      db_delete('history')
167
        ->condition('uid', $account->id())
168 169 170 171 172 173
        ->execute();
      break;
  }
}

/**
174
 * Implements hook_ENTITY_TYPE_delete() for user entities.
175 176 177
 */
function history_user_delete($account) {
  db_delete('history')
178
    ->condition('uid', $account->id())
179 180
    ->execute();
}
181

182
/**
183
 * #lazy_builder callback; attaches the last read timestamp for a node.
184
 *
185 186
 * @param int $node_id
 *   The node ID for which to attach the last read timestamp.
187
 *
188
 * @return array
189
 *   A renderable array containing the last read timestamp.
190
 */
191 192
function history_attach_timestamp($node_id) {
  $element = [];
193
  $element['#attached']['drupalSettings']['history']['lastReadTimestamps'][$node_id] = (int) history_read($node_id);
194 195
  return $element;
}