Example #1
0
def my_post_comment(request):
    referer = request.META.get('HTTP_REFERER', '')
    if not request.POST.has_key('preview'):
        response = post_comment(request,next=referer)
        curr_user = get_object_or_404(User, username=request.user)
        up = get_object_or_404(User_Profile, user=request.user)
        up.comment_count = up.comment_count+1
        up.save()
        content_type_id=request.POST['content_type']
        object_id=request.POST['object_pk']
        quip = get_object_or_404(Quip,id=int(object_id))
        quip.comment_count = quip.comment_count + 1 # incremnt comment count
        quip.last_comment_at=datetime.datetime.now() # last comment time updated
        quip.save()
        cache_key = '%s_quip%s' % (settings.CACHE_MIDDLEWARE_KEY_PREFIX,object_id,)
        cache.delete(cache_key)
	cache_key = '%s_activekwip' % (settings.CACHE_MIDDLEWARE_KEY_PREFIX,)
        cache.delete(cache_key)
        obj_user = quip.account.user
        text = request.POST['comment']
        subscribe_comments = request.POST.get('subscribe_comments', False)
        if subscribe_comments:
            follow_comments(request, quip.id)
        timestamp = quip.created_at.strftime("%Y/%b/%d/%H%M%S")
        link = str(obj_user.username)+'/kwips/'+timestamp.lower()+'/?type=comment&src=mail'	    
        #link = str(request['url'][1:])
        params_for_mail = {'#_1':obj_user.username,'#_2':curr_user.username,'#_3':request.POST['comment'],'#_4':link,'#_5':datetime.datetime.now().ctime()}
        if curr_user != obj_user:                
            send_mail(str(obj_user.email),'kwippy <*****@*****.**>','comment',params_for_mail)
            params_for_mail['#_4'] = params_for_mail['#_4'].replace('mail','im')
            send_im(obj_user,'comment',params_for_mail)
        send_anon_comment_emails(quip,curr_user,params_for_mail,link)
        send_comment_emails(quip,curr_user,params_for_mail,link)	    
        return redirect_to(request, referer)
    return post_comment(request,next=referer)
Example #2
0
def my_post_free_comment(request):
    if request.get("url"):
        response = post_comment(request)

        # Check there's a url to redirect to, and that post_free_comment worked
        if len(request.get("url").strip()) > 0 and isinstance(response, HttpResponseRedirect):
            return HttpResponseRedirect(request.get("url"))

        return post_comment(request)
Example #3
0
 def post(self, request, *args, **kwargs):
     o = get_object_or_404(Information, slug=self.kwargs['slug'])
     if isinstance(o, HTTPResponse):
         return o
     form = self.form_class(o, request.POST)
     if form.is_valid():
         post_comment(request)
         return self.get(request)
     return self.render_to_response({'form': form, 'object': o})
Example #4
0
def my_post_free_comment(request):
    if request.get('url'):
        response = post_comment(request)

        # Check there's a url to redirect to, and that post_free_comment worked
        if len(request.get('url').strip()) > 0 and isinstance(
                response, HttpResponseRedirect):
            return HttpResponseRedirect(request.get('url'))

        return post_comment(request)
Example #5
0
def redirect_post_comment(request):
    if request.REQUEST.has_key('target_url') and not request.REQUEST.has_key('preview'):
        response = post_comment(request)
        
        # Check there's a url to redirect to, and that post_free_comment worked
        if len(request.REQUEST['target_url'].strip()) > 0 and isinstance(response, HttpResponseRedirect):
            return HttpResponseRedirect(request.REQUEST['target_url'])
        
        # Fall back on the default post_free_comment response
        return response
    
    return post_comment(request)
Example #6
0
    def form_valid(self, form):
        if self.is_interaction_or_finalizing:
            button = self.request.POST['tabs']
            if button in ['submit_comment', 'submit_score_and_comment']:
                post_comment(self.request)

            message = _('Changed %s.') % get_text_list(form.changed_data, _('and'))
            reversion.revision.comment = message

        result = super(ScoreEditView, self).form_valid(form)

        return result
def maybelessspamcomment_post_comment(request):
        if 'url' in request.REQUEST and 'preview' not in request.REQUEST:
                response = post_comment(request)
            
                # Check there's a url to redirect to, and that post_free_comment worked
		redirect_url = request.REQUEST['redirect_url']
                if len(redirect_url.strip()) > 0 and isinstance(response, HttpResponseRedirect):
                        return HttpResponseRedirect(redirect_url)
                
                # Fall back on the default post_free_comment response
                return response
        
        return post_comment(request)
Example #8
0
def anti_spam(request):
    # make sure users have taken at least 5 seconds to read
    # this page before writing a comment (spam bots don't)
    # TODO: replace this with honeypot method
    if int(request.POST['timestamp']) + 5 > int(datetime.datetime.now().strftime('%s')):
        return HttpResponsePermanentRedirect('/')
    return post_comment(request)
Example #9
0
def oneliner_comment(request, pk):
    params = _common_params(request)
    params["cancel_url"] = reverse(oneliner, args=(pk,))

    try:
        oneliner0 = OneLiner.objects.get(pk=pk)
        oneliner0.score = sum([x.value for x in oneliner0.vote_set.all()])
    except OneLiner.DoesNotExist:
        return render_to_response("oneliners/pages/access_error.html", params)

    if request.method == "POST":
        if request.user.is_authenticated():
            data = request.POST.copy()
            data["name"] = request.user.get_full_name() or request.user.username
            data["email"] = request.user.email
            form = PostCommentOnOneLinerForm(oneliner0, data)
            if form.is_valid():
                return comments.post_comment(request, next=oneliner0.get_absolute_url())
        else:
            form = PostCommentOnOneLinerForm(oneliner0, request.POST)
    else:
        form = PostCommentOnOneLinerForm(oneliner0)

    params["form"] = form
    params["oneliner"] = oneliner0

    return render_to_response("oneliners/pages/oneliner_comment.html", params, context_instance=RequestContext(request))
Example #10
0
    def render(self, **kwargs):
        parent_type = self.parent.__class__.__name__.lower()
        request = kwargs.get('request')

        comment_page = self.parent
        if hasattr(comment_page, 'original_translation') and comment_page.original_translation:
            comment_page = comment_page.original_translation

        f = None
        if self.comments_enabled and request.POST:

            # I guess the drawback is that this page can't handle any other types of posts
            # just the comments for right now, but if we just post to the current path
            # and handle it this way .. at least it works for now.

            #extra = request._feincms_appcontent_parameters.get('page_extra_path', ())
            #if len(extra) > 0 and extra[0] == u"post-comment":

            from django.contrib.comments.views.comments import post_comment
            r = post_comment(request)
            if not isinstance(r, HttpResponseRedirect):
                f = comments.get_form()(comment_page, data=request.POST)

        if f is None:
            f = comments.get_form()(comment_page)

        return render_to_string([
            'content/comments/%s.html' % parent_type,
            'content/comments/default-site.html',
            'content/comments/default.html',
            ], RequestContext(request, { 'content': self, 'feincms_page' : self.parent, 'parent': comment_page, 'form' : f }))
Example #11
0
def custom_comment_post(request, next=None, using=None):
    # Check if IP not blacklisted
    httpbl = HttpBLMiddleware()
    response = httpbl.process_request(request)
    if response:
        # User blacklisted
        return response

    # original post comment function
    response = contrib_comments.post_comment(request, next, using)

    if type(response) == HttpResponseRedirect:
        redirect_path, comment_id = response.get('Location').split('?c=')
        # check if the comment was saved
        comment = KopiComment.objects.get( id=comment_id )
        if comment:
            # set the session id to the current one to allow edit
            comment.session_id = request.session.session_key
            comment.save()
           
            for subscription in Subscription.objects.filter(
                                  content_type = comment.content_type, 
                                  object_pk = comment.object_pk):
                if subscription.email != comment.email:
                    print("sending email for {}".format(subscription.email))
                    send_comment_email(subscription, NEW_COMMENT_ALERT, comment)

            if 'subscribe' in request.POST:
                comment_subscribe(comment)

            return HttpResponseRedirect( comment.get_absolute_url("#c%(id)s") )
    
    return response
Example #12
0
def save_free_comment(request):

    if request.POST:

        target = request.POST.get("target", None)

        if target:

            (ct_id, obj_id) = target.split(":")

            user_type = ContentType.objects.get(id=ct_id)

            if user_type.model == "section":
                section = Section.objects.get(pk=obj_id)
                legislation = section.title.legislation
            elif user_type.model == "legislation":
                legislation = Legislation.objects.get(pk=obj_id)
            else:
                legislation = None

            if legislation and legislation.allow_comments:

                return post_comment(request, extra_context)

            else:

                raise Http404, "Sorry, comments are not allowed on this legislation."

    else:

        raise Http404, "All you do is GET, GET, GET. How about you POST every once in a while like you used to at the beginning of our relationship?"

    return HttpResponseServerError("DENIED! Not really, something just broke.")
    def render(self, **kwargs):
        parent_type = self.parent.__class__.__name__.lower()
        request = kwargs.get('request')

        comment_page = self.parent
        if hasattr(comment_page, 'original_translation') and comment_page.original_translation:
            comment_page = comment_page.original_translation

        f = None
        if self.comments_enabled and request.POST:
            extra = request._feincms_appcontent_parameters.get('page_extra_path', ())
            if len(extra) > 0 and extra[0] == u"post-comment":
                from django.contrib.comments.views.comments import post_comment
                r = post_comment(request)
                if not isinstance(r, HttpResponseRedirect):
                    f = comments.get_form()(comment_page, data=request.POST)

        if f is None:
            f = comments.get_form()(comment_page)

        return render_to_string([
            'content/comments/%s.html' % parent_type,
            'content/comments/default-site.html',
            'content/comments/default.html',
            ], RequestContext(request, { 'content': self, 'feincms_page' : self.parent, 'parent': comment_page, 'form' : f }))
Example #14
0
def oneliner_comment(request, pk):
    params = _common_params(request)
    initial = _common_initial(request)
    params['next_url'] = initial['next_url']

    try:
        oneliner0 = OneLiner.objects.get(pk=pk)
    except:
        return render_to_response('main/pages/access_error.html', params)

    if request.method == 'POST':
        if request.user.is_authenticated():
            data = request.POST.copy()
            data['name'] = request.user.get_full_name() or request.user.username
            data['email'] = request.user.email
            form = PostCommentOnOneLinerForm(oneliner0, data)
            if form.is_valid():
                comment = form.cleaned_data['comment']
                send_oneliner_comment(oneliner0, request.user, comment)
                return comments.post_comment(request, next=oneliner0.get_absolute_url())
            else:
                params['next_url'] = request.POST.get('next_url')
        else:
            form = PostCommentOnOneLinerForm(oneliner0, request.POST)
    else:
        form = PostCommentOnOneLinerForm(oneliner0, initial=initial)

    params['form'] = form
    params['oneliner'] = oneliner0

    return render_to_response('main/pages/oneliner_comment.html', params, context_instance=RequestContext(request))
Example #15
0
def comment_post_wrapper(request):
    if request.user.is_authenticated():
        if not (request.user.username == request.POST['name'] and \
               request.user.email == request.POST['email']):
            return HttpResponse("You registered user...trying to spoof a form...eh?")
        return post_comment(request)
    return HttpResponse("You anonymous cheater...trying to spoof a form?")
Example #16
0
def oneliner_comment(request, pk):
    params = _common_params(request)
    params['cancel_url'] = reverse(oneliner, args=(pk, ))

    try:
        oneliner0 = OneLiner.objects.get(pk=pk)
        oneliner0.score = sum([x.value for x in oneliner0.vote_set.all()])
    except OneLiner.DoesNotExist:
        return render_to_response('oneliners/pages/access_error.html', params)

    if request.method == 'POST':
        if request.user.is_authenticated():
            data = request.POST.copy()
            data['name'] = request.user.get_full_name(
            ) or request.user.username
            data['email'] = request.user.email
            form = PostCommentOnOneLinerForm(oneliner0, data)
            if form.is_valid():
                return comments.post_comment(request,
                                             next=oneliner0.get_absolute_url())
        else:
            form = PostCommentOnOneLinerForm(oneliner0, request.POST)
    else:
        form = PostCommentOnOneLinerForm(oneliner0)

    params['form'] = form
    params['oneliner'] = oneliner0

    return render_to_response('oneliners/pages/oneliner_comment.html',
                              params,
                              context_instance=RequestContext(request))
