예제 #1
0
 def test_anon_user_with_author(self):
     mock_akismet()
     request = AuthRequest(anon=True)
     akismet_check_spam(TEXT, request, author=User())
     params = get_request_params(1)
     self.assertEqual(params['comment_content'], TEXT)
     self.assertEqual(params['user_ip'], USER_IP)
     self.assertEqual(params['user_agent'], USER_AGENT)
     self.assertEqual(params['blog'], 'http://askbot.com/questions/')
     self.assertEqual(params['comment_author'], COMMENT_AUTHOR)
     self.assertEqual(params['comment_author_email'], COMMENT_AUTHOR_EMAIL)
예제 #2
0
 def test_anon_user_no_author(self):
     mock_akismet()
     request = AuthRequest(anon=True)
     akismet_check_spam(TEXT, request)
     params = get_request_params(1)
     self.assertEqual(params['comment_content'], TEXT)
     self.assertEqual(params['user_ip'], USER_IP)
     self.assertEqual(params['user_agent'], USER_AGENT)
     self.assertEqual(params['blog'], 'http://askbot.com/questions/')
     self.assertTrue('comment_author' not in params)
     self.assertTrue('comment_author_email' not in params)
예제 #3
0
 def test_auth_user_no_author(self):
     mock_akismet()
     request = AuthRequest(username='******', email='*****@*****.**')
     akismet_check_spam(TEXT, request)
     params = get_request_params(1)
     self.assertEqual(params['comment_content'], TEXT)
     self.assertEqual(params['user_ip'], USER_IP)
     self.assertEqual(params['user_agent'], USER_AGENT)
     self.assertEqual(params['blog'], 'http://askbot.com/questions/')
     self.assertEqual(params['comment_author'], 'Request User')
     self.assertEqual(params['comment_author_email'], '*****@*****.**')
예제 #4
0
 def test_anon_user_with_author(self):
     mock_akismet()
     request = AuthRequest(anon=True)
     akismet_check_spam(TEXT, request, author=User())
     params = get_request_params(1)
     self.assertEqual(params['comment_content'], TEXT)
     self.assertEqual(params['user_ip'], USER_IP)
     self.assertEqual(params['user_agent'], USER_AGENT)
     self.assertEqual(params['blog'], 'http://askbot.com/questions/')
     self.assertEqual(params['comment_author'], COMMENT_AUTHOR)
     self.assertEqual(params['comment_author_email'], COMMENT_AUTHOR_EMAIL)
예제 #5
0
 def test_anon_user_no_author(self):
     mock_akismet()
     request = AuthRequest(anon=True)
     akismet_check_spam(TEXT, request)
     params = get_request_params(1)
     self.assertEqual(params['comment_content'], TEXT)
     self.assertEqual(params['user_ip'], USER_IP)
     self.assertEqual(params['user_agent'], USER_AGENT)
     self.assertEqual(params['blog'], 'http://askbot.com/questions/')
     self.assertTrue('comment_author' not in params)
     self.assertTrue('comment_author_email' not in params)
예제 #6
0
 def test_auth_user_no_author(self):
     mock_akismet()
     request = AuthRequest(username='******',
                           email='*****@*****.**')
     akismet_check_spam(TEXT, request)
     params = get_request_params(1)
     self.assertEqual(params['comment_content'], TEXT)
     self.assertEqual(params['user_ip'], USER_IP)
     self.assertEqual(params['user_agent'], USER_AGENT)
     self.assertEqual(params['blog'], 'http://askbot.com/questions/')
     self.assertEqual(params['comment_author'], 'Request User')
     self.assertEqual(params['comment_author_email'], '*****@*****.**')
예제 #7
0
def retag_question(request, id):
    """retag question view
    """
    question = get_object_or_404(models.Post, id=id)

    try:
        request.user.assert_can_retag_question(question)
        if request.method == 'POST':
            form = forms.RetagQuestionForm(question, request.POST)

            if form.is_valid():
                if form.has_changed():
                    if akismet_check_spam(form.cleaned_data['tags'], request):
                        raise exceptions.PermissionDenied(_(
                            'Spam was detected on your post, sorry '
                            'for if this is a mistake'
                        ))
                    request.user.retag_question(question=question, tags=form.cleaned_data['tags'])
                if request.is_ajax():
                    response_data = {
                        'success': True,
                        'new_tags': question.thread.tagnames
                    }

                    if request.user.message_set.count() > 0:
                        #todo: here we will possibly junk messages
                        message = request.user.get_and_delete_messages()[-1]
                        response_data['message'] = message

                    data = simplejson.dumps(response_data)
                    return HttpResponse(data, content_type="application/json")
                else:
                    return HttpResponseRedirect(question.get_absolute_url())
            elif request.is_ajax():
                response_data = {
                    'message': format_errors(form.errors['tags']),
                    'success': False
                }
                data = simplejson.dumps(response_data)
                return HttpResponse(data, content_type="application/json")
        else:
            form = forms.RetagQuestionForm(question)

        data = {
            'active_tab': 'questions',
            'question': question,
            'form' : form,
        }
        return render(request, 'question_retag.html', data)
    except exceptions.PermissionDenied as e:
        if request.is_ajax():
            response_data = {
                'message': unicode(e),
                'success': False
            }
            data = simplejson.dumps(response_data)
            return HttpResponse(data, content_type="application/json")
        else:
            request.user.message_set.create(message = unicode(e))
            return HttpResponseRedirect(question.get_absolute_url())
