wordpress anti-spam 小墙劼墨誌增强版

/

Wordpress anti-spam 小墙劼墨誌增强版

Willin Kan 写的Wordpress 小墙代码在中文 Wordpress 圈广为流传,理论上可以100%屏蔽机器人提交的垃圾评论。不过,原版小墙代码评论框的 name 属性的值是固定的,最好隔一段时间手动修改一下。

为了更加方便,劼墨誌对原版小墙代码做了下修改,将原代码利用 output buffering 改变 comment field 变更为利用 wordpress filter 实现,提升了效率,同时,评论框的 name 属性的值采用更加难以揣度的加密字符串,并且每24小时改变一次。这样,小墙就更加给力了。

//the wall for antispam
class anti_spam {
    private $salt = 'U8kNWre0vHUH5'; // change it first when using

    public function anti_spam() {
        if ( !is_user_logged_in() ) {
            add_filter('comment_form_defaults', array($this, 'custom_comment_form'), 1);
            add_action('pre_comment_on_post', array($this, 'gate'), 1);
            add_action('preprocess_comment', array($this, 'sink'), 1);
        }
    }

    public function generate_secret() {
        $expire = strtotime("+1 day 1:17:33");
        $md5 = base64_encode(md5($this->salt.$expire, true));
        $md5 = strtr($md5, '+/', '-_');
        $md5 = str_replace('=', '', $md5);
        return $md5;
    }

    public function custom_comment_form($defaults) {
        $defaults['comment_field'] = '<p class="comment-form-comment"><label for="comment">Comment</label><textarea id="comment" name="' . $this->generate_secret() . '" cols="45" rows="8" aria-required="true"></textarea><textarea name="comment" cols="45" rows="4" style="display:none"></textarea></p>';
        return $defaults;
    }

    public function gate() {
        $secret = $this->generate_secret();
        ( !empty($_POST[$secret]) && empty($_POST['comment']) ) ? $_POST['comment'] = $_POST[$secret] : $_POST['spam_confirmed'] = 1;
    }

    public function sink( $comment ) {
        if ( !empty($_POST['spam_confirmed']) ) {
            $is_ping = in_array( $comment['comment_type'], array('pingback', 'trackback') );
            if(!$is_ping) {
                die();
            }
        }
        return $comment;
    }
}
$anti_spam = new anti_spam();

Comments