Esempio n. 1
0
def post(request, group = None, category_id = None, post_id = None, thread_id = None):
    if 'type' in request.REQUEST and request.REQUEST['type'] == 'preview':
        previewpost = Post( body = request.REQUEST['body'],
                            markup = request.REQUEST.get('markup', None), )
        return HttpResponse( unicode(previewpost.body_escaped()) )

    
    post = None
    thread = None
    category = None
    context = { }
    
    if post_id is None and 'post_id' in request.REQUEST:
        # if no post_id is given take it from the request.
        post_id = request.REQUEST['post_id']

    if post_id:
        try:
            post = Post.allobjects.get( pk = post_id )
        except Post.DoesNotExist:
            raise Http404

        if not post.allowEditing():
            raise PermissionDenied()
        thread = post.thread
    
    if 'thread' in request.REQUEST:
        thread_id = request.REQUEST['thread']

    if thread_id:
        try:
            thread = Post.allobjects.get( pk = thread_id )
        except Post.DoesNotExist:
            raise Http404

        category = thread.category
        context['thread'] = thread
        
        if not thread.allowPosting( request.user ):
            raise PermissionDenied()
    else:
        category = get_object_or_404(Category, pk = category_id)
        if not category.allowPostThread( request.user ):
            raise PermissionDenied()

    context['category'] = category

    category_type = category.get_category_type()
    MyPostForm = PostForm
    if category_type is not None:
        MyPostForm = category_type.get_post_form_class(thread, post)

    attachmentForm = None
    allow_attachments = get_sph_setting('board_allow_attachments')
    if request.method == 'POST':
        postForm = MyPostForm(request.POST)
        postForm.init_for_category_type(category_type, post)
        pollForm = PostPollForm(request.POST)

        create_post = True

        if allow_attachments:
            attachmentForm = PostAttachmentForm(request.POST,
                                                request.FILES,
                                                prefix = 'attachment')

            if 'cmd_addfile' in request.POST:
                create_post = False

            if attachmentForm.is_valid():
                attachment = attachmentForm.save(commit = False)
                if attachment.fileupload:
                    # Only save attachments if there was an upload...
                    # If the form is valid, store the attachment
                    if not post:
                        # if there is no post yet.. we need to create a draft
                        post = Post( category = category,
                                     author = request.user,
                                     thread = thread,
                                     is_hidden = 1,
                                     )
                        post.set_new( True )
                        post.save()

                    # Reference the post and save the attachment
                    attachment.post = post
                    attachment.save()


        if create_post \
                and postForm.is_valid() \
                and ('createpoll' not in request.POST \
                         or pollForm.is_valid()):
            data = postForm.cleaned_data

            if post:
                newpost = post
                newpost.subject = data['subject']
                newpost.body = data['body']
                # make post visible
                newpost.is_hidden = 0
                if not post.is_new() and category_type.append_edit_message_to_post(post):
                    newpost.body += "\n\n" + _(u'--- Last Edited by %(username)s at %(edit_date)s ---') % {'username':get_user_displayname( request.user ), 'edit_date':format_date( datetime.today())}
            else:
                user = request.user.is_authenticated() and request.user or None
                newpost = Post( category = category,
                                subject = data['subject'],
                                body = data['body'],
                                author = user,
                                thread = thread,
                                )
            if 'markup' in data:
                newpost.markup = data['markup']
                
            elif len( POST_MARKUP_CHOICES ) == 1:
                newpost.markup = POST_MARKUP_CHOICES[0][0]
                
            newpost.save()

            category_type.save_post( newpost, data )


            # Creating monitor
            if request.POST.get( 'addmonitor', False ):
                newpost.toggle_monitor()


            if 'createpoll' in request.POST and request.POST['createpoll'] == '1':
                newpost.set_poll( True );
                newpost.save()

                # Creating poll...
                polldata = pollForm.cleaned_data
                newpoll = Poll( post = newpost,
                                question = polldata['question'],
                                choices_per_user = polldata['choicesPerUser'])
                newpoll.save()

                choices = polldata['answers'].splitlines()
                i=0
                for choice in choices:
                    pollchoice = PollChoice( poll = newpoll,
                                             choice = choice,
                                             count = 0,
                                             sortorder = i)
                    i+=1
                    pollchoice.save()
                if request.user.is_authenticated():
                    request.user.message_set.create( message = ugettext(u'Vote created successfully.') )

            if request.user.is_authenticated():
                if post:
                    request.user.message_set.create( message = ugettext(u'Post edited successfully.') )
                else:
                    request.user.message_set.create( message = ugettext(u'Post created successfully.') )
            if thread == None: thread = newpost
            return HttpResponseRedirect( newpost.get_absolute_url() )

    else:
        postForm = MyPostForm( )
        postForm.init_for_category_type(category_type, post)
        pollForm = PostPollForm()

        if allow_attachments:
            attachmentForm = PostAttachmentForm(prefix = 'attachment')

    if post:
        postForm.fields['subject'].initial = post.subject
        postForm.fields['body'].initial = post.body
        if 'markup' in postForm.fields:
            postForm.fields['markup'].initial = post.markup
        context['post'] = post
        context['thread'] = post.thread or post
    elif 'quote' in request.REQUEST:
        quotepost = Post.objects.get( pk = request.REQUEST['quote'] )
        postForm.fields['subject'].initial = 'Re: %s' % thread.subject
        if quotepost.author == None:
            username = '******'
        else:
            username = quotepost.author.username
        postForm.fields['body'].initial = '[quote=%s;%s]\n%s\n[/quote]\n' % (username, quotepost.id, quotepost.body)
    elif thread:
        postForm.fields['subject'].initial = 'Re: %s' % thread.subject
    context['form'] = postForm

    # Only allow polls if this is a new _thread_ (not a reply)
    if (not thread and not post) or (post and post.is_new() and post.thread is None):
        context['pollform'] = pollForm
    context['attachmentForm'] = attachmentForm
    if 'createpoll' in request.REQUEST:
        context['createpoll'] = request.REQUEST['createpoll']

    res = render_to_response( "sphene/sphboard/post.html", context,
                              context_instance = RequestContext(request) )
    # Maybe the user is in the 'edit' form, which should not be cached.
    res.sph_lastmodified = True
    return res
Esempio n. 2
0
def sph_user_displayname(user):
    """ Returns the display name of the given user
    (No HTML, just text) """
    return get_user_displayname(user)
def post(request, group=None, category_id=None, post_id=None, thread_id=None):
    """
    View method to allow users to:
    - create new threads (post_id and thread_id is None)
    - reply to threads (post_id is None)
    - edit posts (post_id is the post which should be edited, thread_id is None)

    post_id and thread_id can either be passed in by URL (named parameters 
    to this method) or by request.REQUEST parameters.
    """
    if "type" in request.REQUEST and request.REQUEST["type"] == "preview":
        # If user just wants a preview, simply create a dummy post so it can be rendered.
        previewpost = Post(body=request.REQUEST["body"], markup=request.REQUEST.get("markup", None))
        return HttpResponse(unicode(previewpost.body_escaped()))

    # All available objects should be loaded from the _id variables.
    post = None
    thread = None
    category = None
    context = {
        "bbcodewysiwyg": enable_wysiwyg_editor()
        or (get_sph_setting("board_wysiwyg_testing") and request.REQUEST.get("wysiwyg", False))
    }

    if post_id is None and "post_id" in request.REQUEST:
        # if no post_id is given take it from the request.
        post_id = request.REQUEST["post_id"]

    if post_id is not None:
        # User wants to edit a post ..
        try:
            post = Post.allobjects.get(pk=post_id)
        except Post.DoesNotExist:
            raise Http404

        if not post.allowEditing():
            raise PermissionDenied()
        thread = post.thread
        category = post.category

    else:
        # User wants to create a new post (thread or reply)
        if "thread" in request.REQUEST:
            thread_id = request.REQUEST["thread"]

        if thread_id is not None:
            # User is posting (replying) to a thread.
            try:
                thread = Post.allobjects.get(pk=thread_id)
            except Post.DoesNotExist:
                raise Http404

            category = thread.category

            if not thread.allowPosting(request.user):
                raise PermissionDenied()
        else:
            # User is creating a new thread.
            category = get_object_or_404(Category, pk=category_id)
            if not category.allowPostThread(request.user):
                raise PermissionDenied()

    context["thread"] = thread
    context["category"] = category

    category_type = category.get_category_type()
    MyPostForm = PostForm
    if category_type is not None:
        MyPostForm = category_type.get_post_form_class(thread, post)

    attachmentForm = None
    allow_attachments = get_sph_setting("board_allow_attachments")
    if request.method == "POST":
        postForm = MyPostForm(request.POST)
        postForm.init_for_category_type(category_type, post)
        pollForm = PostPollForm(request.POST)

        create_post = True

        if allow_attachments:
            attachmentForm = PostAttachmentForm(request.POST, request.FILES, prefix="attachment")

            if "cmd_addfile" in request.POST:
                create_post = False

            if attachmentForm.is_valid():
                attachment = attachmentForm.save(commit=False)
                if attachment.fileupload:
                    # Only save attachments if there was an upload...
                    # If the form is valid, store the attachment
                    if not post:
                        # if there is no post yet.. we need to create a draft
                        post = Post(category=category, author=request.user, thread=thread, is_hidden=1)
                        post.set_new(True)
                        post.save()

                    # Reference the post and save the attachment
                    attachment.post = post
                    attachment.save()

        if create_post and postForm.is_valid() and ("createpoll" not in request.POST or pollForm.is_valid()):
            data = postForm.cleaned_data

            if post:
                newpost = post
                newpost.subject = data["subject"]
                newpost.body = data["body"]
                # make post visible
                newpost.is_hidden = 0
                if not post.is_new() and category_type.append_edit_message_to_post(post):
                    newpost.body += "\n\n" + _(u"--- Last Edited by %(username)s at %(edit_date)s ---") % {
                        "username": get_user_displayname(request.user),
                        "edit_date": format_date(datetime.today()),
                    }
            else:
                user = request.user.is_authenticated() and request.user or None
                newpost = Post(
                    category=category, subject=data["subject"], body=data["body"], author=user, thread=thread
                )
            if "markup" in data:
                newpost.markup = data["markup"]

            elif len(POST_MARKUP_CHOICES) == 1:
                newpost.markup = POST_MARKUP_CHOICES[0][0]

            newpost.save(additional_data=data)

            # category_type.save_post( newpost, data )

            # Creating monitor
            if request.POST.get("addmonitor", False):
                newpost.toggle_monitor()

            if "createpoll" in request.POST and request.POST["createpoll"] == "1":
                newpost.set_poll(True)
                newpost.save()

                # Creating poll...
                polldata = pollForm.cleaned_data
                newpoll = Poll(post=newpost, question=polldata["question"], choices_per_user=polldata["choicesPerUser"])
                newpoll.save()

                choices = polldata["answers"].splitlines()
                i = 0
                for choice in choices:
                    pollchoice = PollChoice(poll=newpoll, choice=choice, count=0, sortorder=i)
                    i += 1
                    pollchoice.save()
                if request.user.is_authenticated():
                    request.user.message_set.create(message=ugettext(u"Vote created successfully."))

            if request.user.is_authenticated():
                if post:
                    request.user.message_set.create(message=ugettext(u"Post edited successfully."))
                else:
                    request.user.message_set.create(message=ugettext(u"Post created successfully."))
            if thread == None:
                thread = newpost
            return HttpResponseRedirect(newpost.get_absolute_url())

    else:
        postForm = MyPostForm()
        postForm.init_for_category_type(category_type, post)
        pollForm = PostPollForm()

        if allow_attachments:
            attachmentForm = PostAttachmentForm(prefix="attachment")

    if post:
        postForm.fields["subject"].initial = post.subject
        postForm.fields["body"].initial = post.body
        if "markup" in postForm.fields:
            postForm.fields["markup"].initial = post.markup
        context["post"] = post
        context["thread"] = post.thread or post
    elif "quote" in request.REQUEST:
        quotepost = Post.objects.get(pk=request.REQUEST["quote"])
        postForm.fields["subject"].initial = "Re: %s" % thread.subject
        if quotepost.author == None:
            username = "******"
        else:
            username = quotepost.author.username
        postForm.fields["body"].initial = "[quote=%s;%s]\n%s\n[/quote]\n" % (username, quotepost.id, quotepost.body)
    elif thread:
        postForm.fields["subject"].initial = "Re: %s" % thread.subject
    context["form"] = postForm

    # Only allow polls if this is a new _thread_ (not a reply)
    if (not thread and not post) or (post and post.is_new() and post.thread is None):
        context["pollform"] = pollForm
    context["attachmentForm"] = attachmentForm
    if "createpoll" in request.REQUEST:
        context["createpoll"] = request.REQUEST["createpoll"]

    res = render_to_response("sphene/sphboard/post.html", context, context_instance=RequestContext(request))
    # Maybe the user is in the 'edit' form, which should not be cached.
    res.sph_lastmodified = True
    return res
Esempio n. 4
0
def post(request, group=None, category_id=None, post_id=None, thread_id=None):
    """
    View method to allow users to:
    - create new threads (post_id and thread_id is None)
    - reply to threads (post_id is None)
    - edit posts (post_id is the post which should be edited, thread_id is None)

    post_id and thread_id can either be passed in by URL (named parameters
    to this method) or by request.REQUEST parameters.
    """
    if 'type' in request.REQUEST and request.REQUEST['type'] == 'preview':
        # If user just wants a preview, simply create a dummy post so it can be rendered.
        previewpost = Post(
            body=request.REQUEST['body'],
            markup=request.REQUEST.get('markup', None),
        )
        return HttpResponse(unicode(previewpost.body_escaped()))

    # All available objects should be loaded from the _id variables.
    post_obj = None
    thread = None
    category = None
    context = {
        'bbcodewysiwyg': enable_wysiwyg_editor() \
            or (get_sph_setting('board_wysiwyg_testing') \
                    and request.REQUEST.get('wysiwyg', False)) }

    if post_id is None and 'post_id' in request.REQUEST:
        # if no post_id is given take it from the request.
        post_id = request.REQUEST['post_id']

    if post_id is not None:
        # User wants to edit a post ..
        try:
            post_obj = Post.allobjects.get(pk=post_id)
        except Post.DoesNotExist:
            raise Http404

        if not post_obj.allowEditing():
            raise PermissionDenied()
        thread = post_obj.thread
        category = post_obj.category

    else:
        # User wants to create a new post (thread or reply)
        if 'thread' in request.REQUEST:
            thread_id = request.REQUEST['thread']

        if thread_id is not None:
            # User is posting (replying) to a thread.
            try:
                thread = Post.allobjects.get(pk=thread_id)
            except Post.DoesNotExist:
                raise Http404

            category = thread.category

            if not thread.allowPosting(request.user):
                raise PermissionDenied()
        else:
            # User is creating a new thread.
            category = get_object_or_404(Category, pk=category_id)
            if not category.allowPostThread(request.user):
                raise PermissionDenied()

    context['thread'] = thread
    context['category'] = category

    category_type = category.get_category_type()
    MyPostForm = PostForm
    if category_type is not None:
        MyPostForm = category_type.get_post_form_class(thread, post_obj)

    allow_attachments = get_sph_setting('board_allow_attachments')
    allowedattachments = 0
    if allow_attachments:
        allowedattachments = 1
        # bool is a subclass of int (hehe)
        if isinstance(allow_attachments,
                      int) and type(allow_attachments) != bool:
            allowedattachments = allow_attachments

    PostAttachmentFormSet = modelformset_factory(PostAttachment,
                                                 form=PostAttachmentForm,
                                                 fields=('fileupload', ),
                                                 can_delete=True,
                                                 max_num=allowedattachments)

    post_attachment_qs = PostAttachment.objects.none()
    if post_obj:
        post_attachment_qs = post_obj.attachments.all()

    if request.method == 'POST':
        postForm = MyPostForm(request.POST)
        postForm.init_for_category_type(category_type, post_obj)
        pollForm = PostPollForm(request.POST)

        create_post = True
        if allowedattachments and 'cmd_addfile' in request.POST:
            create_post = False

        post_attachment_formset = PostAttachmentFormSet(
            request.POST,
            request.FILES,
            queryset=post_attachment_qs,
            prefix='attachment')

        if post_attachment_formset.is_valid():
            instances = post_attachment_formset.save(commit=False)
            for attachment in instances:
                if not post_obj:
                    # if there is no post yet.. we need to create a draft
                    post_obj = Post(
                        category=category,
                        author=request.user,
                        thread=thread,
                        is_hidden=1,
                    )
                    post_obj.set_new(True)
                    post_obj.save()

                # Reference the post and save the attachment
                attachment.post = post_obj
                attachment.save()

        if create_post \
                and postForm.is_valid() \
                and ('createpoll' not in request.POST \
                         or pollForm.is_valid()):
            data = postForm.cleaned_data

            if post_obj:
                newpost = post_obj
                newpost.subject = data['subject']
                newpost.body = data['body']
                # make post visible
                newpost.is_hidden = 0
                if not post_obj.is_new(
                ) and category_type.append_edit_message_to_post(post_obj):
                    newpost.body += "\n\n" + _(
                        u'--- Last Edited by %(username)s at %(edit_date)s ---'
                    ) % {
                        'username': get_user_displayname(request.user),
                        'edit_date': format_date(timezone.now())
                    }
            else:
                user = request.user.is_authenticated() and request.user or None
                newpost = Post(
                    category=category,
                    subject=data['subject'],
                    body=data['body'],
                    author=user,
                    thread=thread,
                )
            if 'markup' in data:
                newpost.markup = data['markup']

            elif len(POST_MARKUP_CHOICES) == 1:
                newpost.markup = POST_MARKUP_CHOICES[0][0]

            newpost.save(additional_data=data)

            #category_type.save_post( newpost, data )

            # Creating monitor
            if request.POST.get('addmonitor', False):
                newpost.toggle_monitor()

            if 'createpoll' in request.POST and request.POST[
                    'createpoll'] == '1':
                newpost.set_poll(True)
                newpost.save()

                # Creating poll...
                polldata = pollForm.cleaned_data
                newpoll = Poll(post=newpost,
                               question=polldata['question'],
                               choices_per_user=polldata['choicesPerUser'])
                newpoll.save()

                choices = polldata['answers'].splitlines()
                i = 0
                for choice in choices:
                    pollchoice = PollChoice(poll=newpoll,
                                            choice=choice,
                                            count=0,
                                            sortorder=i)
                    i += 1
                    pollchoice.save()
                if request.user.is_authenticated():
                    messages.success(
                        request,
                        message=ugettext(u'Vote created successfully.'))

            if request.user.is_authenticated():
                if post_obj:
                    messages.success(
                        request,
                        message=ugettext(u'Post edited successfully.'))
                else:
                    messages.success(
                        request,
                        message=ugettext(u'Post created successfully.'))
            if thread == None: thread = newpost
            return HttpResponseRedirect(newpost.get_absolute_url())

    else:
        postForm = MyPostForm()
        postForm.init_for_category_type(category_type, post_obj)
        pollForm = PostPollForm()

        post_attachment_formset = PostAttachmentFormSet(
            queryset=post_attachment_qs, prefix='attachment')

    if post_obj:
        postForm.fields['subject'].initial = post_obj.subject
        postForm.fields['body'].initial = post_obj.body
        if 'markup' in postForm.fields:
            postForm.fields['markup'].initial = post_obj.markup
        context['post'] = post_obj
        context['thread'] = post_obj.thread or post_obj
    elif 'quote' in request.REQUEST:
        quotepost = get_object_or_404(Post, pk=request.REQUEST['quote'])
        postForm.fields['subject'].initial = 'Re: %s' % thread.subject
        if quotepost.author == None:
            username = '******'
        else:
            username = quotepost.author.username
        postForm.fields['body'].initial = '[quote=%s;%s]\n%s\n[/quote]\n' % (
            username, quotepost.id, quotepost.body)
    elif thread:
        postForm.fields['subject'].initial = 'Re: %s' % thread.subject
    context['form'] = postForm

    # Only allow polls if this is a new _thread_ (not a reply)
    if (not thread and not post_obj) or (post_obj and post_obj.is_new()
                                         and post_obj.thread is None):
        context['pollform'] = pollForm
    context['post_attachment_formset'] = post_attachment_formset
    if 'createpoll' in request.REQUEST:
        context['createpoll'] = request.REQUEST['createpoll']

    res = render_to_response("sphene/sphboard/post.html",
                             context,
                             context_instance=RequestContext(request))
    # Maybe the user is in the 'edit' form, which should not be cached.
    res.sph_lastmodified = True
    return res