예제 #8
0
        def wrapper(request, *args, **kwargs):

            if askbot_settings.USE_AKISMET and request.method == "POST":
                if field not in request.POST:
                    raise Http404

                comment = smart_str(request.POST[field])
                if akismet_check_spam(comment, request):
                    logging.debug(
                        'Spam detected in %s post at: %s',
                        request.user.username,
                        timezone.now()
                    )
                    spam_message = _(
                        'Spam was detected on your post, sorry '
                        'for if this is a mistake'
                    )
                    if request.is_ajax():
                        return HttpResponseForbidden(
                                spam_message,
                                content_type="application/json"
                            )
                    else:
                        request.user.message_set.create(message=spam_message)
                        return HttpResponseRedirect(reverse('index'))

            return view_func(request, *args, **kwargs)
예제 #9
0
def retag_question(request, id):
    """retag question view
    """
    question = get_object_or_404(models.Post, id=id)

    try:
        request.user.assert_can_retag_question(question)
        if request.method == 'POST':
            form = forms.RetagQuestionForm(question, request.POST)

            if form.is_valid():
                if form.has_changed():
                    text = question.get_text_content(tags=form.cleaned_data['tags'])
                    if akismet_check_spam(text, request):
                        message = _('Spam was detected on your post, sorry if it was a mistake')
                        raise exceptions.PermissionDenied(message)

                    request.user.retag_question(question=question, tags=form.cleaned_data['tags'])
                if request.is_ajax():
                    response_data = {
                        'success': True,
                        'new_tags': question.thread.tagnames
                    }

                    if request.user.message_set.count() > 0:
                        #todo: here we will possibly junk messages
                        message = request.user.get_and_delete_messages()[-1]
                        response_data['message'] = message

                    data = simplejson.dumps(response_data)
                    return HttpResponse(data, content_type="application/json")
                else:
                    return HttpResponseRedirect(question.get_absolute_url())
            elif request.is_ajax():
                response_data = {
                    'message': format_errors(form.errors['tags']),
                    'success': False
                }
                data = simplejson.dumps(response_data)
                return HttpResponse(data, content_type="application/json")
        else:
            form = forms.RetagQuestionForm(question)

        data = {
            'active_tab': 'questions',
            'question': question,
            'form' : form,
        }
        return render(request, 'question_retag.html', data)
    except exceptions.PermissionDenied as e:
        if request.is_ajax():
            response_data = {
                'message': unicode(e),
                'success': False
            }
            data = simplejson.dumps(response_data)
            return HttpResponse(data, content_type="application/json")
        else:
            request.user.message_set.create(message = unicode(e))
            return HttpResponseRedirect(question.get_absolute_url())
예제 #10
0
def edit_comment(request):
    if request.user.is_anonymous():
        raise exceptions.PermissionDenied(_('Sorry, anonymous users cannot edit comments'))

    if askbot_settings.READ_ONLY_MODE_ENABLED:
        raise exceptions.PermissionDenied(askbot_settings.READ_ONLY_MESSAGE)

    form = forms.EditCommentForm(request.POST)
    if form.is_valid() == False:
        raise exceptions.PermissionDenied('This content is forbidden')

    if akismet_check_spam(form.cleaned_data['comment'], request):
        raise exceptions.PermissionDenied(_(
            'Spam was detected on your post, sorry '
            'for if this is a mistake'
        ))

    comment_post = models.Post.objects.get(
                    post_type='comment',
                    id=form.cleaned_data['comment_id']
                )

    revision = request.user.edit_comment(
        comment_post=comment_post,
        body_text=form.cleaned_data['comment'],
        suppress_email=form.cleaned_data['suppress_email'],
        ip_addr=request.META.get('REMOTE_ADDR'),
    )

    is_deletable = template_filters.can_delete_comment(
                            comment_post.author, comment_post)

    is_editable = template_filters.can_edit_comment(
                            comment_post.author, comment_post)

    tz = ' ' + template_filters.TIMEZONE_STR

    tz = template_filters.TIMEZONE_STR
    timestamp = str(comment_post.added_at.replace(microsecond=0)) + tz

    #need this because the post.text is due to the latest approved
    #revision, but we may need the suggested revision
    comment_post.text = revision.text
    comment_post.html = comment_post.parse_post_text()['html']

    return {
        'id' : comment_post.id,
        'object_id': comment_post.parent.id,
        'comment_added_at': timestamp,
        'html': comment_post.html,
        'user_display_name': escape(comment_post.author.username),
        'user_url': comment_post.author.get_profile_url(),
        'user_id': comment_post.author.id,
        'is_deletable': is_deletable,
        'is_editable': is_editable,
        'score': comment_post.points, #to support unchanged js
        'points': comment_post.points,
        'voted': comment_post.is_upvoted_by(request.user),
    }
예제 #11
0
def edit_comment(request):
    if request.user.is_anonymous():
        raise exceptions.PermissionDenied(_('Sorry, anonymous users cannot edit comments'))

    if askbot_settings.READ_ONLY_MODE_ENABLED:
        raise exceptions.PermissionDenied(askbot_settings.READ_ONLY_MESSAGE)

    form = forms.EditCommentForm(request.POST)
    if form.is_valid() == False:
        raise exceptions.PermissionDenied('This content is forbidden')

    if akismet_check_spam(form.cleaned_data['comment'], request):
        raise exceptions.PermissionDenied(_(
            'Spam was detected on your post, sorry '
            'for if this is a mistake'
        ))

    comment_post = models.Post.objects.get(
                    post_type='comment',
                    id=form.cleaned_data['comment_id']
                )

    revision = request.user.edit_comment(
        comment_post=comment_post,
        body_text=form.cleaned_data['comment'],
        suppress_email=form.cleaned_data['suppress_email'],
        ip_addr=request.META.get('REMOTE_ADDR'),
    )

    is_deletable = template_filters.can_delete_comment(
                            comment_post.author, comment_post)

    is_editable = template_filters.can_edit_comment(
                            comment_post.author, comment_post)

    tz = ' ' + template_filters.TIMEZONE_STR

    tz = template_filters.TIMEZONE_STR
    timestamp = str(comment_post.added_at.replace(microsecond=0)) + tz

    #need this because the post.text is due to the latest approved
    #revision, but we may need the suggested revision
    comment_post.text = revision.text
    comment_post.html = comment_post.parse_post_text()['html']

    return {
        'id' : comment_post.id,
        'object_id': comment_post.parent.id,
        'comment_added_at': timestamp,
        'html': comment_post.html,
        'user_display_name': escape(comment_post.author.username),
        'user_url': comment_post.author.get_profile_url(),
        'user_id': comment_post.author.id,
        'is_deletable': is_deletable,
        'is_editable': is_editable,
        'score': comment_post.points, #to support unchanged js
        'points': comment_post.points,
        'voted': comment_post.is_upvoted_by(request.user),
    }
