I'd like anonymous users to be able to comment only once on a node. I thought about checking whether there's already a comment from the user's IP-adress and, if yes, hiding the comment form, but I don't know how to do that.
How can I achieve this?
Drupal Answers is a question and answer site for Drupal developers and administrators. It only takes a minute to sign up.
Sign up to join this communityYou can do this by means of two functions called flood_register_event() and flood_is_allowed().
When a anon user views a node, call flood_is_allowed
in hook_node_view
that sets COMMENT_NODE_CLOSED
for the node.
When a anon user comments, register that as a flood event in hook_comment_presave
for that particular node. By setting the $threshold
(parameter for flood_is_allowed
) to 1, the user will be stopped from commenting after the first comment is posted.
This is the bare bones of how to implement hooks that make use of these functions:
function MYMODULE_comment_presave($comment) {
global $user;
if (!$user->uid) {
flood_register_event($comment->nid);
}
}
function MYMODULE_node_view($node, $view_mode, $langcode) {
global $user;
if (!$user->uid && !flood_is_allowed($node->nid, 1)) {
// This bars the anon user from posting a second comment of the node.
// For a more sophisticated blocking method (e.g. to prevent the comment form from
// showing up), ask another question about how to do that.
$node->comment = COMMENT_NODE_CLOSED;
}
}
PS: The module Anonymous Publishing is already using this pair of functions to limit the number of comments an anonymous user can post (but not exactly in the way you specify). However, looking at the source code of that module should give you an idea about how to use this pair of functions for flood control of anonymous comments.