Using comment flags to restrict access

Last modified: May 26, 2009 - 19:34

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:

<?php
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:

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

sql error when logged out

Becky Kinney - June 29, 2009 - 02:58

I am getting a sql error when I use this snippet in a custom mod, and then log out. Apparently c.cid is an unknown column. I found some threads on similar errors, but I don't know enough about either drupal or mysql to paw my way through. Also, I'm wondering whether there is some way to allow only the author of a private comment see it. Seems this snippet relies entirely on role to determine who can and can not see the comment. Is that correct?

Also, is there a way to hide the flag from users who don't have edit permissions on the comment?

Becky Kinney

Hmm, it works for me

gcassie - June 30, 2009 - 14:02

Hmm, it works for me anonymously. I suppose it's possible some other module you have enabled is defining c.cid as a primary field? Try adding a check on the primary table, too.

This snippet does indeed rely on permissions. That's also what I'm currently using to hide the flag from people who wouldn't have edit rights. I'm sure the alter could be reworked to check for the author being the current user, or any number of other conditions. Try using the devel module's debugging commands to view the structure of the query and arguments.

 
 

Drupal is a registered trademark of Dries Buytaert.