예제 #1
0
def convert_to_comment(request, id):
    user = request.user
    answer = get_object_or_404(Answer, id=id)
    question = answer.question

    # Check whether the user has the required permissions
    if not user.is_authenticated():
        raise AnonymousNotAllowedException(_("convert answers to comments"))

    if not user.can_convert_to_comment(answer):
        raise NotEnoughRepPointsException(_("convert answers to comments"))

    if not request.POST:
        description = lambda a: _("Answer by %(uname)s: %(snippet)s...") % {'uname': smart_unicode(a.author.username),
                                                                            'snippet': a.summary[:10]}
        nodes = [(question.id, _("Question"))]
        [nodes.append((a.id, description(a))) for a in
         question.answers.filter_state(deleted=False).exclude(id=answer.id)]

        return render_to_response('node/convert_to_comment.html', {'answer': answer, 'nodes': nodes})

    try:
        new_parent = Node.objects.get(id=request.POST.get('under', None))
    except:
        raise CommandException(_("That is an invalid post to put the comment under"))

    if not (new_parent == question or (new_parent.node_type == 'answer' and new_parent.parent == question)):
        raise CommandException(_("That is an invalid post to put the comment under"))

    AnswerToCommentAction(user=user, node=answer, ip=request.META['REMOTE_ADDR']).save(data=dict(new_parent=new_parent))

    return RefreshPageCommand()
예제 #2
0
def comment(request, id):
    post = get_object_or_404(Node, id=id)
    user = request.user

    if not user.is_authenticated():
        raise AnonymousNotAllowedException(_('comment'))

    if not request.method == 'POST':
        raise CommandException(_("Invalid request"))

    comment_text = request.POST.get('comment', '').strip()

    if not len(comment_text):
        raise CommandException(_("Comment is empty"))

    if len(comment_text) < settings.FORM_MIN_COMMENT_BODY:
        raise CommandException(
            _("At least %d characters required on comment body.") %
            settings.FORM_MIN_COMMENT_BODY)

    if len(comment_text) > settings.FORM_MAX_COMMENT_BODY:
        raise CommandException(
            _("No more than %d characters on comment body.") %
            settings.FORM_MAX_COMMENT_BODY)

    if 'id' in request.POST:
        comment = get_object_or_404(Comment, id=request.POST['id'])

        if not user.can_edit_comment(comment):
            raise NotEnoughRepPointsException(_('edit comments'))

        comment = ReviseAction(user=user,
                               node=comment,
                               ip=request.META['REMOTE_ADDR']).save(data=dict(
                                   text=comment_text)).node
    else:
        if not user.can_comment(post):
            raise NotEnoughRepPointsException(_('comment'))

        comment = CommentAction(
            user=user, ip=request.META['REMOTE_ADDR']).save(
                data=dict(text=comment_text, parent=post)).node

    if comment.active_revision.revision == 1:
        return {
            'commands': {
                'insert_comment': [
                    id,
                    comment.id,
                    comment.comment,
                    user.decorated_name,
                    user.get_profile_url(),
                    reverse('delete_comment', kwargs={'id': comment.id}),
                    reverse('node_markdown', kwargs={'id': comment.id}),
                    reverse('convert_comment', kwargs={'id': comment.id}),
                ]
            }
        }
    else:
        return {'commands': {'update_comment': [comment.id, comment.comment]}}
예제 #3
0
def flag_post(request, id):
    if not request.POST:
        return render_to_response('node/report.html', {'types': settings.FLAG_TYPES})

    post = get_object_or_404(Node, id=id)
    user = request.user

    if not user.is_authenticated():
        raise AnonymousNotAllowedException(_('flag posts'))

    if user == post.author:
        raise CannotDoOnOwnException(_('flag'))

    if not (user.can_flag_offensive(post)):
        raise NotEnoughRepPointsException(_('flag posts'))

    user_flag_count_today = user.get_flagged_items_count_today()

    if user_flag_count_today >= int(settings.MAX_FLAGS_PER_DAY):
        raise NotEnoughLeftException(_('flags'), str(settings.MAX_FLAGS_PER_DAY))

    try:
        current = FlagAction.objects.get(canceled=False, user=user, node=post)
        raise CommandException(
                _("You already flagged this post with the following reason: %(reason)s") % {'reason': current.extra})
    except ObjectDoesNotExist:
        reason = request.POST.get('prompt', '').strip()

        if not len(reason):
            raise CommandException(_("Reason is empty"))

        FlagAction(user=user, node=post, extra=reason, ip=request.META['REMOTE_ADDR']).save()

    return {'message': _("Thank you for your report. A moderator will review your submission shortly.")}
