Using comment flags to restrict access

Last updated on
30 April 2025

You can use comment flags to control who has rights to view a comment. In this example, assume an access private comments permission has been defined, and that the flag is a global comment flag called public. The system's comments are unflagged as public by default; that is, they must be explicitly made public, so anything that isn't flagged is considered private.

Then you just need to implement hook_db_rewrite_sql in a custom module:

function modulename_db_rewrite_sql($query, $primary_table, $primary_field, $args) {
  if ($primary_field == 'cid' && !user_access('access private comments')) {
    $return = array();
    $return['join'] = "INNER JOIN {flag_counts} fc ON c.cid = fc.content_id INNER JOIN {flags} f ON f.fid = fc.fid";
    $return['where'] = "fc.content_type = 'comment' AND f.name = 'public' AND fc.count > 0";
    return $return;
  }
}

Now the query that pulls comments will only pull publicly flagged comments if the current user doesn't have rights to access private ones.

If you are using a phptemplate-based theme, you can add this to your preprocess_comment hook to get a private/public class assigned to your comments for use in your css:

  $public = flag_get_counts('comment', $vars['comment']->cid);
  $classes[] = ($public['public'] ? 'public-comment' : 'private-comment'); 

Help improve this page

Page status: Not set

You can: