5 * Tracks recent content posted by a user or users.
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;
16 * Implements hook_help().
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>';
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>';
35 * Implements hook_cron().
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.
44 function tracker_cron() {
45 $state = \Drupal::state();
46 $max_nid = $state->get('tracker.index_nid') ?: 0;
51 $nids = \Drupal::entityQuery('node')
52 ->condition('nid', $max_nid, '<=')
54 ->range(0, \Drupal::config('tracker.settings')->get('cron_index_limit'))
57 $nodes = Node::loadMultiple($nids);
58 foreach ($nodes as $nid => $node) {
60 // Calculate the changed timestamp for this node.
61 $changed = _tracker_calculate_changed($node);
63 // Remove existing data for this node.
64 db_delete('tracker_node')
65 ->condition('nid', $nid)
67 db_delete('tracker_user')
68 ->condition('nid', $nid)
71 // Insert the node-level data.
72 db_insert('tracker_node')
75 'published' => $node->isPublished(),
76 'changed' => $changed,
80 // Insert the user-level data for the node's author.
81 db_insert('tracker_user')
84 'published' => $node->isPublished(),
85 'changed' => $changed,
86 'uid' => $node->getOwnerId(),
90 // Insert the user-level data for the commenters (except if a commenter
91 // is the node's author).
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)
104 $query = db_insert('tracker_user');
105 foreach ($result as $row) {
107 'uid' => $row['uid'],
109 'published' => CommentInterface::PUBLISHED,
110 'changed' => $changed,
116 // Note that we have indexed at least one node.
122 if ($last_nid !== FALSE) {
123 // Prepare a starting point for the next run.
124 $state->set('tracker.index_nid', $last_nid - 1);
126 \Drupal::logger('tracker')->notice('Indexed %count content items for tracking.', ['%count' => $count]);
129 // If all nodes have been indexed, set to zero to skip future cron runs.
130 $state->set('tracker.index_nid', 0);
136 * Access callback: Determines access permission for a user's own account.
138 * @param \Drupal\Core\Session\AccountInterface $account
139 * The user account to track.
142 * TRUE if a user is accessing tracking info for their own account and
143 * has permission to access the content.
145 * @see tracker_menu()
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');
153 * Access callback: Determines access permission for an account.
155 * @param int $account
156 * The user account ID to track.
159 * TRUE if a user has permission to access the account for $account and
160 * has permission to access the content.
162 * @see tracker_menu()
164 function _tracker_user_access($account) {
165 return $account->access('view') && $account->hasPermission('access content');
169 * Implements hook_ENTITY_TYPE_insert() for node entities.
171 * Adds new tracking information for this node since it's new.
173 function tracker_node_insert(NodeInterface $node, $arg = 0) {
174 _tracker_add($node->id(), $node->getOwnerId(), $node->getChangedTime());
178 * Implements hook_ENTITY_TYPE_update() for node entities.
180 * Adds tracking information for this node since it's been updated.
182 function tracker_node_update(NodeInterface $node, $arg = 0) {
183 _tracker_add($node->id(), $node->getOwnerId(), $node->getChangedTime());
187 * Implements hook_ENTITY_TYPE_predelete() for node entities.
189 * Deletes tracking information for a node.
191 function tracker_node_predelete(EntityInterface $node, $arg = 0) {
192 db_delete('tracker_node')
193 ->condition('nid', $node->id())
195 db_delete('tracker_user')
196 ->condition('nid', $node->id())
201 * Implements hook_ENTITY_TYPE_update() for comment entities.
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());
209 _tracker_remove($comment->getCommentedEntityId(), $comment->getOwnerId(), $comment->getChangedTime());
215 * Implements hook_ENTITY_TYPE_insert() for comment entities.
217 function tracker_comment_insert(CommentInterface $comment) {
218 if ($comment->getCommentedEntityTypeId() == 'node' && $comment->isPublished()) {
219 _tracker_add($comment->getCommentedEntityId(), $comment->getOwnerId(), $comment->getChangedTime());
224 * Implements hook_ENTITY_TYPE_delete() for comment entities.
226 function tracker_comment_delete(CommentInterface $comment) {
227 if ($comment->getCommentedEntityTypeId() == 'node') {
228 _tracker_remove($comment->getCommentedEntityId(), $comment->getOwnerId(), $comment->getChangedTime());
233 * Updates indexing tables when a node is added, updated, or commented on.
238 * The node or comment author.
239 * @param int $changed
240 * The node updated timestamp or comment timestamp.
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();
247 // Adding a comment can only increase the changed timestamp, so our
248 // calculation here is simple.
249 $changed = max($node->changed, $changed);
251 // Update the node-level data.
252 db_merge('tracker_node')
255 'changed' => $changed,
256 'published' => $node->status,
260 // Create or update the user-level data, first for the user posting.
261 db_merge('tracker_user')
267 'changed' => $changed,
268 'published' => $node->status,
271 // Update the times for all the other users tracking the post.
272 db_update('tracker_user')
273 ->condition('nid', $nid)
275 'changed' => $changed,
276 'published' => $node->status,
282 * Picks the most recent timestamp between node changed and the last comment.
284 * @param \Drupal\node\NodeInterface $node
288 * The node changed timestamp, or most recent comment timestamp, whichever is
291 * @todo Check if we should introduce 'language context' here, because the
292 * callers may need different timestamps depending on the users' language?
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;
304 * Cleans up indexed data when nodes or comments are removed.
309 * The author of the node or comment.
310 * @param int $changed
311 * The last changed timestamp of the node.
313 function _tracker_remove($nid, $uid = NULL, $changed = NULL) {
314 $node = Node::load($nid);
316 // The user only keeps their subscription if the node exists.
318 // And they are the author of the node.
319 $keep_subscription = ($node->getOwnerId() == $uid);
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)
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)
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.
351 // We just have to recalculate things from scratch.
352 $changed = _tracker_calculate_changed($node);
354 // And then we push the out the new changed timestamp to our denormalized
356 db_update('tracker_node')
358 'changed' => $changed,
359 'published' => $node->isPublished(),
361 ->condition('nid', $nid)
363 db_update('tracker_node')
365 'changed' => $changed,
366 'published' => $node->isPublished(),
368 ->condition('nid', $nid)
373 // If the node doesn't exist, remove everything.
374 db_delete('tracker_node')
375 ->condition('nid', $nid)
377 db_delete('tracker_user')
378 ->condition('nid', $nid)