예제 #4
0
def vote_post(request, id, vote_type):
    if not request.method == 'POST':
        raise CommandException(_("Invalid request"))


    post = get_object_or_404(Node, id=id).leaf
    user = request.user

    if not user.is_authenticated():
        raise AnonymousNotAllowedException(_('vote'))

    if user == post.author:
        raise CannotDoOnOwnException(_('vote'))

    if not (vote_type == 'up' and user.can_vote_up() or user.can_vote_down()):
        reputation_required = int(settings.REP_TO_VOTE_UP) if vote_type == 'up' else int(settings.REP_TO_VOTE_DOWN)
        action_type = vote_type == 'up' and _('upvote') or _('downvote')
        raise NotEnoughRepPointsException(action_type, user_reputation=user.reputation, reputation_required=reputation_required, node=post)

    user_vote_count_today = user.get_vote_count_today()
    user_can_vote_count_today = user.can_vote_count_today()

    if user_vote_count_today >= user.can_vote_count_today():
        raise NotEnoughLeftException(_('votes'), str(settings.MAX_VOTES_PER_DAY))

    new_vote_cls = (vote_type == 'up') and VoteUpAction or VoteDownAction
    score_inc = 0

    old_vote = VoteAction.get_action_for(node=post, user=user)

    if old_vote:
        if old_vote.action_date < datetime.datetime.now() - datetime.timedelta(days=int(settings.DENY_UNVOTE_DAYS)):
            raise CommandException(
                    _("Sorry but you cannot cancel a vote after %(ndays)d %(tdays)s from the original vote") %
                    {'ndays': int(settings.DENY_UNVOTE_DAYS),
                     'tdays': ungettext('day', 'days', int(settings.DENY_UNVOTE_DAYS))}
                    )

        old_vote.cancel(ip=request.META['REMOTE_ADDR'])
        score_inc = (old_vote.__class__ == VoteDownAction) and 1 or -1
        vote_type = "none"
    else:
        new_vote_cls(user=user, node=post, ip=request.META['REMOTE_ADDR']).save()
        score_inc = (new_vote_cls == VoteUpAction) and 1 or -1

    response = {
    'commands': {
    'update_post_score': [id, score_inc],
    'update_user_post_vote': [id, vote_type]
    }
    }

    votes_left = (user_can_vote_count_today - user_vote_count_today) + (vote_type == 'none' and -1 or 1)

    if int(settings.START_WARN_VOTES_LEFT) >= votes_left:
        response['message'] = _("You have %(nvotes)s %(tvotes)s left today.") % \
                    {'nvotes': votes_left, 'tvotes': ungettext('vote', 'votes', votes_left)}

    return response
예제 #5
0
def accept_answer(request, id):
    if settings.DISABLE_ACCEPTING_FEATURE:
        raise Http404()

    user = request.user

    if not user.is_authenticated():
        raise AnonymousNotAllowedException(_('accept answers'))

    answer = get_object_or_404(Answer, id=id)
    question = answer.question

    if not user.can_accept_answer(answer):
        raise CommandException(_("Sorry but you cannot accept the answer"))

    commands = {}

    if answer.nis.accepted:
        answer.nstate.accepted.cancel(user, ip=request.META['REMOTE_ADDR'])
        commands['unmark_accepted'] = [answer.id]
    else:
        if settings.MAXIMUM_ACCEPTED_ANSWERS and (question.accepted_count >= settings.MAXIMUM_ACCEPTED_ANSWERS):
            raise CommandException(ungettext("This question already has an accepted answer.",
                "Sorry but this question has reached the limit of accepted answers.", int(settings.MAXIMUM_ACCEPTED_ANSWERS)))

        if settings.MAXIMUM_ACCEPTED_PER_USER and question.accepted_count:
            accepted_from_author = question.accepted_answers.filter(author=answer.author).count()

            if accepted_from_author >= settings.MAXIMUM_ACCEPTED_PER_USER:
                raise CommandException(ungettext("The author of this answer already has an accepted answer in this question.",
                "Sorry but the author of this answer has reached the limit of accepted answers per question.", int(settings.MAXIMUM_ACCEPTED_PER_USER)))             


        AcceptAnswerAction(node=answer, user=user, ip=request.META['REMOTE_ADDR']).save()

        # If the request is not an AJAX redirect to the answer URL rather than to the home page
        if not request.is_ajax():
            msg = _("""
              Congratulations! You've accepted an answer.
            """)

            # Notify the user with a message that an answer has been accepted
            request.user.message_set.create(message=msg)

            # Redirect URL should include additional get parameters that might have been attached
            redirect_url = answer.parent.get_absolute_url() + "?accepted_answer=true&%s" % smart_unicode(urlencode(request.GET))

            return HttpResponseRedirect(redirect_url)

        commands['mark_accepted'] = [answer.id]

    return {'commands': commands}
예제 #6
0
def close(request, id, close):
    if close and not request.POST:
        return render_to_response('node/report.html',
                                  {'types': settings.CLOSE_TYPES})

    question = get_object_or_404(Question, id=id)
    user = request.user

    if not user.is_authenticated():
        raise AnonymousNotAllowedException(_('close questions'))

    if question.nis.closed:
        if not user.can_reopen_question(question):
            raise NotEnoughRepPointsException(_('reopen questions'))

        question.nstate.closed.cancel(user, ip=request.META['REMOTE_ADDR'])
    else:
        if not request.user.can_close_question(question):
            raise NotEnoughRepPointsException(_('close questions'))

        reason = request.POST.get('prompt', '').strip()

        if not len(reason):
            raise CommandException(_("Reason is empty"))

        CloseAction(node=question,
                    user=user,
                    extra=reason,
                    ip=request.META['REMOTE_ADDR']).save()

    return RefreshPageCommand()
예제 #7
0
def award_points(request, user_id, answer_id):
    user = request.user
    awarded_user = get_object_or_404(User, id=user_id)
    answer = get_object_or_404(Answer, id=answer_id)

    # Users shouldn't be able to award themselves
    if awarded_user.id == user.id:
        raise CannotDoOnOwnException(_("award"))

    # Anonymous users cannot award  points, they just don't have such
    if not user.is_authenticated():
        raise AnonymousNotAllowedException(_('award'))

    if not request.POST:
        return render_to_response("node/award_points.html", {
            'user' : user,
            'awarded_user' : awarded_user,
            'reputation_to_comment' : str(settings.REP_TO_COMMENT)
        })
    else:
        points = int(request.POST['points'])

        # We should check if the user has enough reputation points, otherwise we raise an exception.
        if points < 0:
            raise CommandException(_("The number of points to award needs to be a positive value."))

        if user.reputation < points:
            raise NotEnoughRepPointsException(_("award"))

        extra = dict(message=request.POST.get('message', ''), awarding_user=request.user.id, value=points)

        # We take points from the awarding user
        AwardPointsAction(user=request.user, node=answer, extra=extra).save(data=dict(value=points, affected=awarded_user))

        return { 'message' : _("You have awarded %(awarded_user)s with %(points)d points") % {'awarded_user' : awarded_user, 'points' : points} }
예제 #8
0
def subscribe(request, id, user=None):
    if user:
        try:
            user = User.objects.get(id=user)
        except User.DoesNotExist:
            raise Http404()

        if not (request.user.is_a_super_user_or_staff() or user.is_authenticated()):
            raise CommandException(_("You do not have the correct credentials to preform this action."))
    else:
        user = request.user

    question = get_object_or_404(Question, id=id)

    try:
        subscription = QuestionSubscription.objects.get(question=question, user=user)
        subscription.delete()
        subscribed = False
    except:
        subscription = QuestionSubscription(question=question, user=user, auto_subscription=False)
        subscription.save()
        subscribed = True

    return {
        'commands': {
            'set_subscription_button': [subscribed and _('unsubscribe me') or _('subscribe me')],
            'set_subscription_status': ['']
        }
    }
