tracker.module 13.2 KB
Newer Older
1 2
<?php

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\node\NodeInterface;
11
use Drupal\Core\Session\AccountInterface;
12

Dries's avatar
Dries committed
13
/**
14
 * Implements hook_help().
Dries's avatar
Dries committed
15
 */
16 17
function tracker_help($path, $arg) {
  switch ($path) {
18
    case 'admin/help#tracker':
19
      $output = '<h3>' . t('About') . '</h3>';
20
      $output .= '<p>' . t('The 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 online handbook entry for <a href="@tracker">Tracker module</a>.', array('@tracker' => 'http://drupal.org/documentation/modules/tracker')) . '</p>';
21 22
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
23 24
      $output .= '<dt>' . t('Tracker navigation') . '</dt>';
      $output .= '<dd>' . t('The Tracker module adds a new menu item to the Tools menu, called <em>Recent content</em>. You can configure menu items via the <a href="@menus">Menus administration page</a>.', array('@menus' => url('admin/structure/menu'))) . '</dd>';
25 26 27 28 29
      $output .= '<dt>' . t('Tracking new and updated site content') . '</dt>';
      $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.", array('@recent' => url('tracker'))) . '</dd>';
      $output .= '<dt>' . t('Tracking user-specific content') . '</dt>';
      $output .= '<dd>' . t("To follow a specific user's new and updated content, select the <em>Track</em> tab from the user's profile page.") . '</dd>';
      $output .= '</dl>';
30
      return $output;
31
  }
32 33
}

34
/**
35
 * Implements hook_cron().
36
 *
37 38
 * Updates tracking information for any items still to be tracked. The state
 * '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 42
 */
function tracker_cron() {
43
  $state = \Drupal::state();
44
  $max_nid = $state->get('tracker.index_nid') ?: 0;
45
  if ($max_nid > 0) {
46
    $batch_size = \Drupal::config('tracker.settings')->get('cron_index_limit');
47
    $last_nid = FALSE;
48 49 50
    // @todo This should be actually filtering on the desired language and just
    //   fall back to the default language.
    $result = db_query_range('SELECT nid, uid, status FROM {node_field_data} WHERE nid <= :max_nid AND default_langcode = 1 ORDER BY nid DESC', 0, $batch_size, array(':max_nid' => $max_nid), array('target' => 'slave'));
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84

    $count = 0;

    foreach ($result as $row) {
      // Calculate the changed timestamp for this node.
      $changed = _tracker_calculate_changed($row->nid);

      // Remove existing data for this node.
      db_delete('tracker_node')
        ->condition('nid', $row->nid)
        ->execute();
      db_delete('tracker_user')
        ->condition('nid', $row->nid)
        ->execute();

      // Insert the node-level data.
      db_insert('tracker_node')
        ->fields(array(
          'nid' => $row->nid,
          'published' => $row->status,
          'changed' => $changed,
        ))
        ->execute();

      // Insert the user-level data for the node's author.
      db_insert('tracker_user')
        ->fields(array(
          'nid' => $row->nid,
          'published' => $row->status,
          'changed' => $changed,
          'uid' => $row->uid,
        ))
        ->execute();

85
      $query = db_select('comment', 'c', array('target' => 'slave'));
86 87 88
      // Force PostgreSQL to do an implicit cast by adding 0.
      $query->addExpression('0 + :changed', 'changed', array(':changed' => $changed));
      $query->addField('c', 'status', 'published');
89
      $query->addField('c', 'entity_id', 'nid');
90 91
      $query
        ->distinct()
92 93 94
        ->fields('c', array('uid'))
        ->condition('c.entity_id', $row->nid)
        ->condition('c.entity_type', 'node')
95
        ->condition('c.uid', $row->uid, '<>')
96
        ->condition('c.status', CommentInterface::PUBLISHED);
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111

      // Insert the user-level data for the commenters (except if a commenter
      // is the node's author).
      db_insert('tracker_user')
        ->from($query)
        ->execute();

      // Note that we have indexed at least one node.
      $last_nid = $row->nid;

      $count++;
    }

    if ($last_nid !== FALSE) {
      // Prepare a starting point for the next run.
112
      $state->set('tracker.index_nid', $last_nid - 1);
113

114
      watchdog('tracker', 'Indexed %count content items for tracking.', array('%count' => $count));
115 116 117
    }
    else {
      // If all nodes have been indexed, set to zero to skip future cron runs.
118
      $state->set('tracker.index_nid', 0);
119 120 121 122 123
    }
  }
}

