Index: modules/comment/comment.module =================================================================== RCS file: /cvs/drupal/drupal/modules/comment/comment.module,v retrieving revision 1.503 diff -u -p -r1.503 comment.module --- modules/comment/comment.module 26 Nov 2006 23:10:29 -0000 1.503 +++ modules/comment/comment.module 28 Nov 2006 00:05:36 -0000 @@ -172,10 +172,49 @@ function comment_block($op = 'list', $de } } +/** + * Find a number of recent comments. + * + * @param $number + * (optional) The maximum number of comments to find. + * @return + * An array of comment objects each contaning all the comment's data, + * including nid, cid, subject, and timestamp, or an + * empty array if there are no recent comments visible to the current user. + */ +function comment_get_recent($number = 10) { + + // Select the $number nodes (visible to the current user) with the most recent comments. This is efficient due to the index on last_comment_timestamp. + $result = db_query_range(db_rewrite_sql("SELECT n.nid from {node_comment_statistics} n WHERE n.comment_count > 0 ORDER BY n.last_comment_timestamp DESC"), 0, $number); + + $nids = array(); + + while ($cnode = db_fetch_object($result)) { + $nids[] = $cnode->nid; + } + + $recent = array(); + + if (!empty($nids)) { + // From among the comments on the nodes selected in the first query, find the $number most recent comments. + $result = db_query_range('SELECT c.* FROM {comments} c INNER JOIN {node} n ON n.nid = c.nid WHERE c.nid IN ('. implode(',', $nids) .') AND n.status = 1 AND c.status = %d ORDER BY c.timestamp DESC', COMMENT_PUBLISHED, 0, $number); + while ($comment = db_fetch_object($result)) { + $recent[] = $comment; + } + } + return $recent; +} + +/** + * Returns a formatted list of recent comments to be displayed in the comment block. + * + * @ingroup themeable + */ function theme_comment_block() { - $result = db_query_range(db_rewrite_sql('SELECT c.nid, c.subject, c.cid, c.timestamp FROM {comments} c INNER JOIN {node} n ON n.nid = c.nid WHERE n.status = 1 AND c.status = %d ORDER BY c.timestamp DESC', 'c'), COMMENT_PUBLISHED, 0, 10); + + $recent = comment_get_recent(); $items = array(); - while ($comment = db_fetch_object($result)) { + foreach ($recent as $comment) { $items[] = l($comment->subject, 'node/'. $comment->nid, NULL, NULL, 'comment-'. $comment->cid) .'
'. t('@time ago', array('@time' => format_interval(time() - $comment->timestamp))); } return theme('item_list', $items);