def post_comment(request, next=None, using=None):
    """Wraps Django's post_comment view to handle the redirect better."""
    data = request.POST.copy()
    if 'cancel' in data:
        return redirect(data['cancel_url'])
    
    response = comments.post_comment(request, next, using)
    
    comment_pk = ''
    if response.status_code == 302:
        # Move the comment pk in the query string to the URL fragment 
        # (and clear out delete and reply key values pairs as well)
        redirect_location = response['location']
        redirect_url = list(urlparse.urlparse(redirect_location))
        redirect_qs = urlparse.parse_qs(redirect_url[4])
        comment_pk = ''
        if 'c' in redirect_qs:
            comment_pk = redirect_qs['c'][0]
            del redirect_qs['c']
        if EDIT_QUERY_STRING_KEY in redirect_qs:
            del redirect_qs[EDIT_QUERY_STRING_KEY]
        if REPLY_QUERY_STRING_KEY in redirect_qs:
            del redirect_qs[REPLY_QUERY_STRING_KEY]
        redirect_url[4] = urllib.urlencode(redirect_qs, True)
        redirect_url[5] = ''.join(['c', comment_pk])
        response['location'] = urlparse.urlunparse(redirect_url)
    
        if request.is_ajax():
            return redirect(get_comment, comment_id=comment_pk)
    
    return response
Example #18
0
def save_comment(request):
    if request.POST:
        human_form = HumanityForm(request.POST)
        if human_form.is_valid():
            return post_comment(request)
    else:
        raise Http404, "All you do is GET, GET, GET. How about you POST every once in a while like you used to at the beginning of our relationship?"
Example #19
0
def section_detail(request, legislation_slug, title_num, section_num):
    
    if request.method == 'POST':
        human_form = HumanityForm(request.POST, label_suffix='')
        is_human = request.POST.get('humanity', 'robot') == 'human'
        if is_human or human_form.is_valid():
            return post_comment(request)
    else:
        human_form = HumanityForm(label_suffix='')
    
    section_num = int(section_num)
    section = Section.objects.get(number=section_num, title__number=title_num, title__legislation__slug=legislation_slug)
    try:
        next_section = Section.objects.get(number=section_num + 1, title__number=title_num, title__legislation__slug=legislation_slug)
    except Section.DoesNotExist:
        next_section = None
    try:
        previous_section = Section.objects.get(number=section_num - 1, title__number=title_num, title__legislation__slug=legislation_slug)
    except Section.DoesNotExist:
        previous_section = None
    data = {
        'legislation': section.title.legislation,
        'title': section.title,
        'section': section,
        'next_section': next_section,
        'previous_section': previous_section,
        'human_form': human_form,
    }
    return render_to_response("legislation/section_detail.html", data,
                              context_instance=RequestContext(request))
Example #20
0
def save_free_comment(request):
    
    if request.POST:
        
        target = request.POST.get("target", None)
        
        if target:
            
            (ct_id, obj_id) = target.split(":")
        
            user_type = ContentType.objects.get(id=ct_id)
            
            if user_type.model == "section":
                section = Section.objects.get(pk=obj_id)
                legislation = section.title.legislation
            elif user_type.model == "legislation":
                legislation = Legislation.objects.get(pk=obj_id)
            else:
                legislation = None
        
            if legislation and legislation.allow_comments:
        
                return post_comment(request, extra_context)
                
            else:
                
                raise Http404, "Sorry, comments are not allowed on this legislation."
    
    else:
    
        raise Http404, "All you do is GET, GET, GET. How about you POST every once in a while like you used to at the beginning of our relationship?"
        
    return HttpResponseServerError("DENIED! Not really, something just broke.")
Example #21
0
def save_comment(request):
    if request.POST:
        human_form = HumanityForm(request.POST)
        if human_form.is_valid():
            return post_comment(request)
    else:
        raise Http404, "All you do is GET, GET, GET. How about you POST every once in a while like you used to at the beginning of our relationship?"
Example #22
0
def comment_post_wrapper(request):
    # Clean the request to prevent form spoofing
    if request.user.is_authenticated():
        if (('name' in request.POST and (request.user.get_full_name() != request.POST['name'])) or \
                ('email' in request.POST and (request.user.email == request.POST['email']))):
            return HttpResponse("Access denied")
        return post_comment(request)
    return HttpResponse("Access denied")
Example #23
0
def comment_post_wrapper(request):
    # Clean the request to prevent form spoofing
    if request.user.is_authenticated():
        if (('name' in request.POST and (request.user.get_full_name() != request.POST['name'])) or \
                ('email' in request.POST and (request.user.email == request.POST['email']))):
            return HttpResponse("Access denied")
        return post_comment(request)
    return HttpResponse("Access denied")
Example #24
0
def comment_post_wrapper(request):
    # Clean the request to prevent form spoofing
    if request.user.is_authenticated():
        if not (request.user.get_full_name() == request.POST['name'] or \
               request.user.email == request.POST['email']):
            return HttpResponse("You registered user...trying to spoof a form...eh?")
        return post_comment(request)
    return HttpResponse("You anonymous cheater...trying to spoof a form?")
def comment_post_wrapper(request):
    # Clean the request to prevent form spoofing
    if request.user.is_authenticated():
        if not (request.user.get_full_name() == request.POST['name'] or \
               request.user.email == request.POST['email']):
            return HttpResponse("Error 403: You're an evil hacker")
        return post_comment(request)
    return HttpResponse("Error 403: You're an evil hacker")
Example #26
0
def media(request, media='', id='', playlist=None, view=''):
	
	request.user.playlists = models.Playlist.have_permission(request.user)
	
	if request.POST.get('submit', '') == 'Post Comment':
		post_comment(request)
	if request.POST.get('submit', '') == 'delete_comment':
		comment_id = request.POST.get('comment_id')
		moderation.delete(request, comment_id)
	
	name = media
	media = None
	
	media = get_object_or_404(models.Media, id=id, site=current_site)
	
	if playlist:
		playlist = get_object_or_404(models.Playlist, path=playlist, site=current_site)
	
	if name != media.name:
		raise Http404
	if not playlist and media.playlists.filter(privacy="SEC"):
		raise Http404
	if playlist:
		if playlist.privacy == "SEC" and not playlist.is_accessible_by(request.user):
			raise Http404
		if not playlist in media.playlists.all():
			raise Http404
	
	# Make sure the video file hasn't been deleted from the filesystem
	# If it has, media.sync() will remove it from the database and get_object_or_404(...)
	# will return 404 error
	media.sync()
	get_object_or_404(models.Media, id=id)
	
	# This is for returning log view, print_log view, etc.
	if view:
		return eval('media_'+view)(request, media)
	
	context = {
		'media': media,
		'playlist': playlist,
		'player_settings': media.get_player_settings(),
		'view': 'view',
	}
	return render_to_response('media.html', context, context_instance=RequestContext(request))
Example #27
0
def comment_post_wrapper(request):
    # Clean the request to prevent form spoofing
    if request.user.is_authenticated():
        if not (request.user.get_full_name() == request.POST['name'] or \
               request.user.email == request.POST['email']):
            return HttpResponse(
                "You registered user...trying to spoof a form...eh?")
        return post_comment(request)
    return HttpResponse("You anonymous cheater...trying to spoof a form?")
Example #28
0
def validate_and_submit(request, next=None):
    # The next three lines are slightly hackish but there's not
    # much that can be done if we have to pass the ip
    # address to recaptcha
    ip_address = request.META.get('HTTP_X_FORWARDED_FOR', request.META.get('REMOTE_ADDR', None))
    post_querydict = request.POST.copy()
    post_querydict.update({'remoteip': ip_address})
    request.POST = post_querydict
    return post_comment(request, next=next)
Example #29
0
def comment(request):
    from django.contrib.comments.views.comments import post_comment
    import captcha
    #captcha_html = captcha.displayhtml(settings.RECAPTCHA_PUB_KEY)
    msg = _("Captcha was incorrect")
    if request.POST.has_key('recaptcha_challenge_field') and request.POST.has_key('recaptcha_response_field'):
	captcha_response = captcha.submit(request.POST['recaptcha_challenge_field'], request.POST['recaptcha_response_field'], settings.RECAPTCHA_PRIVATE_KEY, request.META['REMOTE_ADDR'])
	if captcha_response.is_valid:
	    return post_comment(request, request.POST['target'])
    return HttpResponseBadRequest("cannot recognize this form")
Example #30
0
def custom_post_comment(request):
    """custom comment handling. backup in case javascript is disabled."""
    mm = MessageManager(request)
    if 'url-redirect' in request.REQUEST and 'preview' not in request.REQUEST:
        # validate comment body
        data = request.POST.copy()
        if data['comment'] == '':
            return HttpResponseRedirect(request.REQUEST['url-redirect'])
        else:
            # TODO: detect newlines and replace with paragraphs
            response = post_comment(request)
        
         #Check there's a url to redirect to, and that post_comment worked
        if len(request.REQUEST['url-redirect'].strip()) > 0 and isinstance(response, HttpResponseRedirect):
            return HttpResponseRedirect(request.REQUEST['url-redirect'])
        
        #Fall back on the default post_free_comment response
        return response
    
    return post_comment(request)