/**
124 125 126 127 128 129 130 131 132 133
 * Access callback: Determines access permission for a user's own account.
 *
 * @param int $account
 *   The account ID to check.
 *
 * @return boolean
 *   TRUE if a user is accessing tracking info for their own account and
 *   has permission to access the content.
 *
 * @see tracker_menu()
134
 */
135
function _tracker_myrecent_access(AccountInterface $account) {
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
}

/**
141 142 143 144 145 146 147 148 149 150
 * Access callback: Determines access permission for an account.
 *
 * @param int $account
 *   The user account ID to track.
 *
 * @return boolean
 *   TRUE if a user has permission to access the account for $account and
 *   has permission to access the content.
 *
 * @see tracker_menu()
151 152
 */
function _tracker_user_access($account) {
153
  return $account->access('view') && $account->hasPermission('access content');
154 155
}

156
/**
157
 * Implements hook_node_insert().
158 159
 *
 * Adds new tracking information for this node since it's new.
160
 */
161
function tracker_node_insert(NodeInterface $node, $arg = 0) {
162
  _tracker_add($node->id(), $node->getOwnerId(), $node->getChangedTime());
163 164 165
}

/**
166
 * Implements hook_node_update().
167 168
 *
 * Adds tracking information for this node since it's been updated.
169
 */
170
function tracker_node_update(NodeInterface $node, $arg = 0) {
171
  _tracker_add($node->id(), $node->getOwnerId(), $node->getChangedTime());
172 173 174
}

/**
175
 * Implements hook_node_predelete().
176 177
 *
 * Deletes tracking information for a node.
178
 */
179
function tracker_node_predelete(EntityInterface $node, $arg = 0) {
180
  db_delete('tracker_node')
181
    ->condition('nid', $node->id())
182 183
    ->execute();
  db_delete('tracker_user')
184
    ->condition('nid', $node->id())
185
    ->execute();
186 187 188
}

/**
189
 * Implements hook_comment_update().
190 191 192 193
 *
 * Comment module doesn't call hook_comment_unpublish() when saving individual
 * comments so we need to check for those here.
 */
194
function tracker_comment_update(CommentInterface $comment) {
195
  // $comment->save() calls hook_comment_publish() for all published comments
196
  // so we need to handle all other values here.
197 198
  if (!$comment->isPublished() && $comment->getCommentedEntityTypeId() == 'node') {
    _tracker_remove($comment->getCommentedEntityId(), $comment->getOwnerId(), $comment->getChangedTime());
199 200 201 202
  }
}

/**
203
 * Implements hook_comment_publish().
204 205
 *
 * This actually handles the insert and update of published nodes since
206
 * $comment->save() calls hook_comment_publish() for all published comments.
207
 */
208
function tracker_comment_publish(CommentInterface $comment) {
209 210
  if ($comment->getCommentedEntityTypeId() == 'node') {
    _tracker_add($comment->getCommentedEntityId(), $comment->getOwnerId(), $comment->getChangedTime());
211
  }
212 213 214
}

/**
215
 * Implements hook_comment_unpublish().
216
 */
217
function tracker_comment_unpublish(CommentInterface $comment) {
218 219
  if ($comment->getCommentedEntityTypeId() == 'node') {
    _tracker_remove($comment->getCommentedEntityId(), $comment->getOwnerId(), $comment->getChangedTime());
220
  }
221 222 223
}

/**
224
 * Implements hook_comment_delete().
225
 */
226
function tracker_comment_delete(CommentInterface $comment) {
227 228
  if ($comment->getCommentedEntityTypeId() == 'node') {
    _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 236 237 238 239 240 241 242
 *
 * @param $nid
 *   A node ID.
 * @param $uid
 *   The node or comment author.
 * @param $changed
 *   The node updated timestamp or comment timestamp.
 */
function _tracker_add($nid, $uid, $changed) {
243 244 245
  // @todo This should be actually filtering on the desired language and just
  //   fall back to the default language.
  $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', array(':nid' => $nid))->fetchObject();
246 247 248 249 250 251 252

  // Adding a comment can only increase the changed timestamp, so our
  // calculation here is simple.
  $changed = max($node->changed, $changed);

  // Update the node-level data.
  db_merge('tracker_node')
253
    ->key('nid', $nid)
254 255 256 257 258 259 260 261
    ->fields(array(
      'changed' => $changed,
      'published' => $node->status,
    ))
    ->execute();

  // Create or update the user-level data.
  db_merge('tracker_user')
262
    ->keys(array(
263 264 265 266 267 268 269 270 271 272 273
      'nid' => $nid,
      'uid' => $uid,
    ))
    ->fields(array(
      'changed' => $changed,
      'published' => $node->status,
    ))
    ->execute();
}

/**
274
 * Picks the most recent timestamp between node changed and the last comment.
275 276 277 278 279
 *
 * @param $nid
 *   A node ID.
 *
 * @return
280 281
 *  The node changed timestamp, or most recent comment timestamp, whichever is
 *  the greatest.
282 283
 */
function _tracker_calculate_changed($nid) {
284 285 286
  // @todo This should be actually filtering on the desired language and just
  //   fall back to the default language.
  $changed = db_query('SELECT changed FROM {node_field_data} WHERE nid = :nid AND default_langcode = 1 ORDER BY changed DESC', array(':nid' => $nid), array('target' => 'slave'))->fetchField();
287
  $latest_comment = db_query_range("SELECT cid, changed FROM {comment} WHERE entity_type = 'node' AND entity_id = :nid AND status = :status ORDER BY changed DESC", 0, 1, array(
288
    ':nid' => $nid,
289
    ':status' => CommentInterface::PUBLISHED,
290
  ), array('target' => 'slave'))->fetchObject();
291 292
  if ($latest_comment && $latest_comment->changed > $changed) {
    $changed = $latest_comment->changed;
293 294 295 296 297
  }
  return $changed;
}

/**
298
 * Cleans up indexed data when nodes or comments are removed.
299 300 301 302 303 304 305 306 307
 *
 * @param $nid
 *  The node ID.
 * @param $uid
 *   The author of the node or comment.
 * @param $changed
 *   The last changed timestamp of the node.
 */
function _tracker_remove($nid, $uid = NULL, $changed = NULL) {
308 309 310
  // @todo This should be actually filtering on the desired language and just
  //   fall back to the default language.
  $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', array(':nid' => $nid))->fetchObject();
311

312
  // The user only keeps their subscription if the node exists.
313
  if ($node) {
314
    // And they are the author of the node.
315 316
    $keep_subscription = ($node->uid == $uid);

317
    // Or if they have commented on the node.
318
    if (!$keep_subscription) {
319
      // Check if the user has commented at least once on the given nid.
320
      $keep_subscription = db_query_range("SELECT COUNT(*) FROM {comment} WHERE entity_type = 'node' AND entity_id = :nid AND uid = :uid AND status = :status", 0, 1, array(
321 322
        ':nid' => $nid,
        ':uid' => $uid,
323
        ':status' => CommentInterface::PUBLISHED,
324
      ))->fetchField();
325 326 327 328 329 330 331 332 333 334 335 336 337
    }

    // If we haven't found a reason to keep the user's subscription, delete it.
    if (!$keep_subscription) {
      db_delete('tracker_user')
        ->condition('nid', $nid)
        ->condition('uid', $uid)
        ->execute();
    }

    // Now we need to update the (possibly) changed timestamps for other users
    // and the node itself.
    // We only need to do this if the removed item has a timestamp that equals
338
    // or exceeds the listed changed timestamp for the node.
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
    $tracker_node = db_query('SELECT nid, changed FROM {tracker_node} WHERE nid = :nid', array(':nid' => $nid))->fetchObject();
    if ($tracker_node && $changed >= $tracker_node->changed) {
      // If we're here, the item being removed is *possibly* the item that
      // established the node's changed timestamp.

      // We just have to recalculate things from scratch.
      $changed = _tracker_calculate_changed($nid);

      // And then we push the out the new changed timestamp to our denormalized
      // tables.
      db_update('tracker_node')
        ->fields(array(
          'changed' => $changed,
          'published' => $node->status,
        ))
        ->condition('nid', $nid)
        ->execute();
      db_update('tracker_node')
        ->fields(array(
          'changed' => $changed,
          'published' => $node->status,
        ))
        ->condition('nid', $nid)
        ->execute();
363
    }
364 365 366 367 368 369 370 371 372 373 374
  }
  else {
    // If the node doesn't exist, remove everything.
    db_delete('tracker_node')
      ->condition('nid', $nid)
      ->execute();
    db_delete('tracker_user')
      ->condition('nid', $nid)
      ->execute();
  }
}