예제 #12
0
def edit_answer(request, id):
    answer = get_object_or_404(models.Post, id=id)

    if askbot_settings.READ_ONLY_MODE_ENABLED:
        return HttpResponseRedirect(answer.get_absolute_url())

    try:
        revision = answer.revisions.get(revision=0)
    except models.PostRevision.DoesNotExist:
        revision = answer.get_latest_revision()

    class_path = getattr(settings, 'ASKBOT_EDIT_ANSWER_FORM', None)
    if class_path:
        edit_answer_form_class = load_module(class_path)
    else:
        edit_answer_form_class = forms.EditAnswerForm

    try:
        request.user.assert_can_edit_answer(answer)
        if request.method == "POST":
            if request.POST['select_revision'] == 'true':
                # user has changed revistion number
                revision_form = forms.RevisionForm(answer, revision,
                                                   request.POST)
                if revision_form.is_valid():
                    # Replace with those from the selected revision
                    rev = revision_form.cleaned_data['revision']
                    revision = answer.revisions.get(revision=rev)
                    form = edit_answer_form_class(answer,
                                                  revision,
                                                  user=request.user)
                else:
                    form = edit_answer_form_class(answer,
                                                  revision,
                                                  request.POST,
                                                  user=request.user)
            else:
                form = edit_answer_form_class(answer,
                                              revision,
                                              request.POST,
                                              user=request.user)
                revision_form = forms.RevisionForm(answer, revision)

                if form.is_valid():
                    if form.has_changed():
                        user = form.get_post_user(request.user)
                        suppress_email = form.cleaned_data['suppress_email']
                        is_private = form.cleaned_data.get(
                            'post_privately', False)

                        text = form.cleaned_data['text']
                        if akismet_check_spam(text, request):
                            message = _(
                                'Spam was detected on your post, sorry if it was a mistake'
                            )
                            raise exceptions.PermissionDenied(message)

                        user.edit_answer(
                            answer=answer,
                            body_text=text,
                            revision_comment=form.cleaned_data['summary'],
                            wiki=form.cleaned_data.get('wiki', answer.wiki),
                            is_private=is_private,
                            suppress_email=suppress_email,
                            ip_addr=request.META.get('REMOTE_ADDR'))

                        signals.answer_edited.send(None,
                                                   answer=answer,
                                                   user=user,
                                                   form_data=form.cleaned_data)

                    return HttpResponseRedirect(answer.get_absolute_url())
        else:
            revision_form = forms.RevisionForm(answer, revision)
            form = edit_answer_form_class(answer, revision, user=request.user)
            if request.user.can_make_group_private_posts():
                form.initial['post_privately'] = answer.is_private()

        data = {
            'page_class': 'edit-answer-page',
            'active_tab': 'questions',
            'answer': answer,
            'revision': revision,
            'revision_form': revision_form,
            'form': form,
        }
        extra_context = context.get_extra(
            'ASKBOT_EDIT_ANSWER_PAGE_EXTRA_CONTEXT', request, data)
        data.update(extra_context)

        return render(request, 'answer_edit.html', data)

    except exceptions.PermissionDenied as e:
        request.user.message_set.create(message=unicode(e))
        return HttpResponseRedirect(answer.get_absolute_url())
예제 #13
0
def ask(request):#view used to ask a new question
    """a view to ask a new question
    gives space for q title, body, tags and checkbox for to post as wiki

    user can start posting a question anonymously but then
    must login/register in order for the question go be shown
    """
    if request.user.is_authenticated():
        if request.user.is_read_only():
            referer = request.META.get("HTTP_REFERER", reverse('questions'))
            request.user.message_set.create(message=_('Sorry, but you have only read access'))
            return HttpResponseRedirect(referer)

    if askbot_settings.READ_ONLY_MODE_ENABLED:
        return HttpResponseRedirect(reverse('index'))

    if request.method == 'POST':
        form = forms.AskForm(request.POST, user=request.user)
        if form.is_valid():
            timestamp = timezone.now()
            title = form.cleaned_data['title']
            wiki = form.cleaned_data['wiki']
            tagnames = form.cleaned_data['tags']
            text = form.cleaned_data['text']
            ask_anonymously = form.cleaned_data['ask_anonymously']
            post_privately = form.cleaned_data['post_privately']
            group_id = form.cleaned_data.get('group_id', None)
            language = form.cleaned_data.get('language', None)

            content = u'{}\n\n{}\n\n{}'.format(title, tagnames, text)
            if akismet_check_spam(content, request):
                message = _('Spam was detected on your post, sorry if it was a mistake')
                raise exceptions.PermissionDenied(message)

            if request.user.is_authenticated():
                drafts = models.DraftQuestion.objects.filter(author=request.user)
                drafts.delete()
                user = form.get_post_user(request.user)
            elif request.user.is_anonymous() and askbot_settings.ALLOW_ASK_UNREGISTERED:
                user = models.get_or_create_anonymous_user()
                ask_anonymously = True
            else:
                user = None

            if user:
                try:
                    question = user.post_question(
                        title=title,
                        body_text=text,
                        tags=tagnames,
                        wiki=wiki,
                        is_anonymous=ask_anonymously,
                        is_private=post_privately,
                        timestamp=timestamp,
                        group_id=group_id,
                        language=language,
                        ip_addr=request.META.get('REMOTE_ADDR')
                    )
                    signals.new_question_posted.send(None,
                        question=question,
                        user=user,
                        form_data=form.cleaned_data
                    )
                    return HttpResponseRedirect(question.get_absolute_url())
                except exceptions.PermissionDenied as e:
                    request.user.message_set.create(message = unicode(e))
                    return HttpResponseRedirect(reverse('index'))

            else:
                session_key=request.session.session_key
                if session_key is None:
                    return HttpResponseForbidden()

                models.AnonymousQuestion.objects.create(
                    session_key=session_key,
                    title=title,
                    tagnames=tagnames,
                    wiki=wiki,
                    is_anonymous=ask_anonymously,
                    text=text,
                    added_at=timestamp,
                    ip_addr=request.META.get('REMOTE_ADDR'),
                )
                return HttpResponseRedirect(url_utils.get_login_url())

    if request.method == 'GET':
        form = forms.AskForm(user=request.user)
        #session key used only to enable anonymous asking
        #as django will autodelete empty sessions
        request.session['askbot_write_intent'] = True

    draft_title = ''
    draft_text = ''
    draft_tagnames = ''
    if request.user.is_authenticated():
        drafts = models.DraftQuestion.objects.filter(author=request.user)
        if len(drafts) > 0:
            draft = drafts[0]
            draft_title = draft.title
            draft_text = draft.get_text()
            draft_tagnames = draft.tagnames

    form.initial = {
        'ask_anonymously': request.REQUEST.get('ask_anonymously', False),
        'tags': request.REQUEST.get('tags', draft_tagnames),
        'text': request.REQUEST.get('text', draft_text),
        'title': request.REQUEST.get('title', draft_title),
        'post_privately': request.REQUEST.get('post_privately', False),
        'language': get_language(),
        'wiki': request.REQUEST.get('wiki', False),
    }
    if 'group_id' in request.REQUEST:
        try:
            group_id = int(request.GET.get('group_id', None))
            form.initial['group_id'] = group_id
        except Exception:
            pass

    editor_is_folded = (askbot_settings.QUESTION_BODY_EDITOR_MODE=='folded' and \
                        askbot_settings.MIN_QUESTION_BODY_LENGTH==0 and \
                        form.initial['text'] == '')

    data = {
        'active_tab': 'ask',
        'page_class': 'ask-page',
        'form' : form,
        'editor_is_folded': editor_is_folded,
        'mandatory_tags': models.tag.get_mandatory_tags(),
        'email_validation_faq_url':reverse('faq') + '#validate',
        'category_tree_data': askbot_settings.CATEGORY_TREE,
        'tag_names': forms.split_tags(form.initial['tags'])
    }
    data.update(context.get_for_tag_editor())
    return render(request, 'ask.html', data)
예제 #14
0
def ask(request):  #view used to ask a new question
    """a view to ask a new question
    gives space for q title, body, tags and checkbox for to post as wiki

    user can start posting a question anonymously but then
    must login/register in order for the question go be shown
    """
    if request.user.is_authenticated():
        if request.user.is_read_only():
            referer = request.META.get("HTTP_REFERER", reverse('questions'))
            request.user.message_set.create(
                message=_('Sorry, but you have only read access'))
            return HttpResponseRedirect(referer)

    if askbot_settings.READ_ONLY_MODE_ENABLED:
        return HttpResponseRedirect(reverse('index'))

    if request.method == 'POST':
        form = forms.AskForm(request.POST, user=request.user)
        if form.is_valid():
            timestamp = timezone.now()
            title = form.cleaned_data['title']
            wiki = form.cleaned_data['wiki']
            tagnames = form.cleaned_data['tags']
            text = form.cleaned_data['text']
            ask_anonymously = form.cleaned_data['ask_anonymously']
            post_privately = form.cleaned_data['post_privately']
            group_id = form.cleaned_data.get('group_id', None)
            language = form.cleaned_data.get('language', None)

            content = '{}\n\n{}\n\n{}'.format(title, tagnames, text)
            if akismet_check_spam(content, request):
                message = _(
                    'Spam was detected on your post, sorry if it was a mistake'
                )
                raise exceptions.PermissionDenied(message)

            if request.user.is_authenticated():
                drafts = models.DraftQuestion.objects.filter(
                    author=request.user)
                drafts.delete()
                user = form.get_post_user(request.user)
            elif request.user.is_anonymous(
            ) and askbot_settings.ALLOW_ASK_UNREGISTERED:
                user = models.get_or_create_anonymous_user()
                ask_anonymously = True
            else:
                user = None

            if user:
                try:
                    question = user.post_question(
                        title=title,
                        body_text=text,
                        tags=tagnames,
                        wiki=wiki,
                        is_anonymous=ask_anonymously,
                        is_private=post_privately,
                        timestamp=timestamp,
                        group_id=group_id,
                        language=language,
                        ip_addr=request.META.get('REMOTE_ADDR'))
                    signals.new_question_posted.send(
                        None,
                        question=question,
                        user=user,
                        form_data=form.cleaned_data)
                    return HttpResponseRedirect(question.get_absolute_url())
                except exceptions.PermissionDenied as e:
                    request.user.message_set.create(message=unicode(e))
                    return HttpResponseRedirect(reverse('index'))

            else:
                session_key = request.session.session_key
                if session_key is None:
                    return HttpResponseForbidden()

                models.AnonymousQuestion.objects.create(
                    session_key=session_key,
                    title=title,
                    tagnames=tagnames,
                    wiki=wiki,
                    is_anonymous=ask_anonymously,
                    text=text,
                    added_at=timestamp,
                    ip_addr=request.META.get('REMOTE_ADDR'),
                )
                return HttpResponseRedirect(url_utils.get_login_url())

    if request.method == 'GET':
        form = forms.AskForm(user=request.user)
        #session key used only to enable anonymous asking
        #as django will autodelete empty sessions
        request.session['askbot_write_intent'] = True

    draft_title = ''
    draft_text = ''
    draft_tagnames = ''
    if request.user.is_authenticated():
        drafts = models.DraftQuestion.objects.filter(author=request.user)
        if len(drafts) > 0:
            draft = drafts[0]
            draft_title = draft.title
            draft_text = draft.get_text()
            draft_tagnames = draft.tagnames

    form.initial = {
        'ask_anonymously': request.REQUEST.get('ask_anonymously', False),
        'tags': request.REQUEST.get('tags', draft_tagnames),
        'text': request.REQUEST.get('text', draft_text),
        'title': request.REQUEST.get('title', draft_title),
        'post_privately': request.REQUEST.get('post_privately', False),
        'language': get_language(),
        'wiki': request.REQUEST.get('wiki', False),
    }
    if 'group_id' in request.REQUEST:
        try:
            group_id = int(request.GET.get('group_id', None))
            form.initial['group_id'] = group_id
        except Exception:
            pass

    editor_is_folded = (askbot_settings.QUESTION_BODY_EDITOR_MODE=='folded' and \
                        askbot_settings.MIN_QUESTION_BODY_LENGTH==0 and \
                        form.initial['text'] == '')

    data = {
        'active_tab': 'ask',
        'page_class': 'ask-page',
        'form': form,
        'editor_is_folded': editor_is_folded,
        'mandatory_tags': models.tag.get_mandatory_tags(),
        'email_validation_faq_url': reverse('faq') + '#validate',
        'category_tree_data': askbot_settings.CATEGORY_TREE,
        'tag_names': forms.split_tags(form.initial['tags'])
    }
    data.update(context.get_for_tag_editor())
    return render(request, 'ask.html', data)
예제 #15
0
def edit_question(request, id):
    """edit question view
    """
    question = get_object_or_404(models.Post, id=id)

    if askbot_settings.READ_ONLY_MODE_ENABLED:
        return HttpResponseRedirect(question.get_absolute_url())

    try:
        revision = question.revisions.get(revision=0)
    except models.PostRevision.DoesNotExist:
        revision = question.get_latest_revision()

    revision_form = None

    try:
        request.user.assert_can_edit_question(question)
        if request.method == 'POST':
            if request.POST['select_revision'] == 'true':
                #revert-type edit - user selected previous revision
                revision_form = forms.RevisionForm(question, revision,
                                                   request.POST)
                if revision_form.is_valid():
                    # Replace with those from the selected revision
                    rev_id = revision_form.cleaned_data['revision']
                    revision = question.revisions.get(revision=rev_id)
                    form = forms.EditQuestionForm(question=question,
                                                  user=request.user,
                                                  revision=revision)
                else:
                    form = forms.EditQuestionForm(request.POST,
                                                  question=question,
                                                  user=question.user,
                                                  revision=revision)
            else:  #new content edit
                # Always check modifications against the latest revision
                form = forms.EditQuestionForm(
                    request.POST,
                    question=question,
                    revision=revision,
                    user=request.user,
                )
                revision_form = forms.RevisionForm(question, revision)
                if form.is_valid():
                    if form.has_changed():

                        if form.can_edit_anonymously(
                        ) and form.cleaned_data['reveal_identity']:
                            question.thread.remove_author_anonymity()
                            question.is_anonymous = False

                        is_wiki = form.cleaned_data.get('wiki', question.wiki)
                        post_privately = form.cleaned_data['post_privately']
                        suppress_email = form.cleaned_data['suppress_email']

                        user = form.get_post_user(request.user)

                        content = question.get_text_content(
                            title=form.cleaned_data['title'],
                            body_text=form.cleaned_data['text'],
                            tags=form.cleaned_data['tags'])
                        if akismet_check_spam(content, request):
                            message = _(
                                'Spam was detected on your post, sorry if it was a mistake'
                            )
                            raise exceptions.PermissionDenied(message)

                        user.edit_question(
                            question=question,
                            title=form.cleaned_data['title'],
                            body_text=form.cleaned_data['text'],
                            revision_comment=form.cleaned_data['summary'],
                            tags=form.cleaned_data['tags'],
                            wiki=is_wiki,
                            edit_anonymously=form.
                            cleaned_data['edit_anonymously'],
                            is_private=post_privately,
                            suppress_email=suppress_email,
                            ip_addr=request.META.get('REMOTE_ADDR'))

                        if 'language' in form.cleaned_data:
                            question.thread.set_language_code(
                                form.cleaned_data['language'])

                    return HttpResponseRedirect(question.get_absolute_url())
        else:
            #request type was "GET"
            revision_form = forms.RevisionForm(question, revision)
            initial = {
                'language': question.thread.language_code,
                'post_privately': question.is_private(),
                'wiki': question.wiki
            }
            form = forms.EditQuestionForm(question=question,
                                          revision=revision,
                                          user=request.user,
                                          initial=initial)

        data = {
            'page_class': 'edit-question-page',
            'active_tab': 'questions',
            'question': question,
            'revision': revision,
            'revision_form': revision_form,
            'mandatory_tags': models.tag.get_mandatory_tags(),
            'form': form,
            'tag_names': question.thread.get_tag_names(),
            'category_tree_data': askbot_settings.CATEGORY_TREE
        }
        data.update(context.get_for_tag_editor())
        return render(request, 'question_edit.html', data)

    except exceptions.PermissionDenied as e:
        request.user.message_set.create(message=unicode(e))
        return HttpResponseRedirect(question.get_absolute_url())
예제 #16
0
def edit_question(request, id):
    """edit question view
    """
    question = get_object_or_404(models.Post, id=id)

    if askbot_settings.READ_ONLY_MODE_ENABLED:
        return HttpResponseRedirect(question.get_absolute_url())

    try:
        revision = question.revisions.get(revision=0)
    except models.PostRevision.DoesNotExist:
        revision = question.get_latest_revision()

    revision_form = None

    try:
        request.user.assert_can_edit_question(question)
        if request.method == 'POST':
            if request.POST['select_revision'] == 'true':
                #revert-type edit - user selected previous revision
                revision_form = forms.RevisionForm(
                                                question,
                                                revision,
                                                request.POST
                                            )
                if revision_form.is_valid():
                    # Replace with those from the selected revision
                    rev_id = revision_form.cleaned_data['revision']
                    revision = question.revisions.get(revision = rev_id)
                    form = forms.EditQuestionForm(
                                            question=question,
                                            user=request.user,
                                            revision=revision
                                        )
                else:
                    form = forms.EditQuestionForm(
                                            request.POST,
                                            question=question,
                                            user=question.user,
                                            revision=revision
                                        )
            else:#new content edit
                # Always check modifications against the latest revision
                form = forms.EditQuestionForm(
                                        request.POST,
                                        question=question,
                                        revision=revision,
                                        user=request.user,
                                    )
                revision_form = forms.RevisionForm(question, revision)
                if form.is_valid():
                    if form.has_changed():

                        if form.can_edit_anonymously() and form.cleaned_data['reveal_identity']:
                            question.thread.remove_author_anonymity()
                            question.is_anonymous = False

                        is_wiki = form.cleaned_data.get('wiki', question.wiki)
                        post_privately = form.cleaned_data['post_privately']
                        suppress_email = form.cleaned_data['suppress_email']

                        user = form.get_post_user(request.user)

                        content = question.get_text_content(title=form.cleaned_data['title'],
                                                            body_text=form.cleaned_data['text'],
                                                            tags=form.cleaned_data['tags'])
                        if akismet_check_spam(content, request):
                            message = _('Spam was detected on your post, sorry if it was a mistake')
                            raise exceptions.PermissionDenied(message)

                        user.edit_question(
                            question=question,
                            title=form.cleaned_data['title'],
                            body_text=form.cleaned_data['text'],
                            revision_comment=form.cleaned_data['summary'],
                            tags=form.cleaned_data['tags'],
                            wiki=is_wiki,
                            edit_anonymously=form.cleaned_data['edit_anonymously'],
                            is_private=post_privately,
                            suppress_email=suppress_email,
                            ip_addr=request.META.get('REMOTE_ADDR')
                        )

                        if 'language' in form.cleaned_data:
                            question.thread.set_language_code(form.cleaned_data['language'])

                    return HttpResponseRedirect(question.get_absolute_url())
        else:
            #request type was "GET"
            revision_form = forms.RevisionForm(question, revision)
            initial = {
                'language': question.thread.language_code,
                'post_privately': question.is_private(),
                'wiki': question.wiki
            }
            form = forms.EditQuestionForm(
                                    question=question,
                                    revision=revision,
                                    user=request.user,
                                    initial=initial
                                )

        data = {
            'page_class': 'edit-question-page',
            'active_tab': 'questions',
            'question': question,
            'revision': revision,
            'revision_form': revision_form,
            'mandatory_tags': models.tag.get_mandatory_tags(),
            'form' : form,
            'tag_names': question.thread.get_tag_names(),
            'category_tree_data': askbot_settings.CATEGORY_TREE
        }
        data.update(context.get_for_tag_editor())
        return render(request, 'question_edit.html', data)

    except exceptions.PermissionDenied as e:
        request.user.message_set.create(message = unicode(e))
        return HttpResponseRedirect(question.get_absolute_url())
예제 #17
0
def answer(request, id, form_class=forms.AnswerForm):#process a new answer
    """view that posts new answer

    anonymous users post into anonymous storage
    and redirected to login page

    authenticated users post directly
    """
    question = get_object_or_404(models.Post, post_type='question', id=id)

    if askbot_settings.READ_ONLY_MODE_ENABLED:
        return HttpResponseRedirect(question.get_absolute_url())

    if request.method == 'GET':
        #session key used only to enable anonymous asking
        #as django will autodelete empty sessions
        request.session['askbot_write_intent'] = True
    elif request.method == 'POST':

        #this check prevents backward compatilibility
        if form_class == forms.AnswerForm:
            custom_class_path = getattr(settings, 'ASKBOT_NEW_ANSWER_FORM', None)
            if custom_class_path:
                form_class = load_module(custom_class_path)
            else:
                form_class = forms.AnswerForm

        form = form_class(request.POST, user=request.user)

        if form.is_valid():
            if request.user.is_authenticated():
                drafts = models.DraftAnswer.objects.filter(
                                                author=request.user,
                                                thread=question.thread
                                            )
                drafts.delete()
                user = form.get_post_user(request.user)
                try:
                    text = form.cleaned_data['text']
                    if akismet_check_spam(text, request):
                        message = _('Spam was detected on your post, sorry if it was a mistake')
                        raise exceptions.PermissionDenied(message)

                    answer = form.save(
                                    question,
                                    user,
                                    ip_addr=request.META.get('REMOTE_ADDR')
                                )

                    signals.new_answer_posted.send(None,
                        answer=answer,
                        user=user,
                        form_data=form.cleaned_data
                    )

                    return HttpResponseRedirect(answer.get_absolute_url())
                except askbot_exceptions.AnswerAlreadyGiven as e:
                    request.user.message_set.create(message = unicode(e))
                    answer = question.thread.get_answers_by_user(user)[0]
                    return HttpResponseRedirect(answer.get_absolute_url())
                except exceptions.PermissionDenied as e:
                    request.user.message_set.create(message = unicode(e))
            else:
                if request.session.session_key is None:
                    return HttpResponseForbidden()

                models.AnonymousAnswer.objects.create(
                    question=question,
                    wiki=form.cleaned_data['wiki'],
                    text=form.cleaned_data['text'],
                    session_key=request.session.session_key,
                    ip_addr=request.META.get('REMOTE_ADDR'),
                )
                return HttpResponseRedirect(url_utils.get_login_url())

    #TODO: look into an issue here is that backend form validation errors
    # won't be displayed, we are fully relying on the prevalidation
    # in the js
    return HttpResponseRedirect(question.get_absolute_url())
