Backup of db before drupal security update
[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  * @param \Drupal\Core\Session\AccountInterface $account
139  *   The user account to track.
140  *
141  * @return bool
142  *   TRUE if a user is accessing tracking info for their own account and
143  *   has permission to access the content.
144  *
145  * @see tracker_menu()
146  */
147 function _tracker_myrecent_access(AccountInterface $account) {
148   // This path is only allowed for authenticated users looking at their own content.
149   return $account->id() && (\Drupal::currentUser()->id() == $account->id()) && $account->hasPermission('access content');
150 }
151
152 /**
153  * Access callback: Determines access permission for an account.
154  *
155  * @param int $account
156  *   The user account ID to track.
157  *
158  * @return bool
159  *   TRUE if a user has permission to access the account for $account and
160  *   has permission to access the content.
161  *
162  * @see tracker_menu()
163  */
164 function _tracker_user_access($account) {
165   return $account->access('view') && $account->hasPermission('access content');
166 }
167
168 /**
169  * Implements hook_ENTITY_TYPE_insert() for node entities.
170  *
171  * Adds new tracking information for this node since it's new.
172  */
173 function tracker_node_insert(NodeInterface $node, $arg = 0) {
174   _tracker_add($node->id(), $node->getOwnerId(), $node->getChangedTime());
175 }
176
177 /**
178  * Implements hook_ENTITY_TYPE_update() for node entities.
179  *
180  * Adds tracking information for this node since it's been updated.
181  */
182 function tracker_node_update(NodeInterface $node, $arg = 0) {
183   _tracker_add($node->id(), $node->getOwnerId(), $node->getChangedTime());
184 }
185
186 /**
187  * Implements hook_ENTITY_TYPE_predelete() for node entities.
188  *
189  * Deletes tracking information for a node.
190  */
191 function tracker_node_predelete(EntityInterface $node, $arg = 0) {
192   db_delete('tracker_node')
193     ->condition('nid', $node->id())
194     ->execute();
195   db_delete('tracker_user')
196     ->condition('nid', $node->id())
197     ->execute();
198 }
199
200 /**
201  * Implements hook_ENTITY_TYPE_update() for comment entities.
202  */
203 function tracker_comment_update(CommentInterface $comment) {
204   if ($comment->getCommentedEntityTypeId() == 'node') {
205     if ($comment->isPublished()) {
206       _tracker_add($comment->getCommentedEntityId(), $comment->getOwnerId(), $comment->getChangedTime());
207     }
208     else {
209       _tracker_remove($comment->getCommentedEntityId(), $comment->getOwnerId(), $comment->getChangedTime());
210     }
211   }
212 }
213
214 /**
215  * Implements hook_ENTITY_TYPE_insert() for comment entities.
216  */
217 function tracker_comment_insert(CommentInterface $comment) {
218   if ($comment->getCommentedEntityTypeId() == 'node' && $comment->isPublished()) {
219     _tracker_add($comment->getCommentedEntityId(), $comment->getOwnerId(), $comment->getChangedTime());
220   }
221 }
222
223 /**
224  * Implements hook_ENTITY_TYPE_delete() for comment entities.
225  */
226 function tracker_comment_delete(CommentInterface $comment) {
227   if ($comment->getCommentedEntityTypeId() == 'node') {
228     _tracker_remove($comment->getCommentedEntityId(), $comment->getOwnerId(), $comment->getChangedTime());
229   }
230 }
231
232 /**
233  * Updates indexing tables when a node is added, updated, or commented on.
234  *
235  * @param int $nid
236  *   A node ID.
237  * @param int $uid
238  *   The node or comment author.
239  * @param int $changed
240  *   The node updated timestamp or comment timestamp.
241  */
242 function _tracker_add($nid, $uid, $changed) {
243   // @todo This should be actually filtering on the desired language and just
244   //   fall back to the default language.
245   $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();
246
247   // Adding a comment can only increase the changed timestamp, so our
248   // calculation here is simple.
249   $changed = max($node->changed, $changed);
250
251   // Update the node-level data.
252   db_merge('tracker_node')
253     ->key('nid', $nid)
254     ->fields([
255       'changed' => $changed,
256       'published' => $node->status,
257     ])
258     ->execute();
259
260   // Create or update the user-level data, first for the user posting.
261   db_merge('tracker_user')
262     ->keys([
263       'nid' => $nid,
264       'uid' => $uid,
265     ])
266     ->fields([
267       'changed' => $changed,
268       'published' => $node->status,
269     ])
270     ->execute();
271   // Update the times for all the other users tracking the post.
272   db_update('tracker_user')
273     ->condition('nid', $nid)
274     ->fields([
275       'changed' => $changed,
276       'published' => $node->status,
277     ])
278     ->execute();
279 }
280
281 /**
282  * Picks the most recent timestamp between node changed and the last comment.
283  *
284  * @param \Drupal\node\NodeInterface $node
285  *   The node entity.
286  *
287  * @return int
288  *   The node changed timestamp, or most recent comment timestamp, whichever is
289  *   the greatest.
290  *
291  * @todo Check if we should introduce 'language context' here, because the
292  *   callers may need different timestamps depending on the users' language?
293  */
294 function _tracker_calculate_changed($node) {
295   $changed = $node->getChangedTime();
296   $latest_comment = \Drupal::service('comment.statistics')->read([$node], 'node', FALSE);
297   if ($latest_comment && $latest_comment->last_comment_timestamp > $changed) {
298     $changed = $latest_comment->last_comment_timestamp;
299   }
300   return $changed;
301 }
302
303 /**
304  * Cleans up indexed data when nodes or comments are removed.
305  *
306  * @param int $nid
307  *   The node ID.
308  * @param int $uid
309  *   The author of the node or comment.
310  * @param int $changed
311  *   The last changed timestamp of the node.
312  */
313 function _tracker_remove($nid, $uid = NULL, $changed = NULL) {
314   $node = Node::load($nid);
315
316   // The user only keeps their subscription if the node exists.
317   if ($node) {
318     // And they are the author of the node.
319     $keep_subscription = ($node->getOwnerId() == $uid);
320
321     // Or if they have commented on the node.
322     if (!$keep_subscription) {
323       // Check if the user has commented at least once on the given nid.
324       $keep_subscription = \Drupal::entityQuery('comment')
325         ->condition('entity_type', 'node')
326         ->condition('entity_id', $nid)
327         ->condition('uid', $uid)
328         ->condition('status', CommentInterface::PUBLISHED)
329         ->range(0, 1)
330         ->count()
331         ->execute();
332     }
333
334     // If we haven't found a reason to keep the user's subscription, delete it.
335     if (!$keep_subscription) {
336       db_delete('tracker_user')
337         ->condition('nid', $nid)
338         ->condition('uid', $uid)
339         ->execute();
340     }
341
342     // Now we need to update the (possibly) changed timestamps for other users
343     // and the node itself.
344     // We only need to do this if the removed item has a timestamp that equals
345     // or exceeds the listed changed timestamp for the node.
346     $tracker_node = db_query('SELECT nid, changed FROM {tracker_node} WHERE nid = :nid', [':nid' => $nid])->fetchObject();
347     if ($tracker_node && $changed >= $tracker_node->changed) {
348       // If we're here, the item being removed is *possibly* the item that
349       // established the node's changed timestamp.
350
351       // We just have to recalculate things from scratch.
352       $changed = _tracker_calculate_changed($node);
353
354       // And then we push the out the new changed timestamp to our denormalized
355       // tables.
356       db_update('tracker_node')
357         ->fields([
358           'changed' => $changed,
359           'published' => $node->isPublished(),
360         ])
361         ->condition('nid', $nid)
362         ->execute();
363       db_update('tracker_node')
364         ->fields([
365           'changed' => $changed,
366           'published' => $node->isPublished(),
367         ])
368         ->condition('nid', $nid)
369         ->execute();
370     }
371   }
372   else {
373     // If the node doesn't exist, remove everything.
374     db_delete('tracker_node')
375       ->condition('nid', $nid)
376       ->execute();
377     db_delete('tracker_user')
378       ->condition('nid', $nid)
379       ->execute();
380   }
381 }