]> git.openstreetmap.org Git - osqa.git/blob - forum_modules/akismet/startup.py
Commit for OSQA Jira 501. Minor change in syntax of Akismet can_bypass_spam_check...
[osqa.git] / forum_modules / akismet / startup.py
1 from django.utils.translation import ugettext as _
2 from django.http import HttpResponse, HttpResponseRedirect
3 from django.utils import simplejson
4 from django.utils.encoding import smart_str
5 from django.shortcuts import render_to_response
6 from forum.modules import decorate
7 from forum import views
8 from lib.akismet import Akismet
9 from forum.settings import APP_URL, OSQA_VERSION
10 from settings import WORDPRESS_API_KEY, REP_FOR_NO_SPAM_CHECK
11 from forum.models.user import User
12
13 import settings
14
15 def can_bypass_spam_check(user):
16     return user.is_authenticated and (user.is_superuser or user.is_staff or cmp(int(user.reputation), REP_FOR_NO_SPAM_CHECK) > 0)
17
18
19 def check_spam(param, comment_type):
20     def wrapper(origin, request, *args, **kwargs):
21         if request.POST and request.POST.get(param, None) and WORDPRESS_API_KEY and (not can_bypass_spam_check(
22                 request.user)):
23             comment = smart_str(request.POST[param])
24
25             data = {
26             "user_ip":request.META["REMOTE_ADDR"],
27             "user_agent":request.environ['HTTP_USER_AGENT'],
28             "comment_type": comment_type,
29             "comment":comment
30             }
31
32             if request.user.is_authenticated():
33                 data.update({
34                 "comment_author":smart_str(request.user.username),
35                 "comment_author_email":request.user.email,
36                 "comment_author_url":request.user.website,
37                 })
38
39             api = Akismet(settings.WORDPRESS_API_KEY, APP_URL, "OSQA/%s" % OSQA_VERSION)
40             if api.comment_check(comment, data):
41                 if request.is_ajax():
42                     response = {
43                     'success': False,
44                     'error_message': _("Sorry, but akismet thinks your %s is spam.") % comment_type
45                     }
46                     return HttpResponse(simplejson.dumps(response), mimetype="application/json")
47                 else:
48                     return render_to_response('modules/akismet/foundspam.html', {
49                     'action_name': comment_type
50                     })
51
52         return origin(request, *args, **kwargs)
53
54     return wrapper
55
56
57 decorate(views.writers.ask)(check_spam('text', _('question')))
58 decorate(views.writers.answer)(check_spam('text', _('answer')))
59 decorate(views.commands.comment)(check_spam('comment', _('comment')))
60
61