tracker.module 13 KB

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