Example #31
0
def comment_post_wrapper(request):
    # from http://thejaswi.info/tech/blog/2008/11/20/part-2-django-comments-authenticated-users/
    # Clean the request to prevent form spoofing
    user = request.user
    if user.is_authenticated() and not user.profile.restricted:
        if not (user.get_full_name() == request.POST['name'] and \
                user.email == request.POST['email']):
            return HttpResponse("You registered user...trying to spoof a form...eh?")
        resp = post_comment(request)
        if isinstance(resp, HttpResponseRedirect):
            messages.success(request, _(u"Your comment was posted."))
        return resp
    return HttpResponse("You anonymous cheater...trying to spoof a form?")
Example #32
0
def comment_post_wrapper(request):
    # from http://thejaswi.info/tech/blog/2008/11/20/part-2-django-comments-authenticated-users/
    # Clean the request to prevent form spoofing
    user = request.user
    if user.is_authenticated() and not user.profile.restricted:
        if not (user.get_full_name() == request.POST['name'] and \
                user.email == request.POST['email']):
            return HttpResponse(
                "You registered user...trying to spoof a form...eh?")
        resp = post_comment(request)
        if isinstance(resp, HttpResponseRedirect):
            messages.success(request, _(u"Your comment was posted."))
        return resp
    return HttpResponse("You anonymous cheater...trying to spoof a form?")
Example #33
0
def comment(request):
    from django.contrib.comments.views.comments import post_comment
    import captcha
    #captcha_html = captcha.displayhtml(settings.RECAPTCHA_PUB_KEY)
    msg = _("Captcha was incorrect")
    if request.POST.has_key(
            'recaptcha_challenge_field') and request.POST.has_key(
                'recaptcha_response_field'):
        captcha_response = captcha.submit(
            request.POST['recaptcha_challenge_field'],
            request.POST['recaptcha_response_field'],
            settings.RECAPTCHA_PRIVATE_KEY, request.META['REMOTE_ADDR'])
        if captcha_response.is_valid:
            return post_comment(request, request.POST['target'])
    return HttpResponseBadRequest("cannot recognize this form")
Example #34
0
def post_comment(request):
	# Call post comment function
	from django.contrib.comments.views import comments
	next = request.POST.get('next', '/')

	try:
		response = comments.post_comment(request, next)
	except:
		return HttpResponseRedirect('/noticias/')

	# Clean url
	url_redirect = response.get('Location', '')
	end = url_redirect.find('?')
	if end > 0:
		response['Location'] = url_redirect[:end] + '#respond'

	return response
Example #35
0
def post_comment(request):
	# Call post comment function
	from django.contrib.comments.views import comments
	next = request.POST.get('next', '/')

	try:
		response = comments.post_comment(request, next)
	except:
		return HttpResponseRedirect('/noticias/')

	# Clean url
	url_redirect = response.get('Location', '')
	end = url_redirect.find('?')
	if end > 0:
		response['Location'] = url_redirect[:end] + '#respond'

	return response
Example #36
0
def post_rating(request, url="/ratings/posted/", maxcomments=1):
    """Wrap django.contrib.comments.views.comments.post_comment, so that we can control where the user
    is returned after submit, also add the ability to control the maximum number of ratings per user
    per product.
    """
    if request.method != "POST":
        raise Http404(_("One or more of the required fields wasn't submitted"))

    if "url" in request.POST:
        url = request.POST["url"]

    response = post_comment(request)

    if maxcomments > 0 and not request.user.is_anonymous:
        try:
            target = request.POST["target"]
        except KeyError:
            raise Http404(
                _("One or more of the required fields wasn't submitted"))

        content_type_id, object_id = target.split(":")

        try:
            ct = ContentType.objects.get(pk=content_type_id)
        except ContentType.DoesNotExist:
            raise Http404(_("Bad ContentType: %s" % content_type_id))

        comments = Comment.objects.filter(
            object_id__exact=object_id,
            content_type__app_label__exact=ct.app_label,
            content_type__model__exact=ct.model,
            is_public__exact=True,
            user__exact=request.user.id,
        ).order_by("submit_date")

        ct = len(comments)
        if ct > maxcomments:
            log.debug("Got %i comments for user - removing all but %i", ct,
                      maxcomments)
            for c in comments:
                c.delete()
                ct -= 1
                if ct == maxcomments:
                    break

    return HttpResponseRedirect(url)
