Пример #1
0
def new_thread(request, document_slug):
    """Start a new thread."""
    doc = get_document(document_slug, request)

    if request.method == "GET":
        form = NewThreadForm()
        return render(request, "kbforums/new_thread.html", {"form": form, "document": doc})

    form = NewThreadForm(request.POST)
    post_preview = None
    if form.is_valid():
        if "preview" in request.POST:
            thread = Thread(creator=request.user, title=form.cleaned_data["title"])
            post_preview = Post(thread=thread, creator=request.user, content=form.cleaned_data["content"])
        elif not _is_ratelimited(request):
            thread = doc.thread_set.create(creator=request.user, title=form.cleaned_data["title"])
            thread.save()
            statsd.incr("kbforums.thread")
            post = thread.new_post(creator=request.user, content=form.cleaned_data["content"])
            post.save()

            # Send notifications to forum watchers.
            NewThreadEvent(post).fire(exclude=post.creator)

            # Add notification automatically if needed.
            if Setting.get_for_user(request.user, "kbforums_watch_new_thread"):
                NewPostEvent.notify(request.user, thread)

            return HttpResponseRedirect(reverse("wiki.discuss.posts", args=[document_slug, thread.id]))

    return render(request, "kbforums/new_thread.html", {"form": form, "document": doc, "post_preview": post_preview})
Пример #2
0
def reply(request, document_slug, thread_id):
    """Reply to a thread."""
    doc = get_document(document_slug, request)

    form = ReplyForm(request.POST)
    post_preview = None
    if form.is_valid():
        thread = get_object_or_404(Thread, pk=thread_id, document=doc)

        if not thread.is_locked:
            reply_ = form.save(commit=False)
            reply_.thread = thread
            reply_.creator = request.user
            if 'preview' in request.POST:
                post_preview = reply_
            elif not _is_ratelimited(request):
                reply_.save()
                statsd.incr('kbforums.reply')

                # Subscribe the user to the thread.
                if Setting.get_for_user(request.user,
                                        'kbforums_watch_after_reply'):
                    NewPostEvent.notify(request.user, thread)

                # Send notifications to thread/forum watchers.
                NewPostEvent(reply_).fire(exclude=reply_.creator)

                return HttpResponseRedirect(reply_.get_absolute_url())

    return posts(request, document_slug, thread_id, form, post_preview)
Пример #3
0
def reply(request, document_slug, thread_id):
    """Reply to a thread."""
    doc = get_document(document_slug, request)

    form = ReplyForm(request.POST)
    post_preview = None
    if form.is_valid():
        thread = get_object_or_404(Thread, pk=thread_id, document=doc)

        if not thread.is_locked:
            reply_ = form.save(commit=False)
            reply_.thread = thread
            reply_.creator = request.user
            if 'preview' in request.POST:
                post_preview = reply_
            elif not _is_ratelimited(request):
                reply_.save()

                # Subscribe the user to the thread.
                if Setting.get_for_user(request.user,
                                        'kbforums_watch_after_reply'):
                    NewPostEvent.notify(request.user, thread)

                # Send notifications to thread/forum watchers.
                NewPostEvent(reply_).fire(exclude=reply_.creator)

                return HttpResponseRedirect(reply_.get_absolute_url())

    return posts(request, document_slug, thread_id, form, post_preview)
Пример #4
0
    def test_private_message_sends_email(self, get_current):
        """
        With the setting enabled and receiving a private message should
        send and email.
        """
        get_current.return_value.domain = 'testserver'

        s, c = Setting.objects.get_or_create(user=self.to,
                                             name='email_private_messages')
        s.value = True
        s.save()
        # User has setting, and should recieve notification email.

        assert Setting.get_for_user(self.to, 'email_private_messages')

        self.client.login(username=self.sender.username, password='******')
        post(self.client, 'messages.new', {
            'to': self.to,
            'message': 'a message'
        })
        subject = u'[SUMO] You have a new private message from [{sender}]'

        attrs_eq(mail.outbox[0],
                 to=[self.to.email],
                 subject=subject.format(sender=self.sender.username))
        starts_with(mail.outbox[0].body,
                    PRIVATE_MESSAGE_EMAIL.format(sender=self.sender.username))
Пример #5
0
    def test_private_message_sends_email(self, get_current):
        """
        With the setting enabled and receiving a private message should
        send and email.
        """
        get_current.return_value.domain = "testserver"

        s, c = Setting.objects.get_or_create(user=self.to, name="email_private_messages")
        s.value = True
        s.save()
        # User has setting, and should recieve notification email.

        assert Setting.get_for_user(self.to, "email_private_messages")

        self.client.login(username=self.sender.username, password="******")
        post(self.client, "messages.new", {"to": self.to, "message": "a message"})
        subject = "[SUMO] You have a new private message from [{sender}]"

        attrs_eq(
            mail.outbox[0],
            to=[self.to.email],
            subject=subject.format(sender=self.sender.profile.name),
        )
        starts_with(
            mail.outbox[0].body, PRIVATE_MESSAGE_EMAIL.format(sender=self.sender.profile.name)
        )
Пример #6
0
def reply(request, question_id):
    """Post a new answer to a question."""
    question = get_object_or_404(Question, pk=question_id, is_spam=False)
    answer_preview = None

    if not question.allows_new_answer(request.user):
        raise PermissionDenied

    form = AnswerForm(request.POST, **{"user": request.user, "question": question})

    # NOJS: delete images
    if "delete_images" in request.POST:
        for image_id in request.POST.getlist("delete_image"):
            ImageAttachment.objects.get(pk=image_id).delete()

        return question_details(request, question_id=question_id, form=form)

    # NOJS: upload image
    if "upload_image" in request.POST:
        upload_imageattachment(request, request.user)
        return question_details(request, question_id=question_id, form=form)

    if form.is_valid() and not request.limited:
        answer = Answer(
            question=question,
            creator=request.user,
            content=form.cleaned_data["content"],
        )
        if "preview" in request.POST:
            answer_preview = answer
        else:
            if form.cleaned_data.get("is_spam"):
                _add_to_moderation_queue(request, answer)
            else:
                answer.save()

            ans_ct = ContentType.objects.get_for_model(answer)
            # Move over to the answer all of the images I added to the
            # reply form
            user_ct = ContentType.objects.get_for_model(request.user)
            up_images = ImageAttachment.objects.filter(creator=request.user, content_type=user_ct)
            up_images.update(content_type=ans_ct, object_id=answer.id)

            # Handle needsinfo tag
            if "needsinfo" in request.POST:
                question.set_needs_info()
            elif "clear_needsinfo" in request.POST:
                question.unset_needs_info()

            if Setting.get_for_user(request.user, "questions_watch_after_reply"):
                QuestionReplyEvent.notify(request.user, question)

            return HttpResponseRedirect(answer.get_absolute_url())

    return question_details(
        request, question_id=question_id, form=form, answer_preview=answer_preview
    )
Пример #7
0
 def test_create_setting(self):
     url = reverse('users.edit_settings', locale='en-US')
     eq_(Setting.objects.filter(user=self.u).count(), 0)  # No settings
     res = self.client.get(url, follow=True)
     eq_(200, res.status_code)
     res = self.client.post(url, {'forums_watch_new_thread': True},
                            follow=True)
     eq_(200, res.status_code)
     assert Setting.get_for_user(self.u, 'forums_watch_new_thread')
Пример #8
0
 def test_create_setting(self):
     url = reverse('users.edit_settings', locale='en-US')
     eq_(Setting.objects.filter(user=self.user).count(), 0)  # No settings
     res = self.client.get(url, follow=True)
     eq_(200, res.status_code)
     res = self.client.post(url, {'forums_watch_new_thread': True},
                            follow=True)
     eq_(200, res.status_code)
     assert Setting.get_for_user(self.user, 'forums_watch_new_thread')