예제 #18
0
def edit_answer(request, id):
    answer = get_object_or_404(models.Post, id=id)

    if askbot_settings.READ_ONLY_MODE_ENABLED:
        return HttpResponseRedirect(answer.get_absolute_url())

    try:
        revision = answer.revisions.get(revision=0)
    except models.PostRevision.DoesNotExist:
        revision = answer.get_latest_revision()

    class_path = getattr(settings, 'ASKBOT_EDIT_ANSWER_FORM', None)
    if class_path:
        edit_answer_form_class = load_module(class_path)
    else:
        edit_answer_form_class = forms.EditAnswerForm

    try:
        request.user.assert_can_edit_answer(answer)
        if request.method == "POST":
            if request.POST['select_revision'] == 'true':
                # user has changed revistion number
                revision_form = forms.RevisionForm(
                                                answer,
                                                revision,
                                                request.POST
                                            )
                if revision_form.is_valid():
                    # Replace with those from the selected revision
                    rev = revision_form.cleaned_data['revision']
                    revision = answer.revisions.get(revision = rev)
                    form = edit_answer_form_class(
                                    answer, revision, user=request.user
                                )
                else:
                    form = edit_answer_form_class(
                                                answer,
                                                revision,
                                                request.POST,
                                                user=request.user
                                            )
            else:
                form = edit_answer_form_class(
                    answer, revision, request.POST, user=request.user
                )
                revision_form = forms.RevisionForm(answer, revision)

                if form.is_valid():
                    if form.has_changed():
                        user = form.get_post_user(request.user)
                        suppress_email = form.cleaned_data['suppress_email']
                        is_private = form.cleaned_data.get('post_privately', False)

                        text = form.cleaned_data['text']
                        if akismet_check_spam(text, request):
                            message = _('Spam was detected on your post, sorry if it was a mistake')
                            raise exceptions.PermissionDenied(message)

                        user.edit_answer(
                            answer=answer,
                            body_text=text,
                            revision_comment=form.cleaned_data['summary'],
                            wiki=form.cleaned_data.get('wiki', answer.wiki),
                            is_private=is_private,
                            suppress_email=suppress_email,
                            ip_addr=request.META.get('REMOTE_ADDR')
                        )

                        signals.answer_edited.send(None,
                            answer=answer,
                            user=user,
                            form_data=form.cleaned_data
                        )

                    return HttpResponseRedirect(answer.get_absolute_url())
        else:
            revision_form = forms.RevisionForm(answer, revision)
            form = edit_answer_form_class(answer, revision, user=request.user)
            if request.user.can_make_group_private_posts():
                form.initial['post_privately'] = answer.is_private()

        data = {
            'page_class': 'edit-answer-page',
            'active_tab': 'questions',
            'answer': answer,
            'revision': revision,
            'revision_form': revision_form,
            'form': form,
        }
        extra_context = context.get_extra(
            'ASKBOT_EDIT_ANSWER_PAGE_EXTRA_CONTEXT',
            request,
            data
        )
        data.update(extra_context)

        return render(request, 'answer_edit.html', data)

    except exceptions.PermissionDenied as e:
        request.user.message_set.create(message = unicode(e))
        return HttpResponseRedirect(answer.get_absolute_url())
예제 #19
0
def answer(request, id, form_class=forms.AnswerForm):  #process a new answer
    """view that posts new answer

    anonymous users post into anonymous storage
    and redirected to login page

    authenticated users post directly
    """
    question = get_object_or_404(models.Post, post_type='question', id=id)

    if askbot_settings.READ_ONLY_MODE_ENABLED:
        return HttpResponseRedirect(question.get_absolute_url())

    if request.method == 'GET':
        #session key used only to enable anonymous asking
        #as django will autodelete empty sessions
        request.session['askbot_write_intent'] = True
    elif request.method == 'POST':

        #this check prevents backward compatilibility
        if form_class == forms.AnswerForm:
            custom_class_path = getattr(settings, 'ASKBOT_NEW_ANSWER_FORM',
                                        None)
            if custom_class_path:
                form_class = load_module(custom_class_path)
            else:
                form_class = forms.AnswerForm

        form = form_class(request.POST, user=request.user)

        if form.is_valid():
            if request.user.is_authenticated():
                drafts = models.DraftAnswer.objects.filter(
                    author=request.user, thread=question.thread)
                drafts.delete()
                user = form.get_post_user(request.user)
                try:
                    text = form.cleaned_data['text']
                    if akismet_check_spam(text, request):
                        message = _(
                            'Spam was detected on your post, sorry if it was a mistake'
                        )
                        raise exceptions.PermissionDenied(message)

                    answer = form.save(question,
                                       user,
                                       ip_addr=request.META.get('REMOTE_ADDR'))

                    signals.new_answer_posted.send(None,
                                                   answer=answer,
                                                   user=user,
                                                   form_data=form.cleaned_data)

                    return HttpResponseRedirect(answer.get_absolute_url())
                except askbot_exceptions.AnswerAlreadyGiven as e:
                    request.user.message_set.create(message=unicode(e))
                    answer = question.thread.get_answers_by_user(user)[0]
                    return HttpResponseRedirect(answer.get_absolute_url())
                except exceptions.PermissionDenied as e:
                    request.user.message_set.create(message=unicode(e))
            else:
                if request.session.session_key is None:
                    return HttpResponseForbidden()

                models.AnonymousAnswer.objects.create(
                    question=question,
                    wiki=form.cleaned_data['wiki'],
                    text=form.cleaned_data['text'],
                    session_key=request.session.session_key,
                    ip_addr=request.META.get('REMOTE_ADDR'),
                )
                return HttpResponseRedirect(url_utils.get_login_url())

    #TODO: look into an issue here is that backend form validation errors
    # won't be displayed, we are fully relying on the prevalidation
    # in the js
    return HttpResponseRedirect(question.get_absolute_url())
