summaryrefslogtreecommitdiffstats
path: root/mycomments/utils.py
blob: 79a59610451d2d999495ff1ce6702a781eabb039 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
'''
This module contains utility methods for comments. Most deal with Akismet
interaction so it is imported unconditionally when this module is loaded.
'''
from django.conf import settings
from django.contrib.sites.models import Site
from django.utils.encoding import smart_str

from akismet import Akismet

def prepare_akismet(request, comment):
    if getattr(settings, 'AKISMET_API_KEY', None) is None:
        print "skipping Akismet check, no AKISMET_API_KEY setting"
        return (None, None)
    akismet_api = Akismet(key=settings.AKISMET_API_KEY,
            blog_url='http://%s/' % Site.objects.get_current().domain)
    if akismet_api.verify_key():
        akismet_data = {
                'comment_type': 'comment',
                'comment_author': smart_str(comment.user_name),
                'comment_author_email': smart_str(comment.user_email),
                'comment_author_url': smart_str(comment.user_url),
                'referrer':   request.META.get('HTTP_REFERER', None),
                'user_agent': request.META.get('HTTP_USER_AGENT', None),
                'user_ip':    request.META.get('REMOTE_ADDR', None),
        }
        return (akismet_api, akismet_data)
    return (None, None)

def akismet_check(request, comment):
    '''
    Check a comment to see if it is likely spam. Returns True
    if so. If your Akismet key didn't validate, return False.
    '''
    api, data = prepare_akismet(request, comment)
    if api:
        return api.comment_check(smart_str(comment.comment),
                data=data, build_data=True)
    return False

def akismet_ham(request, comment):
    api, data = prepare_akismet(request, comment)
    if api:
        api.submit_ham(smart_str(comment.comment),
                data=data, build_data=True)

def akismet_spam(request, comment):
    api, data = prepare_akismet(request, comment)
    if api:
        api.submit_spam(smart_str(comment.comment),
                data=data, build_data=True)

# vim: set ts=4 sw=4 et: