Updated Drupal to 8.6. This goes with the following updates because it's possible...
[yaffs-website] / web / core / modules / history / history.module
1 <?php
2
3 /**
4  * @file
5  * Records which users have read which content.
6  *
7  * @todo
8  * - Generic helper for _forum_user_last_visit() + history_read().
9  * - Generic helper for node_mark().
10  */
11
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  * Entities changed before this time are always shown as read.
19  *
20  * Entities changed within this time may be marked as new, updated, or read,
21  * depending on their state for the current user. Defaults to 30 days ago.
22  */
23 define('HISTORY_READ_LIMIT', REQUEST_TIME - 30 * 24 * 60 * 60);
24
25 /**
26  * Implements hook_help().
27  */
28 function history_help($route_name, RouteMatchInterface $route_match) {
29   switch ($route_name) {
30     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       return $output;
34   }
35 }
36
37 /**
38  * Retrieves the timestamp for the current user's last view of a specified node.
39  *
40  * @param int $nid
41  *   A node ID.
42  *
43  * @return int
44  *   If a node has been previously viewed by the user, the timestamp in seconds
45  *   of when the last view occurred; otherwise, zero.
46  */
47 function history_read($nid) {
48   $history = history_read_multiple([$nid]);
49   return $history[$nid];
50 }
51
52 /**
53  * Retrieves the last viewed timestamp for each of the passed node IDs.
54  *
55  * @param array $nids
56  *   An array of node IDs.
57  *
58  * @return array
59  *   Array of timestamps keyed by node ID. If a node has been previously viewed
60  *   by the user, the timestamp in seconds of when the last view occurred;
61  *   otherwise, zero.
62  */
63 function history_read_multiple($nids) {
64   $history = &drupal_static(__FUNCTION__, []);
65
66   $return = [];
67
68   $nodes_to_read = [];
69   foreach ($nids as $nid) {
70     if (isset($history[$nid])) {
71       $return[$nid] = $history[$nid];
72     }
73     else {
74       // Initialize value if current user has not viewed the node.
75       $nodes_to_read[$nid] = 0;
76     }
77   }
78
79   if (empty($nodes_to_read)) {
80     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   foreach ($result as $row) {
88     $nodes_to_read[$row->nid] = (int) $row->timestamp;
89   }
90   $history += $nodes_to_read;
91
92   return $return + $nodes_to_read;
93 }
94
95 /**
96  * Updates 'last viewed' timestamp of the specified entity for the current user.
97  *
98  * @param $nid
99  *   The node ID that has been read.
100  * @param $account
101  *   (optional) The user account to update the history for. Defaults to the
102  *   current user.
103  */
104 function history_write($nid, $account = NULL) {
105
106   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     $history[$nid] = REQUEST_TIME;
121   }
122 }
123
124 /**
125  * Implements hook_cron().
126  */
127 function history_cron() {
128   db_delete('history')
129     ->condition('timestamp', HISTORY_READ_LIMIT, '<')
130     ->execute();
131 }
132
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   if ($display->getOriginalMode() === 'full') {
139     $build['#cache']['contexts'][] = 'user.roles:authenticated';
140     if (\Drupal::currentUser()->isAuthenticated()) {
141       // When the window's "load" event is triggered, mark the node as read.
142       // This still allows for Drupal behaviors (which are triggered on the
143       // "DOMContentReady" event) to add "new" and "updated" indicators.
144       $build['#attached']['library'][] = 'history/mark-as-read';
145       $build['#attached']['drupalSettings']['history']['nodesToMarkAsRead'][$node->id()] = TRUE;
146     }
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     ->execute();
158 }
159
160 /**
161  * Implements hook_user_cancel().
162  */
163 function history_user_cancel($edit, UserInterface $account, $method) {
164   switch ($method) {
165     case 'user_cancel_reassign':
166       db_delete('history')
167         ->condition('uid', $account->id())
168         ->execute();
169       break;
170   }
171 }
172
173 /**
174  * Implements hook_ENTITY_TYPE_delete() for user entities.
175  */
176 function history_user_delete($account) {
177   db_delete('history')
178     ->condition('uid', $account->id())
179     ->execute();
180 }
181
182 /**
183  * #lazy_builder callback; attaches the last read timestamp for a node.
184  *
185  * @param int $node_id
186  *   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 function history_attach_timestamp($node_id) {
192   $element = [];
193   $element['#attached']['drupalSettings']['history']['lastReadTimestamps'][$node_id] = (int) history_read($node_id);
194   return $element;
195 }