tracker.module 13 KB

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