history.module 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. <?php
  2. /**
  3. * @file
  4. * Records which users have read which content.
  5. *
  6. * @todo
  7. * - Generic helper for _forum_user_last_visit() + history_read().
  8. * - Generic helper for node_mark().
  9. */
  10. use Drupal\Core\Entity\EntityInterface;
  11. use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
  12. use Drupal\Core\Routing\RouteMatchInterface;
  13. /**
  14. * Entities changed before this time are always shown as read.
  15. *
  16. * Entities changed within this time may be marked as new, updated, or read,
  17. * depending on their state for the current user. Defaults to 30 days ago.
  18. */
  19. define('HISTORY_READ_LIMIT', REQUEST_TIME - 30 * 24 * 60 * 60);
  20. /**
  21. * Implements hook_help().
  22. */
  23. function history_help($route_name, RouteMatchInterface $route_match) {
  24. switch ($route_name) {
  25. case 'help.page.history':
  26. $output = '<h3>' . t('About') . '</h3>';
  27. $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>';
  28. return $output;
  29. }
  30. }
  31. /**
  32. * Retrieves the timestamp for the current user's last view of a specified node.
  33. *
  34. * @param int $nid
  35. * A node ID.
  36. *
  37. * @return int
  38. * If a node has been previously viewed by the user, the timestamp in seconds
  39. * of when the last view occurred; otherwise, zero.
  40. */
  41. function history_read($nid) {
  42. $history = history_read_multiple([$nid]);
  43. return $history[$nid];
  44. }
  45. /**
  46. * Retrieves the last viewed timestamp for each of the passed node IDs.
  47. *
  48. * @param array $nids
  49. * An array of node IDs.
  50. *
  51. * @return array
  52. * Array of timestamps keyed by node ID. If a node has been previously viewed
  53. * by the user, the timestamp in seconds of when the last view occurred;
  54. * otherwise, zero.
  55. */
  56. function history_read_multiple($nids) {
  57. $history = &drupal_static(__FUNCTION__, []);
  58. $return = [];
  59. $nodes_to_read = [];
  60. foreach ($nids as $nid) {
  61. if (isset($history[$nid])) {
  62. $return[$nid] = $history[$nid];
  63. }
  64. else {
  65. // Initialize value if current user has not viewed the node.
  66. $nodes_to_read[$nid] = 0;
  67. }
  68. }
  69. if (empty($nodes_to_read)) {
  70. return $return;
  71. }
  72. $result = db_query('SELECT nid, timestamp FROM {history} WHERE uid = :uid AND nid IN ( :nids[] )', [
  73. ':uid' => \Drupal::currentUser()->id(),
  74. ':nids[]' => array_keys($nodes_to_read),
  75. ]);
  76. foreach ($result as $row) {
  77. $nodes_to_read[$row->nid] = (int) $row->timestamp;
  78. }
  79. $history += $nodes_to_read;
  80. return $return + $nodes_to_read;
  81. }
  82. /**
  83. * Updates 'last viewed' timestamp of the specified entity for the current user.
  84. *
  85. * @param $nid
  86. * The node ID that has been read.
  87. * @param $account
  88. * (optional) The user account to update the history for. Defaults to the
  89. * current user.
  90. */
  91. function history_write($nid, $account = NULL) {
  92. if (!isset($account)) {
  93. $account = \Drupal::currentUser();
  94. }
  95. if ($account->isAuthenticated()) {
  96. db_merge('history')
  97. ->keys([
  98. 'uid' => $account->id(),
  99. 'nid' => $nid,
  100. ])
  101. ->fields(['timestamp' => REQUEST_TIME])
  102. ->execute();
  103. // Update static cache.
  104. $history = &drupal_static('history_read_multiple', []);
  105. $history[$nid] = REQUEST_TIME;
  106. }
  107. }
  108. /**
  109. * Implements hook_cron().
  110. */
  111. function history_cron() {
  112. db_delete('history')
  113. ->condition('timestamp', HISTORY_READ_LIMIT, '<')
  114. ->execute();
  115. }
  116. /**
  117. * Implements hook_ENTITY_TYPE_view_alter() for node entities.
  118. */
  119. function history_node_view_alter(array &$build, EntityInterface $node, EntityViewDisplayInterface $display) {
  120. // Update the history table, stating that this user viewed this node.
  121. if ($display->getOriginalMode() === 'full') {
  122. $build['#cache']['contexts'][] = 'user.roles:authenticated';
  123. if (\Drupal::currentUser()->isAuthenticated()) {
  124. // When the window's "load" event is triggered, mark the node as read.
  125. // This still allows for Drupal behaviors (which are triggered on the
  126. // "DOMContentReady" event) to add "new" and "updated" indicators.
  127. $build['#attached']['library'][] = 'history/mark-as-read';
  128. $build['#attached']['drupalSettings']['history']['nodesToMarkAsRead'][$node->id()] = TRUE;
  129. }
  130. }
  131. }
  132. /**
  133. * Implements hook_ENTITY_TYPE_delete() for node entities.
  134. */
  135. function history_node_delete(EntityInterface $node) {
  136. db_delete('history')
  137. ->condition('nid', $node->id())
  138. ->execute();
  139. }
  140. /**
  141. * Implements hook_user_cancel().
  142. */
  143. function history_user_cancel($edit, $account, $method) {
  144. switch ($method) {
  145. case 'user_cancel_reassign':
  146. db_delete('history')
  147. ->condition('uid', $account->id())
  148. ->execute();
  149. break;
  150. }
  151. }
  152. /**
  153. * Implements hook_ENTITY_TYPE_delete() for user entities.
  154. */
  155. function history_user_delete($account) {
  156. db_delete('history')
  157. ->condition('uid', $account->id())
  158. ->execute();
  159. }
  160. /**
  161. * #lazy_builder callback; attaches the last read timestamp for a node.
  162. *
  163. * @param int $node_id
  164. * The node ID for which to attach the last read timestamp.
  165. *
  166. * @return array
  167. * A renderable array containing the last read timestamp.
  168. */
  169. function history_attach_timestamp($node_id) {
  170. $element = [];
  171. $element['#attached']['drupalSettings']['history']['lastReadTimestamps'][$node_id] = (int) history_read($node_id);
  172. return $element;
  173. }