Exemple #1
0
def is_spam(request):
    from pykismet3 import Akismet
    import os

    a = Akismet(blog_url="http://wiseinit.com",
                user_agent="WiseInit System/0.0.1")

    a.api_key = get_setting('akismet')

    check = {
        'user_ip': request.META['REMOTE_ADDR'],
        'user_agent': request.META['HTTP_USER_AGENT'],
        'referrer': request.META.get('HTTP_REFERER', 'unknown'),
        'comment_content': request.POST['comment'],
        'comment_author': request.POST['name'],
    }

    if request.POST['email'].strip():
        check['comment_author_email'] = request.POST['email']

    if request.POST['website'].strip():
        website = request.POST['website'].strip()
        if website and not re.match('https?://.+', website):
            website = 'http://' + website

        check['comment_author_url'] = website

    return a.check(check)
Exemple #2
0
    def clean_body(self):
        """
        Check spam against Akismet.

        Backported from django-contact-form pre-1.0; 1.0 dropped built-in
        Akismet support.
        """
        if 'body' in self.cleaned_data and getattr(settings, 'AKISMET_API_KEY',
                                                   None):
            try:
                akismet_api = Akismet(
                    api_key=settings.AKISMET_API_KEY,
                    blog_url='http://%s/' % Site.objects.get_current().domain,
                    user_agent='Django {}.{}.{}'.format(*django.VERSION))

                akismet_data = {
                    'user_ip': self.request.META.get('REMOTE_ADDR', ''),
                    'user_agent': self.request.META.get('HTTP_USER_AGENT', ''),
                    'referrer': self.request.META.get('HTTP_REFERER', ''),
                    'comment_content': force_bytes(self.cleaned_data['body']),
                    'comment_author': self.cleaned_data['name'],
                }
                if getattr(settings, 'AKISMET_TESTING', None):
                    # Adding test argument to the request in order to tell akismet that
                    # they should ignore the request so that test runs affect the heuristics
                    akismet_data['test'] = 1
                if akismet_api.check(akismet_data):
                    raise forms.ValidationError(
                        "Akismet thinks this message is spam")
            except AkismetServerError:
                logger.error('Akismet server error')
        return self.cleaned_data['body']
Exemple #3
0
    def clean_body(self):
        """
        Check spam against Akismet.

        Backported from django-contact-form pre-1.0; 1.0 dropped built-in
        Akismet support.
        """
        if 'body' in self.cleaned_data and getattr(settings, 'AKISMET_API_KEY', None):
            try:
                akismet_api = Akismet(
                    api_key=settings.AKISMET_API_KEY,
                    blog_url='http://%s/' % Site.objects.get_current().domain,
                    user_agent='Django {}.{}.{}'.format(*django.VERSION)
                )

                akismet_data = {
                    'user_ip': self.request.META.get('REMOTE_ADDR', ''),
                    'user_agent': self.request.META.get('HTTP_USER_AGENT', ''),
                    'referrer': self.request.META.get('HTTP_REFERER', ''),
                    'comment_content': force_bytes(self.cleaned_data['body']),
                    'comment_author': self.cleaned_data['name'],
                }
                if getattr(settings, 'AKISMET_TESTING', None):
                    # Adding test argument to the request in order to tell akismet that
                    # they should ignore the request so that test runs affect the heuristics
                    akismet_data['test'] = 1
                if akismet_api.check(akismet_data):
                    raise forms.ValidationError("Akismet thinks this message is spam")
            except AkismetServerError:
                logger.error('Akismet server error')
        return self.cleaned_data['body']
Exemple #4
0
def mark_it_spam(comment_id):
    comment = Comment.query.filter_by(
                                id=comment_id, mark_for_delete=False).first()
    if comment is None:
        response = make_response(
            jsonify({'not found': 'No such comment'}), 404)
    else:
        a = Akismet(blog_url=comment.post_url,
                    user_agent=comment.user_agent)
        a.api_key = app.config['AKISMET_API_KEY']

        a.submit_spam({'user_ip': comment.user_ip,
            'user_agent': comment.user_agent,
            'referrer': comment.referrer,
            'comment_type': comment.comment_type,
            'comment_author': comment.comment_author,
            'comment_author_email': comment.comment_author_email,
            'comment_content': comment.comment_content,
            'website': comment.website
        })
        comment.mark_for_delete = True
        db.session.commit()
        app.logger.info("The comment was submitted as spam")
        response = make_response(
            jsonify({'success': 'The comment was submitted as spam'}), 200)

    return response
Exemple #5
0
def spam_check(user_ip, user_agent, referrer, name, email, message, \
               website, post_url):

    comment_type = "comment"

    akismet_api_key = app.config['AKISMET_API_KEY']
    if not akismet_api_key:
        app.logger.info(
            "Required environment variable AKISMET_API_KEY missing")
        return (False, None)

    a = Akismet(blog_url=post_url,
                api_key=akismet_api_key,
                user_agent=user_agent)

    try:
        is_spam = a.check({'user_ip': user_ip,
            'user_agent': user_agent,
            'referrer': referrer,
            'comment_type': comment_type,
            'comment_author': name,
            'comment_author_email': email,
            'comment_content': message,
            'website': website
        })
    except AkismetError as e:
        app.logger.info(
            "Error in call to pykismet3.check(): {}".format(str(e)))
        return (False, None)

    return (True, is_spam)
Exemple #6
0
def article(request, article_id):
    a = get_object_or_404(Article, pk=article_id)

    # Check if the article is unpublished, and only show it to people with required permissions if
    # this turns out to be the case.
    if not a.published and not request.user.has_perm('mesoblog.change_article'):
        return HttpResponseForbidden()
 
    # Handle comment form submission
    if request.method == 'POST':
        if a.comments_open() is not True:
            messages.add_message(request, messages.ERROR, "Comments are now closed on this article.")
        else:
            f = CommentForm(request.POST)
            if f.is_valid():
                ak = Akismet(blog_url=request.get_host(), api_key=settings.AKISMET_API_KEY, user_agent="Mesosphere/0.0.1")
                comment = f.save(commit=False)
                ak_dict = {'user_ip': request.META['REMOTE_ADDR'],
                           'user_agent': request.META['HTTP_USER_AGENT'],
                           'referrer': request.META['HTTP_REFERER'],
                           'comment_content': f.cleaned_data['contents'],
                           'comment_author': f.cleaned_data['name'],
                          }
                if settings.DEBUG is True:
                    ak_dict['is_test'] = 1
                comment.is_spam = ak.check(ak_dict)
                comment.user_ip = request.META['REMOTE_ADDR']
                comment.user_agent = request.META['HTTP_USER_AGENT']
                comment.referer = request.META['HTTP_REFERER']

                comment.save()

                messages.add_message(request, messages.SUCCESS, 'Your comment has been posted successfully.')
                f = CommentForm(instance=Comment(article=a))
            else:
                messages.add_message(request, messages.ERROR, 'Your comment was not posted successfully.')

    else:
        f = CommentForm(instance=Comment(article=a))

    # Construct Breadcrumbs
    b = [
        Breadcrumb(name="Home",url=reverse('mesohome.views.index')),
        Breadcrumb(name="Blog",url=reverse('mesoblog.views.index')),
        Breadcrumb(name=a.primary_category.name,url=reverse('mesoblog.views.categoryFromSlug',
            args=(a.primary_category.slug,))),
        Breadcrumb(name=a.title)
    ]

    context = RequestContext(request, {
        'article': a, 
        'breadcrumbs': b,
        'comment_form': f,
        'comments_open': a.comments_open(),
    })
    return render(request, 'mesoblog/article.html', context_instance=context)
Exemple #7
0
def mark_it_valid(comment_id):
    comment = Comment.query.filter_by(
                                id=comment_id, mark_for_delete=False).first()
    if comment is None:
        response = make_response(
            jsonify({'not found': 'No such comment'}), 404)
    else:
        a = Akismet(blog_url=comment.post_url,
                    user_agent=comment.user_agent)
        a.api_key = app.config['AKISMET_API_KEY']

        a.submit_ham({'user_ip': comment.user_ip,
            'user_agent': comment.user_agent,
            'referrer': comment.referrer,
            'comment_type': comment.comment_type,
            'comment_author': comment.comment_author,
            'comment_author_email': comment.comment_author_email,
            'comment_content': comment.comment_content,
            'website': comment.website
        })

        date_str = get_current_datetime_str(comment.submit_datetime)
        name = comment.comment_author
        email = comment.comment_author_email
        website_value = comment.website
        message = comment.comment_content
        slug = comment.slug

        github_token = app.config['GITHUB_TOKEN']
        github_username = app.config['GITHUB_USERNAME']
        github_repo_name = app.config['GITHUB_REPO_NAME']

        if not create_github_pull_request(github_token, github_username, \
            github_repo_name, slug, name, message, date_str, \
            email, website_value):
            app.logger.info("Problem encountered during creation of pull request")
            response = make_response(jsonify({'error': 'Internal Error'}), 500)
        else:
            app.logger.info("Pull request created successfully")
            comment.mark_for_delete = True
            db.session.commit()
            response = make_response(
                jsonify({'success': 'The comment was submitted as valid'}), 200)

    return response