Esempio n. 5
0
def sph_user_displayname(user):
    """ Returns the display name of the given user
    (No HTML, just text) """
    return get_user_displayname(user)
Esempio n. 6
0
def post(request, group=None, category_id=None, post_id=None, thread_id=None):
    if 'type' in request.REQUEST and request.REQUEST['type'] == 'preview':
        previewpost = Post(
            body=request.REQUEST['body'],
            markup=request.REQUEST.get('markup', None),
        )
        return HttpResponse(unicode(previewpost.body_escaped()))

    post = None
    thread = None
    category = None
    context = {}

    if post_id is None and 'post_id' in request.REQUEST:
        # if no post_id is given take it from the request.
        post_id = request.REQUEST['post_id']

    if post_id:
        try:
            post = Post.allobjects.get(pk=post_id)
        except Post.DoesNotExist:
            raise Http404

        if not post.allowEditing():
            raise PermissionDenied()
        thread = post.thread

    if 'thread' in request.REQUEST:
        thread_id = request.REQUEST['thread']

    if thread_id:
        try:
            thread = Post.allobjects.get(pk=thread_id)
        except Post.DoesNotExist:
            raise Http404

        category = thread.category
        context['thread'] = thread

        if not thread.allowPosting(request.user):
            raise PermissionDenied()
    else:
        category = get_object_or_404(Category, pk=category_id)
        if not category.allowPostThread(request.user):
            raise PermissionDenied()

    context['category'] = category

    category_type = category.get_category_type()
    MyPostForm = PostForm
    if category_type is not None:
        MyPostForm = category_type.get_post_form_class(thread, post)

    attachmentForm = None
    allow_attachments = get_sph_setting('board_allow_attachments')
    if request.method == 'POST':
        postForm = MyPostForm(request.POST)
        postForm.init_for_category_type(category_type, post)
        pollForm = PostPollForm(request.POST)

        create_post = True

        if allow_attachments:
            attachmentForm = PostAttachmentForm(request.POST,
                                                request.FILES,
                                                prefix='attachment')

            if 'cmd_addfile' in request.POST:
                create_post = False

            if attachmentForm.is_valid():
                attachment = attachmentForm.save(commit=False)
                if attachment.fileupload:
                    # Only save attachments if there was an upload...
                    # If the form is valid, store the attachment
                    if not post:
                        # if there is no post yet.. we need to create a draft
                        post = Post(
                            category=category,
                            author=request.user,
                            thread=thread,
                            is_hidden=1,
                        )
                        post.set_new(True)
                        post.save()

                    # Reference the post and save the attachment
                    attachment.post = post
                    attachment.save()


        if create_post \
                and postForm.is_valid() \
                and ('createpoll' not in request.POST \
                         or pollForm.is_valid()):
            data = postForm.cleaned_data

            if post:
                newpost = post
                newpost.subject = data['subject']
                newpost.body = data['body']
                # make post visible
                newpost.is_hidden = 0
                if not post.is_new(
                ) and category_type.append_edit_message_to_post(post):
                    newpost.body += "\n\n" + _(
                        u'--- Last Edited by %(username)s at %(edit_date)s ---'
                    ) % {
                        'username': get_user_displayname(request.user),
                        'edit_date': format_date(datetime.today())
                    }
            else:
                user = request.user.is_authenticated() and request.user or None
                newpost = Post(
                    category=category,
                    subject=data['subject'],
                    body=data['body'],
                    author=user,
                    thread=thread,
                )
            if 'markup' in data:
                newpost.markup = data['markup']

            elif len(POST_MARKUP_CHOICES) == 1:
                newpost.markup = POST_MARKUP_CHOICES[0][0]

            newpost.save()

            category_type.save_post(newpost, data)

            # Creating monitor
            if request.POST.get('addmonitor', False):
                newpost.toggle_monitor()

            if 'createpoll' in request.POST and request.POST[
                    'createpoll'] == '1':
                newpost.set_poll(True)
                newpost.save()

                # Creating poll...
                polldata = pollForm.cleaned_data
                newpoll = Poll(post=newpost,
                               question=polldata['question'],
                               choices_per_user=polldata['choicesPerUser'])
                newpoll.save()

                choices = polldata['answers'].splitlines()
                i = 0
                for choice in choices:
                    pollchoice = PollChoice(poll=newpoll,
                                            choice=choice,
                                            count=0,
                                            sortorder=i)
                    i += 1
                    pollchoice.save()
                if request.user.is_authenticated():
                    request.user.message_set.create(
                        message=ugettext(u'Vote created successfully.'))

            if request.user.is_authenticated():
                if post:
                    request.user.message_set.create(
                        message=ugettext(u'Post edited successfully.'))
                else:
                    request.user.message_set.create(
                        message=ugettext(u'Post created successfully.'))
            if thread == None: thread = newpost
            return HttpResponseRedirect(newpost.get_absolute_url())

    else:
        postForm = MyPostForm()
        postForm.init_for_category_type(category_type, post)
        pollForm = PostPollForm()

        if allow_attachments:
            attachmentForm = PostAttachmentForm(prefix='attachment')

    if post:
        postForm.fields['subject'].initial = post.subject
        postForm.fields['body'].initial = post.body
        if 'markup' in postForm.fields:
            postForm.fields['markup'].initial = post.markup
        context['post'] = post
        context['thread'] = post.thread or post
    elif 'quote' in request.REQUEST:
        quotepost = Post.objects.get(pk=request.REQUEST['quote'])
        postForm.fields['subject'].initial = 'Re: %s' % thread.subject
        if quotepost.author == None:
            username = '******'
        else:
            username = quotepost.author.username
        postForm.fields['body'].initial = '[quote=%s;%s]\n%s\n[/quote]\n' % (
            username, quotepost.id, quotepost.body)
    elif thread:
        postForm.fields['subject'].initial = 'Re: %s' % thread.subject
    context['form'] = postForm

    # Only allow polls if this is a new _thread_ (not a reply)
    if (not thread and not post) or (post and post.is_new()
                                     and post.thread is None):
        context['pollform'] = pollForm
    context['attachmentForm'] = attachmentForm
    if 'createpoll' in request.REQUEST:
        context['createpoll'] = request.REQUEST['createpoll']

    res = render_to_response("sphene/sphboard/post.html",
                             context,
                             context_instance=RequestContext(request))
    # Maybe the user is in the 'edit' form, which should not be cached.
    res.sph_lastmodified = True
    return res