Пример #9
0
def new_thread(request, forum_slug):
    """Start a new thread."""
    forum = get_object_or_404(Forum, slug=forum_slug)
    user = request.user
    if not forum.allows_posting_by(user):
        if forum.allows_viewing_by(user):
            raise PermissionDenied
        else:
            raise Http404

    if request.method == 'GET':
        form = NewThreadForm()
        return render(request, 'forums/new_thread.html', {
            'form': form,
            'forum': forum
        })

    form = NewThreadForm(request.POST)
    post_preview = None
    if form.is_valid():
        if 'preview' in request.POST:
            thread = Thread(creator=request.user,
                            title=form.cleaned_data['title'])
            post_preview = Post(thread=thread,
                                author=request.user,
                                content=form.cleaned_data['content'])
            post_preview.author_post_count = \
                post_preview.author.post_set.count()
        elif (_skip_post_ratelimit(request)
              or not is_ratelimited(request,
                                    increment=True,
                                    rate='5/d',
                                    ip=False,
                                    keys=user_or_ip('forum-post'))):
            thread = forum.thread_set.create(creator=request.user,
                                             title=form.cleaned_data['title'])
            thread.save()
            statsd.incr('forums.thread')
            post = thread.new_post(author=request.user,
                                   content=form.cleaned_data['content'])
            post.save()

            NewThreadEvent(post).fire(exclude=post.author)

            # Add notification automatically if needed.
            if Setting.get_for_user(request.user, 'forums_watch_new_thread'):
                NewPostEvent.notify(request.user, thread)

            url = reverse('forums.posts', args=[forum_slug, thread.id])
            return HttpResponseRedirect(urlparams(url, last=post.id))

    return render(request, 'forums/new_thread.html', {
        'form': form,
        'forum': forum,
        'post_preview': post_preview
    })
Пример #10
0
def new_thread(request, forum_slug):
    """Start a new thread."""
    forum = get_object_or_404(Forum, slug=forum_slug)
    user = request.user
    if not forum.allows_posting_by(user):
        if forum.allows_viewing_by(user):
            raise PermissionDenied
        else:
            raise Http404

    if request.method == "GET":
        form = NewThreadForm()
        return render(request, "forums/new_thread.html", {
            "form": form,
            "forum": forum
        })

    form = NewThreadForm(request.POST)
    post_preview = None
    if form.is_valid():
        if "preview" in request.POST:
            thread = Thread(creator=request.user,
                            title=form.cleaned_data["title"])
            post_preview = Post(thread=thread,
                                author=request.user,
                                content=form.cleaned_data["content"])
            post_preview.author_post_count = post_preview.author.post_set.count(
            )
        elif not is_ratelimited(request, "forum-post", "5/d"):
            thread = forum.thread_set.create(creator=request.user,
                                             title=form.cleaned_data["title"])
            thread.save()
            post = thread.new_post(author=request.user,
                                   content=form.cleaned_data["content"])
            post.save()

            NewThreadEvent(post).fire(exclude=post.author)

            # Add notification automatically if needed.
            if Setting.get_for_user(request.user, "forums_watch_new_thread"):
                NewPostEvent.notify(request.user, thread)

            url = reverse("forums.posts", args=[forum_slug, thread.id])
            return HttpResponseRedirect(urlparams(url, last=post.id))

    return render(
        request,
        "forums/new_thread.html",
        {
            "form": form,
            "forum": forum,
            "post_preview": post_preview
        },
    )
Пример #11
0
def reply(request, forum_slug, thread_id):
    """Reply to a thread."""
    forum = get_object_or_404(Forum, slug=forum_slug)
    user = request.user
    if not forum.allows_posting_by(user):
        if forum.allows_viewing_by(user):
            raise PermissionDenied
        else:
            raise Http404

    form = ReplyForm(request.POST)
    post_preview = None
    if form.is_valid():
        thread = get_object_or_404(Thread, pk=thread_id, forum=forum)

        if not thread.is_locked:
            reply_ = form.save(commit=False)
            reply_.thread = thread
            reply_.author = request.user
            if 'preview' in request.POST:
                post_preview = reply_
                post_preview.author_post_count = \
                    reply_.author.post_set.count()
            elif (_skip_post_ratelimit(request)
                  or not is_ratelimited(request,
                                        increment=True,
                                        rate='15/d',
                                        ip=False,
                                        keys=user_or_ip('forum-post'))):
                reply_.save()
                statsd.incr('forums.reply')

                # Subscribe the user to the thread.
                if Setting.get_for_user(request.user,
                                        'forums_watch_after_reply'):
                    NewPostEvent.notify(request.user, thread)

                # Send notifications to thread/forum watchers.
                NewPostEvent(reply_).fire(exclude=reply_.author)

                return HttpResponseRedirect(thread.get_last_post_url())

    return posts(request,
                 forum_slug,
                 thread_id,
                 form,
                 post_preview,
                 is_reply=True)
Пример #12
0
def new_thread(request, forum_slug):
    """Start a new thread."""
    forum = get_object_or_404(Forum, slug=forum_slug)
    user = request.user
    if not forum.allows_posting_by(user):
        if forum.allows_viewing_by(user):
            raise PermissionDenied
        else:
            raise Http404

    if request.method == 'GET':
        form = NewThreadForm()
        return render(request, 'forums/new_thread.html', {
            'form': form, 'forum': forum})

    form = NewThreadForm(request.POST)
    post_preview = None
    if form.is_valid():
        if 'preview' in request.POST:
            thread = Thread(creator=request.user,
                            title=form.cleaned_data['title'])
            post_preview = Post(thread=thread, author=request.user,
                                content=form.cleaned_data['content'])
            post_preview.author_post_count = \
                post_preview.author.post_set.count()
        elif (_skip_post_ratelimit(request) or
              not is_ratelimited(request, increment=True, rate='5/d', ip=False,
                                 keys=user_or_ip('forum-post'))):
            thread = forum.thread_set.create(creator=request.user,
                                             title=form.cleaned_data['title'])
            thread.save()
            statsd.incr('forums.thread')
            post = thread.new_post(author=request.user,
                                   content=form.cleaned_data['content'])
            post.save()

            NewThreadEvent(post).fire(exclude=post.author)

            # Add notification automatically if needed.
            if Setting.get_for_user(request.user, 'forums_watch_new_thread'):
                NewPostEvent.notify(request.user, thread)

            url = reverse('forums.posts', args=[forum_slug, thread.id])
            return HttpResponseRedirect(urlparams(url, last=post.id))

    return render(request, 'forums/new_thread.html', {
        'form': form, 'forum': forum,
        'post_preview': post_preview})
Пример #13
0
def send_message(to, text, sender=None):
    """Send a private message.

    :arg to: a list of Users to send the message to
    :arg sender: the User who is sending the message
    :arg text: the message text
    """
    if sender:
        msg = OutboxMessage.objects.create(sender=sender, message=text)
        msg.to.add(*to)
    for user in to:
        im = InboxMessage.objects.create(sender=sender, to=user, message=text)
        if Setting.get_for_user(user, 'email_private_messages'):
            email_private_message(inbox_message_id=im.id)

    message_sent.send(sender=InboxMessage, to=to, text=text, msg_sender=sender)
Пример #14
0
def new_thread(request, document_slug):
    """Start a new thread."""
    doc = get_document(document_slug, request)

    if request.method == "GET":
        form = NewThreadForm()
        return render(request, "kbforums/new_thread.html", {
            "form": form,
            "document": doc
        })

    form = NewThreadForm(request.POST)
    post_preview = None
    if form.is_valid():
        if "preview" in request.POST:
            thread = Thread(creator=request.user,
                            title=form.cleaned_data["title"])
            post_preview = Post(thread=thread,
                                creator=request.user,
                                content=form.cleaned_data["content"])
        elif not _is_ratelimited(request):
            thread = doc.thread_set.create(creator=request.user,
                                           title=form.cleaned_data["title"])
            thread.save()
            post = thread.new_post(creator=request.user,
                                   content=form.cleaned_data["content"])
            post.save()

            # Send notifications to forum watchers.
            NewThreadEvent(post).fire(exclude=post.creator)

            # Add notification automatically if needed.
            if Setting.get_for_user(request.user, "kbforums_watch_new_thread"):
                NewPostEvent.notify(request.user, thread)

            return HttpResponseRedirect(
                reverse("wiki.discuss.posts", args=[document_slug, thread.id]))

    return render(
        request,
        "kbforums/new_thread.html",
        {
            "form": form,
            "document": doc,
            "post_preview": post_preview
        },
    )
Пример #15
0
def send_message(to, text, sender=None):
    """Send a private message.

    :arg to: a list of Users to send the message to
    :arg sender: the User who is sending the message
    :arg text: the message text
    """
    if sender:
        msg = OutboxMessage.objects.create(sender=sender, message=text)
        msg.to.add(*to)
    for user in to:
        im = InboxMessage.objects.create(sender=sender, to=user, message=text)
        if Setting.get_for_user(user, 'email_private_messages'):
            email_private_message(inbox_message_id=im.id)

    message_sent.send(sender=InboxMessage, to=to, text=text,
                      msg_sender=sender)
Пример #16
0
    def test_private_message_not_sends_email(self, get_current):
        """
        With the setting not enabled and receiving a private message.
        The user should not get an email.
        """
        get_current.return_value.domain = "testserver"

        s, c = Setting.objects.get_or_create(user=self.to, name="email_private_messages")
        # Now user should not recieve email.
        s.value = False
        s.save()
        assert not Setting.get_for_user(self.to, "email_private_messages")

        self.client.login(username=self.sender.username, password="******")
        post(self.client, "messages.new", {"to": self.to, "message": "a message"})

        assert not mail.outbox
Пример #17
0
def new_thread(request, document_slug):
    """Start a new thread."""
    doc = get_document(document_slug, request)

    if request.method == 'GET':
        form = NewThreadForm()
        return render(request, 'kbforums/new_thread.html', {
            'form': form,
            'document': doc
        })

    form = NewThreadForm(request.POST)
    post_preview = None
    if form.is_valid():
        if 'preview' in request.POST:
            thread = Thread(creator=request.user,
                            title=form.cleaned_data['title'])
            post_preview = Post(thread=thread,
                                creator=request.user,
                                content=form.cleaned_data['content'])
        elif not _is_ratelimited(request):
            thread = doc.thread_set.create(creator=request.user,
                                           title=form.cleaned_data['title'])
            thread.save()
            statsd.incr('kbforums.thread')
            post = thread.new_post(creator=request.user,
                                   content=form.cleaned_data['content'])
            post.save()

            # Send notifications to forum watchers.
            NewThreadEvent(post).fire(exclude=post.creator)

            # Add notification automatically if needed.
            if Setting.get_for_user(request.user, 'kbforums_watch_new_thread'):
                NewPostEvent.notify(request.user, thread)

            return HttpResponseRedirect(
                reverse('wiki.discuss.posts', args=[document_slug, thread.id]))

    return render(request, 'kbforums/new_thread.html', {
        'form': form,
        'document': doc,
        'post_preview': post_preview
    })
Пример #18
0
    def test_private_message_not_sends_email(self, get_current):
        """
        With the setting not enabled and receiving a private message.
        The user should not get an email.
        """
        get_current.return_value.domain = 'testserver'

        s, c = Setting.objects.get_or_create(user=self.to,
                                             name='email_private_messages')
        # Now user should not recieve email.
        s.value = False
        s.save()
        assert not Setting.get_for_user(self.to, 'email_private_messages')

        self.client.login(username=self.sender.username, password='******')
        post(self.client, 'messages.new',
             {'to': self.to, 'message': 'a message'})

        assert not mail.outbox
Пример #19
0
def reply(request, forum_slug, thread_id):
    """Reply to a thread."""
    forum = get_object_or_404(Forum, slug=forum_slug)
    user = request.user
    if not forum.allows_posting_by(user):
        if forum.allows_viewing_by(user):
            raise PermissionDenied
        else:
            raise Http404

    form = ReplyForm(request.POST)
    post_preview = None
    if form.is_valid():
        thread = get_object_or_404(Thread, pk=thread_id, forum=forum)

        if not thread.is_locked:
            reply_ = form.save(commit=False)
            reply_.thread = thread
            reply_.author = request.user
            if 'preview' in request.POST:
                post_preview = reply_
                post_preview.author_post_count = \
                    reply_.author.post_set.count()
            elif (_skip_post_ratelimit(request) or
                  not is_ratelimited(request, increment=True, rate='5/d',
                                     ip=False,
                                     keys=user_or_ip('forum-post'))):
                reply_.save()
                statsd.incr('forums.reply')

                # Subscribe the user to the thread.
                if Setting.get_for_user(request.user,
                                        'forums_watch_after_reply'):
                    NewPostEvent.notify(request.user, thread)

                # Send notifications to thread/forum watchers.
                NewPostEvent(reply_).fire(exclude=reply_.author)

                return HttpResponseRedirect(thread.get_last_post_url())

    return posts(request, forum_slug, thread_id, form, post_preview,
                 is_reply=True)
Пример #20
0
    def test_private_message_not_sends_email(self, get_current):
        """
        With the setting not enabled and receiving a private message.
        The user should not get an email.
        """
        get_current.return_value.domain = 'testserver'

        s, c = Setting.objects.get_or_create(user=self.to,
                                             name='email_private_messages')
        # Now user should not recieve email.
        s.value = False
        s.save()
        assert not Setting.get_for_user(self.to, 'email_private_messages')

        self.client.login(username=self.sender.username, password='******')
        post(self.client, 'messages.new', {
            'to': self.to,
            'message': 'a message'
        })

        assert not mail.outbox
Пример #21
0
    def test_private_message_sends_email(self, get_current):
        """
        With the setting enabled and receiving a private message should
        send and email.
        """
        get_current.return_value.domain = 'testserver'

        s, c = Setting.objects.get_or_create(user=self.to, name='email_private_messages')
        s.value = True
        s.save()
        # User has setting, and should recieve notification email.

        assert Setting.get_for_user(self.to, 'email_private_messages')

        self.client.login(username=self.sender.username, password='******')
        post(self.client, 'messages.new',
             {'to': self.to, 'message': 'a message'})
        subject = u'[SUMO] You have a new private message from [{sender}]'

        attrs_eq(mail.outbox[0], to=[self.to.email],
                 subject=subject.format(sender=self.sender.profile.name))
        starts_with(mail.outbox[0].body,
                    PRIVATE_MESSAGE_EMAIL.format(sender=self.sender.profile.name))
Пример #22
0
 def test_default_values(self):
     eq_(0, Setting.objects.count())
     keys = SettingsForm.base_fields.keys()
     for setting in keys:
         field = SettingsForm.base_fields[setting]
         eq_(field.initial, Setting.get_for_user(self.u, setting))
Пример #23
0
 def test_non_existant_setting(self):
     form = SettingsForm()
     bad_setting = 'doesnt_exist'
     assert bad_setting not in form.fields.keys()
     with self.assertRaises(KeyError):
         Setting.get_for_user(self.u, bad_setting)
Пример #24
0
 def test_non_existant_setting(self):
     form = SettingsForm()
     bad_setting = 'doesnt_exist'
     assert bad_setting not in form.fields.keys()
     with self.assertRaises(KeyError):
         Setting.get_for_user(self.u, bad_setting)
Пример #25
0
 def test_default_values(self):
     eq_(0, Setting.objects.count())
     keys = SettingsForm.base_fields.keys()
     for setting in keys:
         field = SettingsForm.base_fields[setting]
         eq_(field.initial, Setting.get_for_user(self.u, setting))
Пример #26
0
 def test_default_values(self):
     eq_(0, Setting.objects.count())
     keys = list(SettingsForm.base_fields.keys())
     for setting in keys:
         SettingsForm.base_fields[setting]
         eq_(False, Setting.get_for_user(self.u, setting))