예제 #9
0
def accept_answer(request, id):
    if settings.DISABLE_ACCEPTING_FEATURE:
        raise Http404()

    user = request.user

    if not user.is_authenticated():
        raise AnonymousNotAllowedException(_('accept answers'))

    answer = get_object_or_404(Answer, id=id)
    question = answer.question

    if not user.can_accept_answer(answer):
        raise CommandException(_("Sorry but you cannot accept the answer"))

    commands = {}

    if answer.nis.accepted:
        answer.nstate.accepted.cancel(user, ip=request.META['REMOTE_ADDR'])
        commands['unmark_accepted'] = [answer.id]
    else:
        if settings.MAXIMUM_ACCEPTED_ANSWERS and (
                question.accepted_count >= settings.MAXIMUM_ACCEPTED_ANSWERS):
            raise CommandException(
                ungettext(
                    "This question already has an accepted answer.",
                    "Sorry but this question has reached the limit of accepted answers.",
                    int(settings.MAXIMUM_ACCEPTED_ANSWERS)))

        if settings.MAXIMUM_ACCEPTED_PER_USER and question.accepted_count:
            accepted_from_author = question.accepted_answers.filter(
                author=answer.author).count()

            if accepted_from_author >= settings.MAXIMUM_ACCEPTED_PER_USER:
                raise CommandException(
                    ungettext(
                        "The author of this answer already has an accepted answer in this question.",
                        "Sorry but the author of this answer has reached the limit of accepted answers per question.",
                        int(settings.MAXIMUM_ACCEPTED_PER_USER)))

        AcceptAnswerAction(node=answer,
                           user=user,
                           ip=request.META['REMOTE_ADDR']).save()
        commands['mark_accepted'] = [answer.id]

    return {'commands': commands}
예제 #10
0
def matching_tags(request):
    if len(request.GET['q']) == 0:
        raise CommandException(_("Invalid request"))

    possible_tags = Tag.active.filter(name__icontains=request.GET['q'])
    tag_output = ''
    for tag in possible_tags:
        tag_output += "%s|%s|%s\n" % (tag.id, tag.name, tag.used_count)

    return HttpResponse(tag_output, mimetype="text/plain")
예제 #11
0
def matching_usernames(request):
    if len(request.GET['q']) == 0:
        raise CommandException(_("Invalid request"))

    possible_users = User.objects.filter(username__icontains=request.GET['q'])
    output = ''

    for user in possible_users:
        output += ("%s\n" % user.username)

    return HttpResponse(output, mimetype="text/plain")
예제 #12
0
def convert_to_question(request, id):
    user = request.user
    answer = get_object_or_404(Answer, id=id)
    question = answer.question

    if not request.POST:
        description = lambda a: _("Answer by %(uname)s: %(snippet)s...") % {
            'uname': a.author.username,
            'snippet': a.summary[:10]
        }
        nodes = [(question.id, _("Question"))]
        [
            nodes.append((a.id, description(a)))
            for a in question.answers.filter_state(deleted=False).exclude(
                id=answer.id)
        ]

        return render_to_response('node/convert_to_question.html',
                                  {'answer': answer})

    if not user.is_authenticated():
        raise AnonymousNotAllowedException(_("convert answers to questions"))

    if not user.can_convert_to_question(answer):
        raise NotEnoughRepPointsException(_("convert answers to questions"))

    try:
        title = request.POST.get('title', None)
    except:
        raise CommandException(
            _("You haven't specified the title of the new question"))

    AnswerToQuestionAction(
        user=user, node=answer,
        ip=request.META['REMOTE_ADDR']).save(data=dict(title=title))

    return RefreshPageCommand()
