tracker.module 13 KB

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