Example #37
0
def post_comment(request):
    # Call post comment function
    from django.contrib.comments.views import comments

    next = request.POST.get("next", "/")

    try:
        response = comments.post_comment(request, next)
    except:
        return HttpResponseRedirect("/noticias/")

        # Clean url
    url_redirect = response.get("Location", "")
    end = url_redirect.find("?")
    if end > 0:
        response["Location"] = url_redirect[:end] + "#respond"

    return response
Example #38
0
    def process(self, request, **kwargs):
        parent_type = self.parent.__class__.__name__.lower()

        comment_page = self.parent
        if (hasattr(comment_page, 'original_translation')
                and comment_page.original_translation):
            comment_page = comment_page.original_translation

        f = None
        if self.comments_enabled and request.POST:

            # I guess the drawback is that this page can't handle any other
            # types of posts just the comments for right now, but if we just
            # post to the current path and handle it this way .. at least it
            # works for now.

            # extra = request._feincms_extra_context.get('page_extra_path', ())
            # if len(extra) > 0 and extra[0] == "post-comment":

            r = post_comment(request, next=comment_page.get_absolute_url())

            if isinstance(r, HttpResponseRedirect):
                return r

            f = comments.get_form()(comment_page, data=request.POST)

        if f is None:
            f = comments.get_form()(comment_page)

        self.rendered_output = render_to_string(
            [
                'content/comments/%s.html' % parent_type,
                'content/comments/default-site.html',
                'content/comments/default.html',
            ],
            RequestContext(
                request, {
                    'content': self,
                    'feincms_page': self.parent,
                    'parent': comment_page,
                    'form': f,
                }),
        )
Example #39
0
def post_rating(request, url='/ratings/posted/', maxcomments=1):
    """Wrap django.contrib.comments.views.comments.post_comment, so that we can control where the user
    is returned after submit, also add the ability to control the maximum number of ratings per user 
    per product.
    """
    if request.method != "POST":
        raise Http404, _("One or more of the required fields wasn't submitted")
        
    if request.POST.has_key('url'):
        url = request.POST['url']
        
    response = post_comment(request)

    if maxcomments > 0 and not request.user.is_anonymous():
        try:
            target = request.POST['target']
        except KeyError:
            raise Http404, _("One or more of the required fields wasn't submitted")
            
        content_type_id, object_id = target.split(':')
        
        try:
            ct = ContentType.objects.get(pk=content_type_id)
        except ContentType.DoesNotExist:
            raise Http404, _("Bad ContentType: %s" % content_type_id)
        
        comments = Comment.objects.filter(object_id__exact=object_id,
            content_type__app_label__exact=ct.app_label,
            content_type__model__exact=ct.model,
            site__exact=Site.objects.get_current(),
            is_public__exact=True,
            user__exact=request.user.id).order_by('submit_date')
            
        ct = len(comments)
        if ct > maxcomments:
            log.debug("Got %i comments for user - removing all but %i", ct, maxcomments)
            for c in comments:
                c.delete()
                ct -= 1
                if ct == maxcomments: break
    
    return HttpResponseRedirect(url)
Example #40
0
    def process(self, request, **kwargs):
        parent_type = self.parent.__class__.__name__.lower()

        comment_page = self.parent
        if (hasattr(comment_page, 'original_translation')
                and comment_page.original_translation):
            comment_page = comment_page.original_translation

        f = None
        if self.comments_enabled and request.POST:

            # I guess the drawback is that this page can't handle any other
            # types of posts just the comments for right now, but if we just
            # post to the current path and handle it this way .. at least it
            # works for now.

            #extra = request._feincms_extra_context.get('page_extra_path', ())
            #if len(extra) > 0 and extra[0] == "post-comment":

            r = post_comment(request, next=comment_page.get_absolute_url())

            if isinstance(r, HttpResponseRedirect):
                return r

            f = comments.get_form()(comment_page, data=request.POST)

        if f is None:
            f = comments.get_form()(comment_page)

        self.rendered_output = render_to_string(
            [
                'content/comments/%s.html' % parent_type,
                'content/comments/default-site.html',
                'content/comments/default.html',
            ],
            RequestContext(request, {
                'content': self,
                'feincms_page': self.parent,
                'parent': comment_page,
                'form': f,
            }),
        )