예제 #13
0
def comment(request, id):
    post = get_object_or_404(Node, id=id)
    user = request.user

    if not request.method == 'POST':
        raise CommandException(_("Invalid request"))

    vote_type = request.POST.get('vote_type', 'comment')
    is_voting = (vote_type in ('up', 'down'))

    if not user.is_authenticated():
        msg = is_voting and _('vote') or _('comment')
        raise AnonymousNotAllowedException(msg)

    from forum.models import CustomBadge
    if is_voting and CustomBadge.is_voting_restricted(user, post):
        msg = _(
            'Only users with the badge (or the badge owners) are allowed to vote.'
        )
        raise CommandException(msg)

    if is_voting and user == post.author:
        raise CannotDoOnOwnException(_('vote'))

    if vote_type == 'up' and not user.can_vote_up():
        raise NotEnoughRepPointsException(_('upvote'))

    if vote_type == 'down' and not user.can_vote_down():
        raise NotEnoughRepPointsException(_('downvote'))

    user_vote_count_today = user.get_vote_count_today()

    if is_voting and user_vote_count_today >= user.can_vote_count_today():
        raise NotEnoughLeftException(_('votes'),
                                     str(settings.MAX_VOTES_PER_DAY))

    comment_text = request.POST.get('comment', '').strip()

    if not len(comment_text):
        raise CommandException(_("Comment is empty"))

    if len(comment_text) < settings.FORM_MIN_COMMENT_BODY:
        raise CommandException(
            _("At least %d characters required on comment body.") %
            settings.FORM_MIN_COMMENT_BODY)

    if len(comment_text) > settings.FORM_MAX_COMMENT_BODY:
        raise CommandException(
            _("No more than %d characters on comment body.") %
            settings.FORM_MAX_COMMENT_BODY)

    old_vote = VoteAction.get_action_for(node=post, user=user)

    if is_voting and old_vote:
        is_too_old = (old_vote.action_date < datetime.datetime.now() -
                      datetime.timedelta(days=int(settings.DENY_UNVOTE_DAYS)))
        if is_too_old:
            raise CommandException(
                _("Sorry but you cannot cancel a vote after %(ndays)d %(tdays)s from the original vote"
                  ) % {
                      'ndays':
                      int(settings.DENY_UNVOTE_DAYS),
                      'tdays':
                      ungettext('day', 'days', int(settings.DENY_UNVOTE_DAYS))
                  })

    if 'id' in request.POST:
        comment = get_object_or_404(Comment, id=request.POST['id'])

        if not user.can_edit_comment(comment):
            raise NotEnoughRepPointsException(_('edit comments'))
    else:
        if not user.can_comment(post):
            raise NotEnoughRepPointsException(_('comment'))

    if is_voting:
        new_vote_cls = (vote_type == 'up') and VoteUpAction or VoteDownAction
        score_inc = 0

        if old_vote:
            old_vote.cancel(ip=request.META['REMOTE_ADDR'])
            score_inc += (old_vote.__class__ == VoteDownAction) and 1 or -1

        if old_vote.__class__ != new_vote_cls:
            new_vote_cls(user=user, node=post,
                         ip=request.META['REMOTE_ADDR']).save()
            score_inc += (new_vote_cls == VoteUpAction) and 1 or -1
        else:
            vote_type = "none"

    if 'id' in request.POST:
        comment = ReviseAction(user=user,
                               node=comment,
                               ip=request.META['REMOTE_ADDR']).save(data=dict(
                                   text=comment_text)).node
    else:
        comment = CommentAction(
            user=user, ip=request.META['REMOTE_ADDR']).save(
                data=dict(text=comment_text, parent=post)).node
        if not is_voting:
            comment_type = VoteComment.COMMENT
        elif old_vote.__class__ != new_vote_cls and new_vote_cls == VoteUpAction:
            comment_type = VoteComment.VOTE_UP
        elif old_vote.__class__ != new_vote_cls and new_vote_cls != VoteUpAction:
            comment_type = VoteComment.VOTE_DOWN
        elif old_vote.__class__ == VoteUpAction:
            comment_type = VoteComment.CANCEL_VOTE_UP
        else:
            comment_type = VoteComment.CANCEL_VOTE_DOWN
        vote_comment = VoteComment(comment_type=comment_type, comment=comment)
        vote_comment.save()

    if comment.active_revision.revision == 1:
        response = {
            'commands': {
                'insert_comment': [
                    id, comment.id, comment.comment, user.decorated_name,
                    user.get_profile_url(),
                    reverse('delete_comment', kwargs={'id': comment.id}),
                    reverse('node_markdown', kwargs={'id': comment.id}),
                    reverse('convert_comment', kwargs={'id': comment.id}),
                    user.can_delete_comment(comment)
                ]
            }
        }
    else:
        response = {
            'commands': {
                'update_comment': [comment.id, comment.comment]
            }
        }

    if is_voting:
        response['commands']['update_post_score'] = [id, score_inc]
        response['commands']['update_user_post_vote'] = [id, vote_type]

        votes_left = (int(settings.MAX_VOTES_PER_DAY) -
                      user_vote_count_today) + (vote_type == 'none' and -1
                                                or 1)

        if int(settings.START_WARN_VOTES_LEFT) >= votes_left:
            response['message'] = _("You have %(nvotes)s %(tvotes)s left today.") % \
                                     {'nvotes': votes_left, 'tvotes': ungettext('vote', 'votes', votes_left)}

    return response