Exemple #8
0
class PykismetTestCase(unittest.TestCase):

    # create an instance of the Akismet class
    def setUp(self):

        self.akismet_client = Akismet(blog_url="http://your.blog/url",
                                      user_agent="My Awesome Web App/0.0.1",
                                      api_key="testkey")


    # test that class raises an ExtraParametersError when extra params are passed
    def test_extra_parameters(self):
        params = {'blog': 'http://your.blog/url',
                  'user_ip': '1.1.1.1',
                  'user_agent': 'My Awesome Web App/0.0.1',
                  'referrer': 'http://your.blog/url',
                  'some_extra': 'extra'
                  }

        with self.assertRaises(ExtraParametersError):
            self.akismet_client.check(params)
Exemple #9
0
   def mark_as_spam(self, request, queryset):
       ak = Akismet(blog_url=request.get_host(),
                    api_key=settings.AKISMET_API_KEY,
                    user_agent="Mesosphere/0.0.1")
       for comment in queryset:
           ak_dict = {'user_ip': comment.user_ip,
                      'user_agent': comment.user_agent,
                      'referrer': comment.referer,
                      'comment_content': comment.contents,
                      'comment_author': comment.name,
                     }
           if settings.DEBUG is True:
               ak_dict['is_test'] = 1
           ak.submit_spam(ak_dict)
           comment.delete()
 
       if len(queryset) == 1:
           message_bit = "1 comment was"
       else:
           message_bit = "%s comments were" % len(queryset)
       
       self.message_user (request, "%s sucessfully marked as spam and deleted." % message_bit)
Exemple #10
0
# -*- coding: utf-8 -*-
from pykismet3 import Akismet
import threading

api_key = 'd7719929047a'
blog_url = 'http://www.iloxp.com/'
akismet = Akismet(api_key, blog_url, user_agent='None')


def spamcheck(obj, referrer):
    comment_type = 'comment'
    if obj.parent:
        comment_type = 'reply'
    verify = akismet.check({
        'referrer': referrer,
        'comment_type': comment_type,
        'user_ip': obj.author_ip,
        'user_agent': obj.agent,
        'comment_content': obj.content,
        'comment_author_email': obj.author_email,
        'comment_author': obj.author_name,
        'is_test': 1,
    })
    if verify:
        obj.approved = 'spam'
    else:
        obj.approved = 'yes'
    obj.save()
    return obj.approved

Exemple #11
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
from pykismet3 import Akismet

from config.db import Config

config = Config('akismet')

a = Akismet(blog_url="", user_agent="Testing/Testing")

a.api_key = config['api_key']

print(
    a.check({
        'user_ip': '127.0.0.1',
        'user_agent': 'Mozilla/Firefox',
        'referrer': 'unknown',
        'comment_content': """Batman V Superman : Dawn of Justice
http://sendalgiceng21.blogspot.com/2016/03/batman-v-superman-dawn-of-justice.html

Captain America Civil War
http://sendalgiceng21.blogspot.com/2016/03/captain-america-civil-war.html

XXX : The Return Of Xander Cage
http://sendalgiceng21.blogspot.com/2016/03/xxx-return-of-xander-cage.html

Deadpool
http://sendalgiceng21.blogspot.com/2016/03/ddeadpool.html
Exemple #12
0
from pykismet3 import Akismet

# code is wrong

# defaultagent = 'akismettest python script from the Collective Intelligence book'
defaultagent = 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_5; en-us) '
defaultagent += 'AppleWebKit/525.27.1 (KHTML, like Gecko) '
defaultagent += 'Version/3.2.1 Safari/525.27.1'

a = Akismet(blog_url='moneydboat.top', user_agent=defaultagent)
a.api_key = 'e467cda4de57'


def isspam(comment, author, ip, agent=defaultagent):
    try:
        result = a.check({
            'user_ip': ip,
            'user_agent': agent,
            'referrer': 'unknown',
            'comment_content': comment,
            'comment_author': author,
            'is_test': 1,
        })
        print(result)
    except Akismet.AkismetError as e:
        print(e.response, e.statuscode)
        return False
Exemple #13
0
    def setUp(self):

        self.akismet_client = Akismet(blog_url="http://your.blog/url",
                                      user_agent="My Awesome Web App/0.0.1",
                                      api_key="testkey")