Example #41
0
def _form_submission(request):
    """ Handle a AJAX comment form submission """
    # Use django.contrib.comments.views.comments.post_comment to handle a comment post.
    response = post_comment(request)
    if isinstance(response, HttpResponseRedirect):
        # reload the page after comment saved via JavaScript
        response = HttpResponse("reload")

        if not request.user.is_authenticated():
            # Store user data for anonymous users in a secure cookie, used in _get_form() to pre fill the form
            comments_data = {
                "name": request.POST["name"],
                "email": request.POST.get("email", ""),
                "url": request.POST.get("url", ""),
            }
            # Store the user data with a security hash
            c = ClientCookieStorage(cookie_key=COOKIE_KEY)
            response = c.save_data(comments_data, response)

    return response
Example #42
0
def post_recipe_comment(request, next=None):
    """
        Modified method for posting comments - in case of
        errors, redirects to recipe detail
    """
    form = __get_form(request)

    if isinstance(form, HttpResponseBadRequest):
        return form  #we didn't get a form but really an error

    #TODO make generic when necessary - when more model types than Recipe is needed
    #do this by sending POST parameter 'next_error' that will contain page
    #where user will be redirected in case of error
    if form.errors:
        #display recipe detail again, if there are some problems with comment
        data = request.POST.copy()
        object_pk = data.get("object_pk")  #may be only recipe now
        recipe = Recipe.objects.get(id=object_pk)
        return recipe_detail(request, recipe.slug, form)

    return post_comment(request, next)
Example #43
0
def test(request):
    """ ajax comment posting """
    data = {'status': 'OK'}
    from django.contrib.comments.views.comments import post_comment
    commented = post_comment(request)
    #hack for finding comment's id
    location = commented.__getitem__('location')
    position = location.find('?c=') + 3
    com_id = location[position:]

    comment = get_object_or_404(comments.get_model(),
                                pk=com_id,
                                site__pk=settings.SITE_ID)

    t = loader.get_template('comments/single.html')
    c = RequestContext(request, {
        'comment': comment,
    })
    data['html'] = t.render(c)

    return HttpResponse(json.dumps(data), "application/json")
Example #44
0
def section_detail(request, legislation_slug, title_num, section_num):

    if request.method == 'POST':
        human_form = HumanityForm(request.POST, label_suffix='')
        is_human = request.POST.get('humanity', 'robot') == 'human'
        if is_human or human_form.is_valid():
            return post_comment(request)
    else:
        human_form = HumanityForm(label_suffix='')

    section_num = int(section_num)
    section = Section.objects.get(number=section_num,
                                  title__number=title_num,
                                  title__legislation__slug=legislation_slug)
    try:
        next_section = Section.objects.get(
            number=section_num + 1,
            title__number=title_num,
            title__legislation__slug=legislation_slug)
    except Section.DoesNotExist:
        next_section = None
    try:
        previous_section = Section.objects.get(
            number=section_num - 1,
            title__number=title_num,
            title__legislation__slug=legislation_slug)
    except Section.DoesNotExist:
        previous_section = None
    data = {
        'legislation': section.title.legislation,
        'title': section.title,
        'section': section,
        'next_section': next_section,
        'previous_section': previous_section,
        'human_form': human_form,
    }
    return render_to_response("legislation/section_detail.html",
                              data,
                              context_instance=RequestContext(request))
Example #45
0
def legislation_detail(request, legislation_slug):

    try:
        legislation = Legislation.objects.get(slug=legislation_slug)
    except Legislation.DoesNotExist:
        return HttpResponseRedirect('/')

    if request.method == 'POST':
        human_form = HumanityForm(request.POST, label_suffix='')
        is_human = request.POST.get('humanity', 'robot') == 'human'
        if is_human or human_form.is_valid():
            return post_comment(request)
    else:
        human_form = HumanityForm(label_suffix='')

    data = {
        'legislation': legislation,
        'human_form': human_form,
    }

    return render_to_response("legislation/legislation_detail.html",
                              data,
                              context_instance=RequestContext(request))
Example #46
0
def post_comment(request, next=None, using=None):
    data = request.POST.copy()
    if not data.get('name', ''):
        data['name'] = 'anonymous'
        request.POST = data
    return comments.post_comment(request, next, using)
Example #47
0
def comment_post_wrapper(request):
    if not request.method == 'POST':
        return HttpResponseRedirect('/')
    return post_comment(request)
Example #48
0
def post(request, next=None, using=None):
    """
    This wrapper view only serves to require login for posting comments
    """
    return django_comments.post_comment(request, next, using)    
Example #49
0
def post_comment(request, next=None):
    POST = request.POST.copy()
    POST['user'] = request.user
    request.POST = POST
    return comments.post_comment(request, next)