예제 #20
0
def post_comments(request):#generic ajax handler to load comments to an object
    """todo: fixme: post_comments is ambigous:
    means either get comments for post or
    add a new comment to post
    """
    # only support get post comments by ajax now
    post_type = request.REQUEST.get('post_type', '')
    if not request.is_ajax() or post_type not in ('question', 'answer'):
        raise Http404  # TODO: Shouldn't be 404! More like 400, 403 or sth more specific

    if post_type == 'question' \
        and askbot_settings.QUESTION_COMMENTS_ENABLED == False:
        raise Http404
    elif post_type == 'answer' \
        and askbot_settings.ANSWER_COMMENTS_ENABLED == False:
        raise Http404

    user = request.user

    if request.method == 'POST':
        form = forms.NewCommentForm(request.POST)
    elif request.method == 'GET':
        form = forms.GetCommentDataForPostForm(request.GET)

    if form.is_valid() == False:
        return HttpResponseBadRequest(
            _('This content is forbidden'),
            content_type='application/json'
        )

    post_id = form.cleaned_data['post_id']
    avatar_size = form.cleaned_data['avatar_size']
    try:
        post = models.Post.objects.get(id=post_id)
    except models.Post.DoesNotExist:
        return HttpResponseBadRequest(
            _('Post not found'), content_type='application/json'
        )

    if request.method == "GET":
        response = __generate_comments_json(post, user, avatar_size)
    elif request.method == "POST":
        try:
            if user.is_anonymous():
                msg = _('Sorry, you appear to be logged out and '
                        'cannot post comments. Please '
                        '<a href="%(sign_in_url)s">sign in</a>.') % \
                        {'sign_in_url': url_utils.get_login_url()}
                raise exceptions.PermissionDenied(msg)

            if askbot_settings.READ_ONLY_MODE_ENABLED:
                raise exceptions.PermissionDenied(askbot_settings.READ_ONLY_MESSAGE)

            text = form.cleaned_data['comment']
            if akismet_check_spam(text, request):
                message = _('Spam was detected on your post, sorry if it was a mistake')
                raise exceptions.PermissionDenied(message)

            comment = user.post_comment(
                parent_post=post,
                body_text=text,
                ip_addr=request.META.get('REMOTE_ADDR')
            )
            signals.new_comment_posted.send(None,
                comment=comment,
                user=user,
                form_data=form.cleaned_data
            )
            response = __generate_comments_json(post, user, avatar_size)
        except exceptions.PermissionDenied as e:
            response = HttpResponseForbidden(unicode(e), content_type="application/json")

    return response
예제 #21
0
def post_comments(
        request):  #generic ajax handler to load comments to an object
    """todo: fixme: post_comments is ambigous:
    means either get comments for post or
    add a new comment to post
    """
    # only support get post comments by ajax now
    post_type = request.REQUEST.get('post_type', '')
    if not request.is_ajax() or post_type not in ('question', 'answer'):
        raise Http404  # TODO: Shouldn't be 404! More like 400, 403 or sth more specific

    if post_type == 'question' \
        and askbot_settings.QUESTION_COMMENTS_ENABLED == False:
        raise Http404
    elif post_type == 'answer' \
        and askbot_settings.ANSWER_COMMENTS_ENABLED == False:
        raise Http404

    user = request.user

    if request.method == 'POST':
        form = forms.NewCommentForm(request.POST)
    elif request.method == 'GET':
        form = forms.GetCommentDataForPostForm(request.GET)

    if form.is_valid() == False:
        return HttpResponseBadRequest(_('This content is forbidden'),
                                      content_type='application/json')

    post_id = form.cleaned_data['post_id']
    avatar_size = form.cleaned_data['avatar_size']
    try:
        post = models.Post.objects.get(id=post_id)
    except models.Post.DoesNotExist:
        return HttpResponseBadRequest(_('Post not found'),
                                      content_type='application/json')

    if request.method == "GET":
        response = __generate_comments_json(post, user, avatar_size)
    elif request.method == "POST":
        try:
            if user.is_anonymous():
                msg = _('Sorry, you appear to be logged out and '
                        'cannot post comments. Please '
                        '<a href="%(sign_in_url)s">sign in</a>.') % \
                        {'sign_in_url': url_utils.get_login_url()}
                raise exceptions.PermissionDenied(msg)

            if askbot_settings.READ_ONLY_MODE_ENABLED:
                raise exceptions.PermissionDenied(
                    askbot_settings.READ_ONLY_MESSAGE)

            text = form.cleaned_data['comment']
            if akismet_check_spam(text, request):
                message = _(
                    'Spam was detected on your post, sorry if it was a mistake'
                )
                raise exceptions.PermissionDenied(message)

            comment = user.post_comment(
                parent_post=post,
                body_text=text,
                ip_addr=request.META.get('REMOTE_ADDR'))
            signals.new_comment_posted.send(None,
                                            comment=comment,
                                            user=user,
                                            form_data=form.cleaned_data)
            response = __generate_comments_json(post, user, avatar_size)
        except exceptions.PermissionDenied as e:
            response = HttpResponseForbidden(unicode(e),
                                             content_type="application/json")

    return response