Esempio n. 7
0
def post(request, group = None, category_id = None, post_id = None, thread_id = None):
    """
    View method to allow users to:
    - create new threads (post_id and thread_id is None)
    - reply to threads (post_id is None)
    - edit posts (post_id is the post which should be edited, thread_id is None)

    post_id and thread_id can either be passed in by URL (named parameters
    to this method) or by request.REQUEST parameters.
    """
    if 'type' in request.REQUEST and request.REQUEST['type'] == 'preview':
        # If user just wants a preview, simply create a dummy post so it can be rendered.
        previewpost = Post( body = request.REQUEST['body'],
                            markup = request.REQUEST.get('markup', None), )
        return HttpResponse( unicode(previewpost.body_escaped()) )


    # All available objects should be loaded from the _id variables.
    post_obj = None
    thread = None
    category = None
    context = {
        'bbcodewysiwyg': enable_wysiwyg_editor() \
            or (get_sph_setting('board_wysiwyg_testing') \
                    and request.REQUEST.get('wysiwyg', False)) }

    if post_id is None and 'post_id' in request.REQUEST:
        # if no post_id is given take it from the request.
        post_id = request.REQUEST['post_id']

    if post_id is not None:
        # User wants to edit a post ..
        try:
            post_obj = Post.allobjects.get( pk = post_id )
        except Post.DoesNotExist:
            raise Http404

        if not post_obj.allowEditing():
            raise PermissionDenied()
        thread = post_obj.thread
        category = post_obj.category

    else:
        # User wants to create a new post (thread or reply)
        if 'thread' in request.REQUEST:
            thread_id = request.REQUEST['thread']

        if thread_id is not None:
            # User is posting (replying) to a thread.
            try:
                thread = Post.allobjects.get( pk = thread_id )
            except Post.DoesNotExist:
                raise Http404

            category = thread.category

            if not thread.allowPosting( request.user ):
                raise PermissionDenied()
        else:
            # User is creating a new thread.
            category = get_object_or_404(Category, pk = category_id)
            if not category.allowPostThread( request.user ):
                raise PermissionDenied()

    context['thread'] = thread
    context['category'] = category

    category_type = category.get_category_type()
    MyPostForm = PostForm
    if category_type is not None:
        MyPostForm = category_type.get_post_form_class(thread, post_obj)

    allow_attachments = get_sph_setting('board_allow_attachments')
    allowedattachments = 0
    if allow_attachments:
        allowedattachments = 1
        # bool is a subclass of int (hehe)
        if isinstance(allow_attachments, int) and type(allow_attachments) != bool:
            allowedattachments = allow_attachments

    PostAttachmentFormSet = modelformset_factory(PostAttachment,
                                                 form=PostAttachmentForm,
                                                 fields=('fileupload',),
                                                 can_delete=True,
                                                 max_num=allowedattachments)

    post_attachment_qs = PostAttachment.objects.none()
    if post_obj:
        post_attachment_qs = post_obj.attachments.all()

    if request.method == 'POST':
        postForm = MyPostForm(request.POST)
        postForm.init_for_category_type(category_type, post_obj)
        pollForm = PostPollForm(request.POST)

        create_post = True
        if allowedattachments and 'cmd_addfile' in request.POST:
            create_post = False

        post_attachment_formset = PostAttachmentFormSet(request.POST,
                                                        request.FILES,
                                                        queryset = post_attachment_qs,
                                                        prefix='attachment'
                                                        )

        if post_attachment_formset.is_valid():
            instances = post_attachment_formset.save(commit=False)
            for attachment in instances:
                if not post_obj:
                    # if there is no post yet.. we need to create a draft
                    post_obj = Post( category = category,
                                 author = request.user,
                                 thread = thread,
                                 is_hidden = 1,
                                 )
                    post_obj.set_new( True )
                    post_obj.save()

                # Reference the post and save the attachment
                attachment.post = post_obj
                attachment.save()

        if create_post \
                and postForm.is_valid() \
                and ('createpoll' not in request.POST \
                         or pollForm.is_valid()):
            data = postForm.cleaned_data

            if post_obj:
                newpost = post_obj
                newpost.subject = data['subject']
                newpost.body = data['body']
                # make post visible
                newpost.is_hidden = 0
                if not post_obj.is_new() and category_type.append_edit_message_to_post(post_obj):
                    newpost.body += "\n\n" + _(u'--- Last Edited by %(username)s at %(edit_date)s ---') % {'username':get_user_displayname( request.user ), 'edit_date':format_date( timezone.now())}
            else:
                user = request.user.is_authenticated() and request.user or None
                newpost = Post( category = category,
                                subject = data['subject'],
                                body = data['body'],
                                author = user,
                                thread = thread,
                                )
            if 'markup' in data:
                newpost.markup = data['markup']

            elif len( POST_MARKUP_CHOICES ) == 1:
                newpost.markup = POST_MARKUP_CHOICES[0][0]

            newpost.save(additional_data = data)

            #category_type.save_post( newpost, data )


            # Creating monitor
            if request.POST.get( 'addmonitor', False ):
                newpost.toggle_monitor()


            if 'createpoll' in request.POST and request.POST['createpoll'] == '1':
                newpost.set_poll( True );
                newpost.save()

                # Creating poll...
                polldata = pollForm.cleaned_data
                newpoll = Poll( post = newpost,
                                question = polldata['question'],
                                choices_per_user = polldata['choicesPerUser'])
                newpoll.save()

                choices = polldata['answers'].splitlines()
                i=0
                for choice in choices:
                    pollchoice = PollChoice( poll = newpoll,
                                             choice = choice,
                                             count = 0,
                                             sortorder = i)
                    i+=1
                    pollchoice.save()
                if request.user.is_authenticated():
                    messages.success(request,  message = ugettext(u'Vote created successfully.') )

            if request.user.is_authenticated():
                if post_obj:
                    messages.success(request,  message = ugettext(u'Post edited successfully.') )
                else:
                    messages.success(request,  message = ugettext(u'Post created successfully.') )
            if thread == None: thread = newpost
            return HttpResponseRedirect( newpost.get_absolute_url() )

    else:
        postForm = MyPostForm( )
        postForm.init_for_category_type(category_type, post_obj)
        pollForm = PostPollForm()

        post_attachment_formset = PostAttachmentFormSet(queryset = post_attachment_qs,
                                                        prefix='attachment')

    if post_obj:
        postForm.fields['subject'].initial = post_obj.subject
        postForm.fields['body'].initial = post_obj.body
        if 'markup' in postForm.fields:
            postForm.fields['markup'].initial = post_obj.markup
        context['post'] = post_obj
        context['thread'] = post_obj.thread or post_obj
    elif 'quote' in request.REQUEST:
        quotepost = get_object_or_404(Post, pk = request.REQUEST['quote'] )
        postForm.fields['subject'].initial = 'Re: %s' % thread.subject
        if quotepost.author == None:
            username = '******'
        else:
            username = quotepost.author.username
        postForm.fields['body'].initial = '[quote=%s;%s]\n%s\n[/quote]\n' % (username, quotepost.id, quotepost.body)
    elif thread:
        postForm.fields['subject'].initial = 'Re: %s' % thread.subject
    context['form'] = postForm

    # Only allow polls if this is a new _thread_ (not a reply)
    if (not thread and not post_obj) or (post_obj and post_obj.is_new() and post_obj.thread is None):
        context['pollform'] = pollForm
    context['post_attachment_formset'] = post_attachment_formset
    if 'createpoll' in request.REQUEST:
        context['createpoll'] = request.REQUEST['createpoll']

    res = render_to_response( "sphene/sphboard/post.html", context,
                              context_instance = RequestContext(request) )
    # Maybe the user is in the 'edit' form, which should not be cached.
    res.sph_lastmodified = True
    return res