bf40dc1e8dc742115b1e6d1be6c3c9de4807bd8b
[yaffs-website] / web / core / modules / tracker / tracker.module
1 <?php
2
3 /**
4  * @file
5  * Tracks recent content posted by a user or users.
6  */
7
8 use Drupal\Core\Entity\EntityInterface;
9 use Drupal\comment\CommentInterface;
10 use Drupal\Core\Routing\RouteMatchInterface;
11 use Drupal\node\Entity\Node;
12 use Drupal\node\NodeInterface;
13 use Drupal\Core\Session\AccountInterface;
14
15 /**
16  * Implements hook_help().
17  */
18 function tracker_help($route_name, RouteMatchInterface $route_match) {
19   switch ($route_name) {
20     case 'help.page.tracker':
21       $output = '<h3>' . t('About') . '</h3>';
22       $output .= '<p>' . t('The Activity Tracker module displays the most recently added and updated content on your site, and allows you to follow new content created by each user. This module has no configuration options. For more information, see the <a href=":tracker">online documentation for the Activity Tracker module</a>.', [':tracker' => 'https://www.drupal.org/documentation/modules/tracker']) . '</p>';
23       $output .= '<h3>' . t('Uses') . '</h3>';
24       $output .= '<dl>';
25       $output .= '<dt>' . t('Tracking new and updated site content') . '</dt>';
26       $output .= '<dd>' . t('The <a href=":recent">Recent content</a> page shows new and updated content in reverse chronological order, listing the content type, title, author\'s name, number of comments, and time of last update. Content is considered updated when changes occur in the text, or when new comments are added. The <em>My recent content</em> tab limits the list to the currently logged-in user.', [':recent' => \Drupal::url('tracker.page')]) . '</dd>';
27       $output .= '<dt>' . t('Tracking user-specific content') . '</dt>';
28       $output .= '<dd>' . t("To follow a specific user's new and updated content, select the <em>Activity</em> tab from the user's profile page.") . '</dd>';
29       $output .= '</dl>';
30       return $output;
31   }
32 }
33
34 /**
35  * Implements hook_cron().
36  *
37  * Updates tracking information for any items still to be tracked. The state
38  * 'tracker.index_nid' is set to ((the last node ID that was indexed) - 1) and
39  * used to select the nodes to be processed. If there are no remaining nodes to
40  * process, 'tracker.index_nid' will be 0.
41  * This process does not run regularly on live sites, rather it updates tracking
42  * info once on an existing site just after the tracker module was installed.
43  */
44 function tracker_cron() {
45   $state = \Drupal::state();
46   $max_nid = $state->get('tracker.index_nid') ?: 0;
47   if ($max_nid > 0) {
48     $last_nid = FALSE;
49     $count = 0;
50
51     $nids = \Drupal::entityQuery('node')
52       ->condition('nid', $max_nid, '<=')
53       ->sort('nid', 'DESC')
54       ->range(0, \Drupal::config('tracker.settings')->get('cron_index_limit'))
55       ->execute();
56
57     $nodes = Node::loadMultiple($nids);
58     foreach ($nodes as $nid => $node) {
59
60       // Calculate the changed timestamp for this node.
61       $changed = _tracker_calculate_changed($node);
62
63       // Remove existing data for this node.
64       db_delete('tracker_node')
65         ->condition('nid', $nid)
66         ->execute();
67       db_delete('tracker_user')
68         ->condition('nid', $nid)
69         ->execute();
70
71       // Insert the node-level data.
72       db_insert('tracker_node')
73         ->fields([
74           'nid' => $nid,
75           'published' => $node->isPublished(),
76           'changed' => $changed,
77         ])
78         ->execute();
79
80       // Insert the user-level data for the node's author.
81       db_insert('tracker_user')
82         ->fields([
83           'nid' => $nid,
84           'published' => $node->isPublished(),
85           'changed' => $changed,
86           'uid' => $node->getOwnerId(),
87         ])
88         ->execute();
89
90       // Insert the user-level data for the commenters (except if a commenter
91       // is the node's author).
92
93       // Get unique user IDs via entityQueryAggregate because it's the easiest
94       // database agnostic way. We don't actually care about the comments here
95       // so don't add an aggregate field.
96       $result = \Drupal::entityQueryAggregate('comment')
97         ->condition('entity_type', 'node')
98         ->condition('entity_id', $node->id())
99         ->condition('uid', $node->getOwnerId(), '<>')
100         ->condition('status', CommentInterface::PUBLISHED)
101         ->groupBy('uid')
102         ->execute();
103       if ($result) {
104         $query = db_insert('tracker_user');
105         foreach ($result as $row) {
106           $query->fields([
107             'uid' => $row['uid'],
108             'nid' => $nid,
109             'published' => CommentInterface::PUBLISHED,
110             'changed' => $changed,
111           ]);
112         }
113         $query->execute();
114       }
115
116       // Note that we have indexed at least one node.
117       $last_nid = $nid;
118
119       $count++;
120     }
121
122     if ($last_nid !== FALSE) {
123       // Prepare a starting point for the next run.
124       $state->set('tracker.index_nid', $last_nid - 1);
125
126       \Drupal::logger('tracker')->notice('Indexed %count content items for tracking.', ['%count' => $count]);
127     }
128     else {
129       // If all nodes have been indexed, set to zero to skip future cron runs.
130       $state->set('tracker.index_nid', 0);
131     }
132   }
133 }
134
135 /**
136  * Access callback: Determines access permission for a user's own account.
137  *
138  * @deprecated in Drupal 8.4.0 and will be removed before Drupal 9.0.0. As
139  *   internal API, _tracker_user_access() may also be removed in a minor
140  *   release.
141  *
142  * @internal
143  *
144  * @param \Drupal\Core\Session\AccountInterface $account
145  *   The user account to track.
146  *
147  * @return bool
148  *   TRUE if a user is accessing tracking info for their own account and
149  *   has permission to access the content.
150  */
151 function _tracker_myrecent_access(AccountInterface $account) {
152   @trigger_error('_tracker_myrecent_access() is deprecated in Drupal 8.4.0 and will be removed before Drupal 9.0.0.', E_USER_DEPRECATED);
153   // This path is only allowed for authenticated users looking at their own content.
154   return $account->id() && (\Drupal::currentUser()->id() == $account->id()) && $account->hasPermission('access content');
155 }
156
157 /**
158  * Access callback: Determines access permission for an account.
159  *
160  * @deprecated in Drupal 8.4.0 and will be removed before Drupal 9.0.0. As
161  *   internal API, _tracker_user_access() may also be removed in a minor
162  *   release.
163  *
164  * @internal
165  *
166  * @param int $account
167  *   The user account ID to track.
168  *
169  * @return bool
170  *   TRUE if a user has permission to access the account for $account and
171  *   has permission to access the content.
172  */
173 function _tracker_user_access($account) {
174   @trigger_error('_tracker_user_access() is deprecated in Drupal 8.4.0 and will be removed before Drupal 9.0.0.', E_USER_DEPRECATED);
175   return $account->access('view') && $account->hasPermission('access content');
176 }
177
178 /**
179  * Implements hook_ENTITY_TYPE_insert() for node entities.
180  *
181  * Adds new tracking information for this node since it's new.
182  */
183 function tracker_node_insert(NodeInterface $node, $arg = 0) {
184   _tracker_add($node->id(), $node->getOwnerId(), $node->getChangedTime());
185 }
186
187 /**
188  * Implements hook_ENTITY_TYPE_update() for node entities.
189  *
190  * Adds tracking information for this node since it's been updated.
191  */
192 function tracker_node_update(NodeInterface $node, $arg = 0) {
193   _tracker_add($node->id(), $node->getOwnerId(), $node->getChangedTime());
194 }
195
196 /**
197  * Implements hook_ENTITY_TYPE_predelete() for node entities.
198  *
199  * Deletes tracking information for a node.
200  */
201 function tracker_node_predelete(EntityInterface $node, $arg = 0) {
202   db_delete('tracker_node')
203     ->condition('nid', $node->id())
204     ->execute();
205   db_delete('tracker_user')
206     ->condition('nid', $node->id())
207     ->execute();
208 }
209
210 /**
211  * Implements hook_ENTITY_TYPE_update() for comment entities.
212  */
213 function tracker_comment_update(CommentInterface $comment) {
214   if ($comment->getCommentedEntityTypeId() == 'node') {
215     if ($comment->isPublished()) {
216       _tracker_add($comment->getCommentedEntityId(), $comment->getOwnerId(), $comment->getChangedTime());
217     }
218     else {
219       _tracker_remove($comment->getCommentedEntityId(), $comment->getOwnerId(), $comment->getChangedTime());
220     }
221   }
222 }
223
224 /**
225  * Implements hook_ENTITY_TYPE_insert() for comment entities.
226  */
227 function tracker_comment_insert(CommentInterface $comment) {
228   if ($comment->getCommentedEntityTypeId() == 'node' && $comment->isPublished()) {
229     _tracker_add($comment->getCommentedEntityId(), $comment->getOwnerId(), $comment->getChangedTime());
230   }
231 }
232
233 /**
234  * Implements hook_ENTITY_TYPE_delete() for comment entities.
235  */
236 function tracker_comment_delete(CommentInterface $comment) {
237   if ($comment->getCommentedEntityTypeId() == 'node') {
238     _tracker_remove($comment->getCommentedEntityId(), $comment->getOwnerId(), $comment->getChangedTime());
239   }
240 }
241
242 /**
243  * Updates indexing tables when a node is added, updated, or commented on.
244  *
245  * @param int $nid
246  *   A node ID.
247  * @param int $uid
248  *   The node or comment author.
249  * @param int $changed
250  *   The node updated timestamp or comment timestamp.
251  */
252 function _tracker_add($nid, $uid, $changed) {
253   // @todo This should be actually filtering on the desired language and just
254   //   fall back to the default language.
255   $node = db_query('SELECT nid, status, uid, changed FROM {node_field_data} WHERE nid = :nid AND default_langcode = 1 ORDER BY changed DESC, status DESC', [':nid' => $nid])->fetchObject();
256
257   // Adding a comment can only increase the changed timestamp, so our
258   // calculation here is simple.
259   $changed = max($node->changed, $changed);
260
261   // Update the node-level data.
262   db_merge('tracker_node')
263     ->key('nid', $nid)
264     ->fields([
265       'changed' => $changed,
266       'published' => $node->status,
267     ])
268     ->execute();
269
270   // Create or update the user-level data, first for the user posting.
271   db_merge('tracker_user')
272     ->keys([
273       'nid' => $nid,
274       'uid' => $uid,
275     ])
276     ->fields([
277       'changed' => $changed,
278       'published' => $node->status,
279     ])
280     ->execute();
281   // Update the times for all the other users tracking the post.
282   db_update('tracker_user')
283     ->condition('nid', $nid)
284     ->fields([
285       'changed' => $changed,
286       'published' => $node->status,
287     ])
288     ->execute();
289 }
290
291 /**
292  * Picks the most recent timestamp between node changed and the last comment.
293  *
294  * @param \Drupal\node\NodeInterface $node
295  *   The node entity.
296  *
297  * @return int
298  *   The node changed timestamp, or most recent comment timestamp, whichever is
299  *   the greatest.
300  *
301  * @todo Check if we should introduce 'language context' here, because the
302  *   callers may need different timestamps depending on the users' language?
303  */
304 function _tracker_calculate_changed($node) {
305   $changed = $node->getChangedTime();
306   $latest_comment = \Drupal::service('comment.statistics')->read([$node], 'node', FALSE);
307   if ($latest_comment && $latest_comment->last_comment_timestamp > $changed) {
308     $changed = $latest_comment->last_comment_timestamp;
309   }
310   return $changed;
311 }
312
313 /**
314  * Cleans up indexed data when nodes or comments are removed.
315  *
316  * @param int $nid
317  *   The node ID.
318  * @param int $uid
319  *   The author of the node or comment.
320  * @param int $changed
321  *   The last changed timestamp of the node.
322  */
323 function _tracker_remove($nid, $uid = NULL, $changed = NULL) {
324   $node = Node::load($nid);
325
326   // The user only keeps their subscription if the node exists.
327   if ($node) {
328     // And they are the author of the node.
329     $keep_subscription = ($node->getOwnerId() == $uid);
330
331     // Or if they have commented on the node.
332     if (!$keep_subscription) {
333       // Check if the user has commented at least once on the given nid.
334       $keep_subscription = \Drupal::entityQuery('comment')
335         ->condition('entity_type', 'node')
336         ->condition('entity_id', $nid)
337         ->condition('uid', $uid)
338         ->condition('status', CommentInterface::PUBLISHED)
339         ->range(0, 1)
340         ->count()
341         ->execute();
342     }
343
344     // If we haven't found a reason to keep the user's subscription, delete it.
345     if (!$keep_subscription) {
346       db_delete('tracker_user')
347         ->condition('nid', $nid)
348         ->condition('uid', $uid)
349         ->execute();
350     }
351
352     // Now we need to update the (possibly) changed timestamps for other users
353     // and the node itself.
354     // We only need to do this if the removed item has a timestamp that equals
355     // or exceeds the listed changed timestamp for the node.
356     $tracker_node = db_query('SELECT nid, changed FROM {tracker_node} WHERE nid = :nid', [':nid' => $nid])->fetchObject();
357     if ($tracker_node && $changed >= $tracker_node->changed) {
358       // If we're here, the item being removed is *possibly* the item that
359       // established the node's changed timestamp.
360
361       // We just have to recalculate things from scratch.
362       $changed = _tracker_calculate_changed($node);
363
364       // And then we push the out the new changed timestamp to our denormalized
365       // tables.
366       db_update('tracker_node')
367         ->fields([
368           'changed' => $changed,
369           'published' => $node->isPublished(),
370         ])
371         ->condition('nid', $nid)
372         ->execute();
373       db_update('tracker_node')
374         ->fields([
375           'changed' => $changed,
376           'published' => $node->isPublished(),
377         ])
378         ->condition('nid', $nid)
379         ->execute();
380     }
381   }
382   else {
383     // If the node doesn't exist, remove everything.
384     db_delete('tracker_node')
385       ->condition('nid', $nid)
386       ->execute();
387     db_delete('tracker_user')
388       ->condition('nid', $nid)
389       ->execute();
390   }
391 }