'article', 'author', 'created_on', 'date_modified', ] # Signals def pre_save_comment(sender, **kargs): """ Run comment through a markdown filter """ if 'comment' in kargs: comment = kargs['comment'] # If in debug mode skip this check with Akismet if not settings.DEBUG: try: real_key = akismet.verify_key(settings.AKISMET_KEY ,Site.objects.get_current().domain) if real_key: is_spam = akismet.comment_check(settings.AKISMET_KEY ,Site.objects.get_current().domain, comment.ip_address, None, comment_content=comment.comment) if is_spam: comment.is_public = False print "That was spam" except akismet.AkismetError, e: print e.response, e.statuscode # Apply markdown comment.comment = markdown(comment.comment) comment_will_be_posted.connect(pre_save_comment, Comment)
cache = TagCache(tag=Tag.objects.get(id=x['tag']), entry=entry, score=x['score__sum']) cache.save() @classmethod @transaction.commit_on_success def recompute(cls, entry): TagCache.objects.filter(entry=entry).delete() cls._recompute_one(entry) @classmethod @transaction.commit_on_success def recompute_all(cls): TagCache.objects.all().delete() for entry in Entry.objects.all(): cls._recompute_one(entry) #------------------------------------------------------------------------------ # Comments #------------------------------------------------------------------------------ def _comment_pre_save(sender, comment, request, **kw): if not permissions.can_comment(request.user): return False comment.user = request.user return True comment_will_be_posted.connect(_comment_pre_save)
from django.conf import settings from django.contrib.comments.signals import comment_will_be_posted from kiwi.views import kiwi_preferred_name def kiwi_verification(sender, comment, request, **kwargs): comment.kiwi_verified = False if 'kiwi_info' in request.session: comment.name = kiwi_preferred_name(request) comment.email = request.session['kiwi_info']['email'] comment.kiwi_verified = True return True if getattr(settings, 'KIWI_API_CODE', False): comment_will_be_posted.connect(kiwi_verification) # vi: set sw=4 ts=4 sts=4 tw=79 ai et nocindent:
from django.contrib.comments.signals import comment_will_be_posted def comment_added(sender, **kwargs): comment = kwargs["comment"] if not comment.user: comment.is_public = False comment_will_be_posted.connect(comment_added)
def spamfilter(sender, comment, **kwargs): return False ban = [ 'cialis', 'viagra', 'generic', 'first time', 'genital', 'ficken', 'cheap', 'affiliate', 'herpes', ' your blog ' 'priceless', 'find out more', ' product ', ' concerns ', 'cheats', 'this site', 'fantastic read', 'features', 'your website', 'this blog', 'this info', 'thank you', 'thanks', 'tips and tricks', ] for b in ban: if b in comment.user_name.lower(): return False if b in comment.user_url.lower(): return False if b in comment.comment.lower(): return False if 'http://' in comment.user_name.lower(): return False return comment.ip_address not in getattr(settings, 'COMMENTS_IP_BLOCKED', ()) comment_will_be_posted.connect(spamfilter)
import hcomments request = kw['request'] comment = kw['comment'] data = request.POST.copy() if request.user.is_authenticated(): if not data.get('name', ''): data["name"] = request.user.get_full_name() or request.user.get_username() if not data.get('email', ''): data["email"] = request.user.email form = hcomments.get_form(request)(comment, data) if not form.is_valid(): raise CaptchaFailed() return True comment_will_be_posted.connect(on_comment_will_be_posted) def post_comment(request): from recaptcha_works.decorators import fix_recaptcha_remote_ip try: result = fix_recaptcha_remote_ip(comments_views.post_comment)(request) except CaptchaFailed: result = None if 'async' not in request.POST: if result: return result else: return comments_views.CommentPostBadRequest('') if result is None:
'hot brunette', 'earn money online', 'adult-friend-finder', 'Hi, interesting post. I have been pondering this issue,so thanks for sharing. I will definitely be subscribing to your blog.', 'Hello. And Bye.', 'http://quick-ways-to-earn-extra-cash.blogspot.com/' 'earn money online', 'http://www.mydatelove.com', 'best buy and loss weight', ] comment=kwargs['comment'].comment request=kwargs['request'] if not request.user.is_authenticated(): return False if not comment or comment in blacklist_identical: return False for b in blacklist_contains: if comment.find(b)!=-1: return False if strip_tags(comment) != comment: return False return True; comment_will_be_posted.connect(comment_spam_test)
from django.contrib.comments.models import Comment from django.contrib.comments.signals import comment_will_be_posted from django.conf import settings import akismet def spam_check(sender, comment, request, **kwargs): ak = akismet.Akismet() try: ak.setAPIKey(settings.AKISMET_API_KEY,"http://www.99percentmedia.org") real_key = ak.verify_key() if real_key: data = { 'user_ip': request.META.get('REMOTE_ADDR', '127.0.0.1'), 'user_agent': request.META.get('HTTP_USER_AGENT', ''), 'referrer': request.META.get('HTTP_REFERER', ''), 'comment_type': 'comment', 'comment_author': comment.user_name.encode('utf-8'), } is_spam = ak.comment_check(comment.comment.encode('utf-8'), data=data, build_data=True) if is_spam: return False else: return True except akismet.AkismetError, e: print 'Something went wrong, allowing comment' print e.response, e.statuscode return True comment_will_be_posted.connect(spam_check,sender=Comment,dispatch_uid="comment_spam_check_akismet")
from django.contrib.comments.signals import comment_will_be_posted from django.contrib.comments.models import Comment from django.http import HttpResponseRedirect def unapprove_comment(sender, **kwargs): the_comment = kwargs['comment'] the_comment.is_public = False return True comment_will_be_posted.connect(unapprove_comment)
from django.contrib.comments.signals import comment_will_be_posted from courant.core.utils.captcha.functions import verify_captcha comment_will_be_posted.connect(verify_captcha)
from django.db import models from django.contrib.comments.models import Comment from django.contrib.comments.managers import CommentManager from django.contrib.comments.signals import comment_will_be_posted class RatingComment(Comment): objects = CommentManager() rating = models.IntegerField(blank=True, default=-1) def make_sure_user_was_authenticated(sender, comment, request, **kwargs): return request.user.is_authenticated() comment_will_be_posted.connect(make_sure_user_was_authenticated)
from django.conf import settings from django.contrib.comments.signals import comment_will_be_posted from django.contrib.comments.signals import comment_was_posted from claims.views import claim_notification from clarifications.views import clarification_notification from custom_comments.views import comment_change_status, comment_notification from exmo2010.helpers import * from exmo2010.models import Monitoring, Score, UserProfile from exmo2010.signals import * from scores.views import create_revision, score_change_notify from tasks.views import task_user_change_notify if hasattr(settings, 'USE_EMAIL') and settings.USE_EMAIL: comment_will_be_posted.connect(comment_notification) score_was_changed.connect(score_change_notify) claim_was_posted_or_deleted.connect(claim_notification) clarification_was_posted.connect(clarification_notification) task_user_changed.connect(task_user_change_notify) post_save.connect(post_save_model) pre_save.connect(create_revision, sender=Score) # Регистрация хэндлера для сигнала перед отправкой комментария, # хэндлер изменяет статус комментариев. comment_was_posted.connect(comment_change_status) # invoke signal when 'organization' field at UserProfile was changed m2m_changed.connect(org_changed, sender=UserProfile.organization.through)
from comment.forms import CommentFormCustom from django.contrib.comments.signals import comment_was_posted,\ comment_will_be_posted from comment.signals import save_name_to_cookie, send_to_email, check_meta_data from comment.models import ProtectComment comment_was_posted.connect(send_to_email) comment_will_be_posted.connect(check_meta_data) def get_form(): return CommentFormCustom def get_model(): return ProtectComment
return BadgeAwarded() badges.register(SecondBestIngredientUse) class ThirdBestIngredientUse(Badge): slug = "Third best ingredient use" levels = [ "Bronze" ] events = [ "end_theme", ] multiple = True user_message ="Ingredients, there are so many of them but you seem to have a pretty good handle on this one, your recipe was voted third best use of ingredient!" def award(self, **state): user=get_object_or_404(User,username=state["user"].username) if state["award"] == "ing3": return BadgeAwarded() badges.register(ThirdBestThemeUse) #signal listeners from django.contrib.comments.signals import comment_will_be_posted def commentCallback(sender, comment, request, **kwargs): "The signal listener call this then it awards a comment point to the user" request.user.get_profile().awardComment(1,request) comment_will_be_posted.connect(commentCallback)
from django.utils.encoding import smart_str from django.contrib.comments.signals import comment_will_be_posted current_site = Site.objects.get_current() def moderate_comment(sender, comment, request, **kwargs): if not comment.id: entry = comment.content_object delta = timezone.now() - entry.pub_date if delta.days > 30: # age detection comment.is_public = False else: # akismet # CHECK BLOG_URL 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', 'referrer': request.META['HTTP_REFERER'], 'user_ip': comment.ip_address, 'user_agent': request.META['HTTP_USER_AGENT'] } if akismet_api.comment_check(smart_str(comment.comment), akismet_data, build_data = True): comment.is_public = False comment_will_be_posted.connect(moderate_comment, sender=Comment) # end comment spam detector
def connect(self): comment_will_be_posted.connect(self.pre_save_moderation, sender=comments.get_model()) signals.post_save.connect(self.post_save_moderation, sender=comments.get_model())
) # delete the item from cache absolute_url = content_object.get_absolute_url() language_code = content_object.language.code delete_cache_item(absolute_url, language_code, site.id) # FIXME: We must only update the cache for the current SITE not for all sites. try: cache.smooth_update() # Save "last change" timestamp in django-tools SmoothCacheBackend except AttributeError: # No SmoothCacheBackend used -> clean the complete cache cache.clear() comment_will_be_posted.connect(comment_will_be_posted_handler) comment_was_posted.connect(comment_was_posted_handler) @ensure_csrf_cookie @check_request(APP_LABEL, "_get_form() error", must_post=False, must_ajax=True) @render_to("pylucid_comments/comment_form.html") def _get_form(request): """ Send the comment form to via AJAX request """ try: ctype = request.GET["content_type"].split(".", 1) model = models.get_model(*ctype) except Exception, err: return bad_request(APP_LABEL, "error", "Wrong content type: %s" % err) try:
'earn money online', 'adult-friend-finder', 'Hi, interesting post. I have been pondering this issue,so thanks for sharing. I will definitely be subscribing to your blog.', 'Hello. And Bye.', 'http://quick-ways-to-earn-extra-cash.blogspot.com/' 'earn money online', 'http://www.mydatelove.com', 'best buy and loss weight', ] comment = kwargs['comment'].comment request = kwargs['request'] if not request.user.is_authenticated(): return False if not comment or comment in blacklist_identical: return False for b in blacklist_contains: if comment.find(b) != -1: return False if strip_tags(comment) != comment: return False return True comment_will_be_posted.connect(comment_spam_test)
def is_draft(self): return self.status == self.DRAFT def is_published(self): return self.status == self.PUBLISHED def get_absolute_url(self, user=None): """ Return a url based on the publication status of the object. Access control of these urls should be done in their views or the URL conf. """ if self.status == self.PUBLISHED: name = 'blog_entry_detail' kwargs = {'slug': self.slug} else: name = 'blog_entry_draft' kwargs = {'object_id': self.id} return reverse(name, kwargs=kwargs) # If we're using static-generator, blow away the cached files on save. if 'staticgenerator.middleware.StaticGeneratorMiddleware' in settings.MIDDLEWARE_CLASSES: from django.dispatch import dispatcher from django.db.models.signals import post_save from staticgenerator import quick_delete def delete(sender, instance, **kwargs): quick_delete(instance, '/') post_save.connect(delete, sender=Entry) # Comment signals comment_will_be_posted.connect(comment_spam_check, sender=Comment) comment_was_posted.connect(comment_notifier, sender=Comment)
module, attr = path[:i], path[i+1:] try: mod = __import__(module, {}, {}, [attr]) except ImportError, e: raise ImproperlyConfigured('Error importing comment validation module %s: "%s"' % (module, e)) try: func = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a "%s" callable comment validator' % (module, attr)) validators.append(func) reject_threshold = getattr(settings, 'FCCV_REJECT_THRESHOLD', 0.9) score = 0.0 for validator in validators: validator_score = validator(comment, request) if settings.DEBUG: logger.debug("""Score from validator %s: %s""" % (validator, validator_score)) if validator_score: score += validator_score if score > reject_threshold: logger.info("""Rejected comment with score of %s:""" % (score) + """ IP Address: "%(ip_address)s" Name: "%(user_name)s" Email: "%(user_email)s" URL: "%(user_url)s" Comment: "%(comment)s" """ % comment.__dict__) return False if score > getattr(settings, 'FCCV_PUBLIC_THRESHOLD', 0.1): logger.info("""Comment spam score is %s; marking it non-public.""" % score) comment.is_public = False return True comment_will_be_posted.connect(validate_comment, sender=Comment)
from django.db.models.signals import post_save from django.contrib.comments.signals import comment_will_be_posted from main.models import * def user_profile_create(sender, **kwargs): if kwargs['created']: profile = UserProfile(user=kwargs['instance']) profile.save() def validate_membership(sender, comment, **kwargs): if not comment.user: return False post_save.connect(user_profile_create, sender=User) comment_will_be_posted.connect(validate_membership)
badges.register(SecondBestIngredientUse) class ThirdBestIngredientUse(Badge): slug = "Third best ingredient use" levels = ["Bronze"] events = [ "end_theme", ] multiple = True user_message = "Ingredients, there are so many of them but you seem to have a pretty good handle on this one, your recipe was voted third best use of ingredient!" def award(self, **state): user = get_object_or_404(User, username=state["user"].username) if state["award"] == "ing3": return BadgeAwarded() badges.register(ThirdBestThemeUse) #signal listeners from django.contrib.comments.signals import comment_will_be_posted def commentCallback(sender, comment, request, **kwargs): "The signal listener call this then it awards a comment point to the user" request.user.get_profile().awardComment(1, request) comment_will_be_posted.connect(commentCallback)
from django.db.models.signals import post_save from django.contrib.comments.signals import comment_will_be_posted from main.models import * def user_profile_create(sender, **kwargs): if kwargs['created']: profile = UserProfile(user=kwargs['instance']); profile.save(); def validate_membership(sender, comment, **kwargs): if not comment.user: return False post_save.connect(user_profile_create, sender=User) comment_will_be_posted.connect(validate_membership)
score=x['score__sum']) cache.save() @classmethod @transaction.commit_on_success def recompute(cls, entry): TagCache.objects.filter(entry=entry).delete() cls._recompute_one(entry) @classmethod @transaction.commit_on_success def recompute_all(cls): TagCache.objects.all().delete() for entry in Entry.objects.all(): cls._recompute_one(entry) #------------------------------------------------------------------------------ # Comments #------------------------------------------------------------------------------ def _comment_pre_save(sender, comment, request, **kw): if not permissions.can_comment(request.user): return False comment.user = request.user return True comment_will_be_posted.connect(_comment_pre_save)
'Su comentario sobre el evento') + ' "' + evento.nombre + '" ' + _( 'ha sido aprobado y publicado en:' ) + '\n' + site.domain + '/comentario/' + str( evento.id) + '/\n\n' + _('Gracias...') else: asunto = _(u'Nuevo comentario en lista de moderación') para = [evento.email] mensaje = _('Un nuevo comentario sobre el evento' ) + ' "' + evento.nombre + '" ' + _( 'se encuentra en espera para ser aprobado en:' ) + '\n' + site.domain + '/admin/comments/comment/' + str( instance.id) + '/\n\n' + _('Gracias...') try: email.enviar_mail(asunto, mensaje, evento.email, para) except Exception, error: pass def pp(sender, comment, request, **kwargs): global EVENTO EVENTO = int(request.POST['instancia_evento']) comment_will_be_posted.connect(pp) pre_save.connect(pre_save_comment, sender=Comment) post_save.connect(post_save_comment, sender=Comment) Comment.add_to_class('instancia_evento', models.ForeignKey(Evento, verbose_name=_(u'Evento')))