Example #1
0
def mobile_reply(request, post_id):
    post = get_object_or_404(Post, id=post_id)
    if not request.user.is_authenticated or post.topic.closed and not (request.user.is_superuser or request.user in forum.moderators.all()):
        raise Http404
    ip = get_client_ip(request)
    post_form_kwargs = {
        "topic":post.topic,
        "user":request.user,
        "ip":ip,
        'is_ip_banned': request.is_ip_banned,
    }
    if AddPostForm.FORM_NAME in request.POST:
        reply_form = AddPostForm(request.POST, request.FILES, **post_form_kwargs)
        if reply_form.is_valid():
            post = reply_form.save()
            messages.success(request, _("Reply saved."))
            return HttpResponseRedirect(post.get_mobile_url())
    else:
        reply_form = AddPostForm(
            initial={
                'markup': request.user.forum_profile.markup,
                'subscribe': False,
                'body':'[quote=' + post.user.username + ']' + post.body + '[/quote]\n',
            },
            **post_form_kwargs
        )
    return render(request, 'djangobb_forum/mobile/reply.html', {
        'form': reply_form,
        'post': post
        })
Example #2
0
def add_topic(request, forum_id, full=True):
    """
    create a new topic, with or without poll
    """
    forum = get_object_or_404(Forum, pk=forum_id)
    if not forum.category.has_access(request.user) or (forum.moderator_only and not (request.user.is_superuser or request.user in forum.moderators.all())):
        return HttpResponseForbidden()

    ip = request.META.get('REMOTE_ADDR', None)
    post_form_kwargs = {"forum":forum, "user":request.user, "ip":ip, }

    if request.method == 'POST':
        form = AddPostForm(request.POST, request.FILES, **post_form_kwargs)
        if form.is_valid():
            all_valid = True
        else:
            all_valid = False

        poll_form = PollForm(request.POST)
        create_poll = poll_form.create_poll()
        if not create_poll:
            # All poll fields are empty: User didn't want to create a poll
            # Don't run validation and remove all form error messages
            poll_form = PollForm() # create clean form without form errors
        elif not poll_form.is_valid():
            all_valid = False

        if all_valid:
            post = form.save()
            if create_poll:
                poll_form.save(post)
                messages.success(request, _("Topic with poll saved."))
            else:
                messages.success(request, _("Topic saved."))
            return HttpResponseRedirect(post.get_absolute_url() if full else post.get_mobile_url())
    else:
        form = AddPostForm(
            initial={
                'markup': request.user.forum_profile.markup,
                'subscribe': request.user.forum_profile.auto_subscribe,
            },
            **post_form_kwargs
        )

    # if creating a new topic and allowed
    create_poll_form = forum_id and forum_settings.ALLOW_POLLS

    poll_form = PollForm()

    context = {
        'forum': forum,
        'create_poll_form': create_poll_form,
        'poll_form': poll_form,
        'form': form,
        'form_url': request.path,
        'back_url': forum.get_absolute_url(),
    }
    return render(request, 'djangobb_forum/add_topic.html' if full else 'djangobb_forum/mobile/add_topic.html', context)
Example #3
0
def add_topic(request, forum_id):
    """
    create a new topic, with or without poll
    """
    forum = get_object_or_404(Forum, pk=forum_id)
    if not forum.category.has_access(request.user):
        raise PermissionDenied

    ip = request.META.get('REMOTE_ADDR', None)
    post_form_kwargs = {"forum":forum, "user":request.user, "ip":ip, }

    poll_form = None
    if request.method == 'POST':
        form = AddPostForm(request.POST, request.FILES, **post_form_kwargs)
        if form.is_valid():
            all_valid = True
        else:
            all_valid = False

        if forum_settings.ENABLE_POLLS:
            poll_form = PollForm(request.POST)
            if not poll_form.has_data():
                # All poll fields are empty: User didn't want to create a poll
                # Don't run validation and remove all form error messages
                poll_form = PollForm() # create clean form without form errors
            elif not poll_form.is_valid():
                all_valid = False

        if all_valid:
            post = form.save()
            if poll_form and poll_form.has_data():
                poll_form.save(post)
                messages.success(request, _("Topic with poll saved."))
            else:
                messages.success(request, _("Topic saved."))
            return HttpResponseRedirect(post.get_absolute_url())
    else:
        form = AddPostForm(
            initial={
                'markup': request.user.forum_profile.markup,
                'subscribe': request.user.forum_profile.auto_subscribe,
            },
            **post_form_kwargs
        )
        if forum_settings.ENABLE_POLLS and forum_id: # Create a new topic
            poll_form = PollForm()

    context = {
        'forum': forum,
        'create_poll_form': poll_form,
        'form': form,
        'form_url': request.path,
        'back_url': forum.get_absolute_url(),
    }
    return render(request, 'djangobb_forum/add_topic.html', context)
Example #4
0
def add_topic(request, forum_id):
    """
    create a new topic, with or without poll
    """
    forum = get_object_or_404(Forum, pk=forum_id)
    if not forum.category.has_access(request.user):
        return HttpResponseForbidden()

    ip = request.META.get("REMOTE_ADDR", None)
    post_form_kwargs = {"forum": forum, "user": request.user, "ip": ip}

    if request.method == "POST":
        form = AddPostForm(request.POST, request.FILES, **post_form_kwargs)
        if form.is_valid():
            all_valid = True
        else:
            all_valid = False

        poll_form = PollForm(request.POST)
        if not poll_form.has_data():
            # All poll fields are empty: User didn't want to create a poll
            # Don't run validation and remove all form error messages
            poll_form = PollForm()  # create clean form without form errors
        elif not poll_form.is_valid():
            all_valid = False

        if all_valid:
            post = form.save()
            if poll_form.has_data():
                poll_form.save(post)
                messages.success(request, _("Topic with poll saved."))
            else:
                messages.success(request, _("Topic saved."))
            return HttpResponseRedirect(post.get_absolute_url())
    else:
        form = AddPostForm(
            initial={
                "markup": request.user.forum_profile.markup,
                "subscribe": request.user.forum_profile.auto_subscribe,
            },
            **post_form_kwargs
        )
        if forum_id:  # Create a new topic
            poll_form = PollForm()

    context = {
        "forum": forum,
        "create_poll_form": poll_form,
        "form": form,
        "form_url": request.path,
        "back_url": forum.get_absolute_url(),
    }
    return render(request, "djangobb_forum/add_topic.html", context)
Example #5
0
def add_topic(request, forum_id):
    """
    create a new topic, with or without poll
    """
    forum = get_object_or_404(Forum, pk=forum_id)
    if not forum.category.has_access(request.user):
        raise PermissionDenied

    ip = request.META.get('REMOTE_ADDR', None)
    post_form_kwargs = {
        "forum": forum,
        "user": request.user,
        "ip": ip,
    }

    poll_form = None
    if request.method == 'POST':
        form = AddPostForm(request.POST, request.FILES, **post_form_kwargs)
        if form.is_valid():
            all_valid = True
        else:
            all_valid = False

        if forum_settings.ENABLE_POLLS:
            poll_form = PollForm(request.POST)
            if not poll_form.has_data():
                # All poll fields are empty: User didn't want to create a poll
                # Don't run validation and remove all form error messages
                poll_form = PollForm()  # create clean form without form errors
            elif not poll_form.is_valid():
                all_valid = False

        if all_valid:
            post = form.save()
            if poll_form and poll_form.has_data():
                poll_form.save(post)
                messages.success(request, _("Topic with poll saved."))
            else:
                messages.success(request, _("Topic saved."))
            return HttpResponseRedirect(post.get_absolute_url())
    else:
        form = AddPostForm(initial={
            'markup':
            request.user.forum_profile.markup,
            'subscribe':
            request.user.forum_profile.auto_subscribe,
        },
                           **post_form_kwargs)
        if forum_settings.ENABLE_POLLS and forum_id:  # Create a new topic
            poll_form = PollForm()

    context = {
        'forum': forum,
        'create_poll_form': poll_form,
        'form': form,
        'form_url': request.path,
        'back_url': forum.get_absolute_url(),
        'forum_settings': forum_settings,
    }
    return render(request, 'djangobb_forum/add_topic.html', context)
Example #6
0
def show_topic(request, topic_id, full=True):
    topic = get_object_or_404(
        Topic.objects.filter(deleted=False).select_related(), pk=topic_id)
    if not topic.forum.category.has_access(request.user):
        return HttpResponseForbidden()
    Topic.objects.filter(deleted=False,
                         pk=topic.id).update(views=F('views') + 1)

    last_post = topic.last_post

    if request.user.is_authenticated():
        topic.update_read(request.user)
    posts = topic.posts.filter(deleted=False) \
        .select_related('user__forum_profile__player') \
        .prefetch_related('attachments')

    initial = {}
    if request.user.is_authenticated():
        initial = {'markup': request.user.forum_profile.markup}
    form = AddPostForm(topic=topic, initial=initial)

    moderator = request.user.is_superuser or\
        request.user in topic.forum.moderators.all()
    if request.user.is_authenticated(
    ) and request.user in topic.subscribers.all():
        subscribed = True
    else:
        subscribed = False

    highlight_word = request.GET.get('hl', '')
    if full:
        return render(
            request, 'djangobb_forum/topic.html', {
                'categories': Category.objects.all(),
                'topic': topic,
                'last_post': last_post,
                'form': form,
                'moderator': moderator,
                'subscribed': subscribed,
                'posts': posts,
                'highlight_word': highlight_word,
            })
    else:
        return render(request, 'djangobb_forum/lofi/topic.html', {
            'categories': Category.objects.all(),
            'topic': topic,
            'posts': posts,
        })
Example #7
0
def delete_posts(request, topic_id):

    topic = Topic.objects.select_related().get(pk=topic_id)

    if forum_moderated_by(topic, request.user):
        deleted = False
        post_list = request.POST.getlist('post')
        for post_id in post_list:
            if not deleted:
                deleted = True
            delete_post(request, post_id)
        if deleted:
            return HttpResponseRedirect(topic.get_absolute_url())

    last_post = topic.posts.latest()

    if request.user.is_authenticated():
        topic.update_read(request.user)

    posts = topic.posts.all().select_related()

    profiles = Profile.objects.filter(user__pk__in=set(x.user.id
                                                       for x in posts))
    profiles = dict((x.user_id, x) for x in profiles)

    for post in posts:
        post.user.forum_profile = profiles[post.user.id]

    initial = {}
    if request.user.is_authenticated():
        initial = {'markup': request.user.forum_profile.markup}
    form = AddPostForm(topic=topic, initial=initial)

    moderator = request.user.is_superuser or\
        request.user in topic.forum.moderators.all()
    if request.user.is_authenticated(
    ) and request.user in topic.subscribers.all():
        subscribed = True
    else:
        subscribed = False
    return {
        'topic': topic,
        'last_post': last_post,
        'form': form,
        'moderator': moderator,
        'subscribed': subscribed,
        'paged_qs': posts,
    }
Example #8
0
def delete_posts(request, topic_id):

    topic = Topic.objects.select_related().get(pk=topic_id)

    if forum_moderated_by(topic, request.user):
        deleted = False
        post_list = request.POST.getlist('post')
        for post_id in post_list:
            if not deleted:
                deleted = True
            delete_post(request, post_id)
        if deleted:
            messages.success(request, _("Post deleted."))
            return HttpResponseRedirect(topic.get_absolute_url())

    last_post = topic.posts.latest()

    if request.user.is_authenticated():
        topic.update_read(request.user)

    posts = topic.posts.all().select_related()

    initial = {}
    if request.user.is_authenticated():
        initial = {'markup': request.user.forum_profile.markup}
    form = AddPostForm(topic=topic,
                       initial=initial,
                       is_ip_banned=request.is_ip_banned)

    moderator = request.user.is_superuser or\
        request.user in topic.forum.moderators.all()
    if request.user.is_authenticated(
    ) and request.user in topic.subscribers.all():
        subscribed = True
    else:
        subscribed = False
    return render(
        request, 'djangobb_forum/delete_posts.html', {
            'topic': topic,
            'last_post': last_post,
            'form': form,
            'moderator': moderator,
            'subscribed': subscribed,
            'posts': posts,
        })
Example #9
0
def mobile_reply(request, post_id):
    post = get_object_or_404(Post, id=post_id)
    if not request.user.is_authenticated or post.topic.closed and not (
            request.user.is_superuser
            or request.user in forum.moderators.all()):
        raise Http404
    ip = get_client_ip(request)
    post_form_kwargs = {
        "topic": post.topic,
        "user": request.user,
        "ip": ip,
        'is_ip_banned': request.is_ip_banned,
        "request_data": request.META,
        "url": "http://scratch.mit.edu%s" % post.get_absolute_url(),
    }
    if AddPostForm.FORM_NAME in request.POST:
        reply_form = AddPostForm(request.POST, request.FILES,
                                 **post_form_kwargs)
        if reply_form.is_valid():
            post = reply_form.save()
            messages.success(request, _("Reply saved."))
            return HttpResponseRedirect(post.get_mobile_url())
    else:
        reply_form = AddPostForm(initial={
            'markup':
            request.user.forum_profile.markup,
            'subscribe':
            False,
            'body':
            '[quote=' + post.user.username + ']' + post.body + '[/quote]\n',
        },
                                 **post_form_kwargs)
    return render(request, 'djangobb_forum/mobile/reply.html', {
        'form': reply_form,
        'post': post
    })
Example #10
0
def show_topic(request, topic_id, full=True):
    """
    * Display a topic
    * save a reply
    * save a poll vote
    
    TODO: Add reply in lofi mode
    """
    post_request = request.method == "POST"
    user_is_authenticated = request.user.is_authenticated()
    if post_request and not user_is_authenticated:
        # Info: only user that are logged in should get forms in the page.
        return HttpResponseForbidden()

    topic = get_object_or_404(Topic.objects.select_related(), pk=topic_id)
    if not topic.forum.category.has_access(request.user):
        return HttpResponseForbidden()
    Topic.objects.filter(pk=topic.id).update(views=F('views') + 1)

    last_post = topic.last_post

    if request.user.is_authenticated():
        topic.update_read(request.user)
    posts = topic.posts.all().select_related()

    moderator = request.user.is_superuser or request.user in topic.forum.moderators.all(
    )
    if user_is_authenticated and request.user in topic.subscribers.all():
        subscribed = True
    else:
        subscribed = False

    # reply form
    reply_form = None
    form_url = None
    back_url = None
    if user_is_authenticated and not topic.closed:
        form_url = request.path + "#reply"  # if form validation failed: browser should scroll down to reply form ;)
        back_url = request.path
        ip = request.META.get('REMOTE_ADDR', None)
        post_form_kwargs = {"topic": topic, "user": request.user, "ip": ip}
        if post_request and AddPostForm.FORM_NAME in request.POST:
            reply_form = AddPostForm(request.POST, request.FILES,
                                     **post_form_kwargs)
            if reply_form.is_valid():
                post = reply_form.save()
                messages.success(request, _("Your reply saved."))
                return HttpResponseRedirect(post.get_absolute_url())
        else:
            reply_form = AddPostForm(initial={
                'markup':
                request.user.forum_profile.markup,
                'subscribe':
                request.user.forum_profile.auto_subscribe,
            },
                                     **post_form_kwargs)

    # handle poll, if exists
    poll_form = None
    polls = topic.poll_set.all()
    if not polls:
        poll = None
    else:
        poll = polls[0]
        if user_is_authenticated:  # Only logged in users can vote
            poll.auto_deactivate()
            has_voted = request.user in poll.users.all()
            if not post_request or not VotePollForm.FORM_NAME in request.POST:
                # It's not a POST request or: The reply form was send and not a poll vote
                if poll.active and not has_voted:
                    poll_form = VotePollForm(poll)
            else:
                if not poll.active:
                    messages.error(request, _("This poll is not active!"))
                    return HttpResponseRedirect(topic.get_absolute_url())
                elif has_voted:
                    messages.error(
                        request,
                        _("You have already vote to this poll in the past!"))
                    return HttpResponseRedirect(topic.get_absolute_url())

                poll_form = VotePollForm(poll, request.POST)
                if poll_form.is_valid():
                    ids = poll_form.cleaned_data["choice"]
                    queryset = poll.choices.filter(id__in=ids)
                    queryset.update(votes=F('votes') + 1)
                    poll.users.add(
                        request.user)  # save that this user has vote
                    messages.success(request, _("Your votes are saved."))
                    return HttpResponseRedirect(topic.get_absolute_url())

    highlight_word = request.GET.get('hl', '')
    if full:
        return render(
            request, 'djangobb_forum/topic.html', {
                'categories': Category.objects.all(),
                'topic': topic,
                'last_post': last_post,
                'form_url': form_url,
                'reply_form': reply_form,
                'back_url': back_url,
                'moderator': moderator,
                'subscribed': subscribed,
                'posts': posts,
                'highlight_word': highlight_word,
                'poll': poll,
                'poll_form': poll_form,
            })
    else:
        return render(
            request, 'djangobb_forum/lofi/topic.html', {
                'categories': Category.objects.all(),
                'topic': topic,
                'posts': posts,
                'poll': poll,
                'poll_form': poll_form,
            })
Example #11
0
def show_topic(request, topic_id, full=True):
    """
    * Display a topic
    * save a reply
    * save a poll vote
    """
    post_request = request.method == "POST"
    user_is_authenticated = request.user.is_authenticated()
    if post_request and not user_is_authenticated:
        # Info: only user that are logged in should get forms in the page.
        return HttpResponseForbidden()

    topic = get_object_or_404(Topic.objects.select_related(), pk=topic_id)
    if not topic.forum.category.has_access(request.user):
        return HttpResponseForbidden()
    Topic.objects.filter(pk=topic.id).update(views=F('views') + 1)
    last_post = topic.last_post

    if request.user.is_authenticated():
        topic.update_read(request.user)
    # without specifying, following query wouldn't select related properly
    posts = topic.posts.select_related('user__userprofile',
        'user__forum_profile',
        'updated_by', 'user').prefetch_related('user__groups').all()
    edit_start = timezone.now() - timedelta(minutes=1)
    edit_end = timezone.now()
    editable = posts.filter(created__range=(edit_start, edit_end)).filter(user_id=request.user.id)
    can_edit = request.user.has_perm('djangobb_forum.change_post')
    try:
        page_url_parameter = int(request.GET.get('page') or 1)
    except:
        page_url_parameter = 1
    first_post_number = int(forum_settings.TOPIC_PAGE_SIZE) * (page_url_parameter - 1)
    can_close = can_close_topic(request.user, topic)

    moderator = request.user.is_superuser or request.user in topic.forum.moderators.all()
    if user_is_authenticated and request.user in topic.subscribers.all():
        subscribed = True
    else:
        subscribed = False

    # reply form
    reply_form = None
    form_url = None
    back_url = None
    if user_is_authenticated and (not topic.closed or moderator):
        form_url = request.path + '?' + request.META['QUERY_STRING'] + '#reply' # if form validation failed: browser should scroll down to reply form ;)
        back_url = request.path
        ip = get_client_ip(request)
        post_form_kwargs = {
            "topic":topic,
            "user":request.user,
            "ip":ip,
            'is_ip_banned': request.is_ip_banned,
        }
        if post_request and AddPostForm.FORM_NAME in request.POST:

            reply_form = AddPostForm(request.POST, request.FILES, **post_form_kwargs)
            if reply_form.is_valid():
                post = reply_form.save()
                messages.success(request, _("Reply saved."))
                return HttpResponseRedirect(post.get_absolute_url() if full else post.get_mobile_url())
        else:
            reply_form = AddPostForm(
                initial={
                    'markup': request.user.forum_profile.markup,
                    'subscribe': False,
                },
                **post_form_kwargs
            )

    group_titles = {}
    
    for post in posts:
        
        if post.user.is_superuser:
            group_titles[post.user] = "Scratch Team"
            
        else: 
            temp_names = [group.name for group in post.user.groups.all()]
            if "Forum Moderators" in temp_names:
                group_titles[post.user] = "Forum Moderator"
            elif "Scratchers" in temp_names:
                group_titles[post.user] = "Scratcher"
            elif "New Scratchers" in temp_names:
                group_titles[post.user] = "New to Scratch"
            else:
                group_titles[post.user] = "Ungrouped"
    
        
    # handle poll, if exists
    poll_form = None
    polls = topic.poll_set.all()
    if not polls:
        poll = None
    else:
        poll = polls[0]
        if user_is_authenticated: # Only logged in users can vote
            poll.auto_deactivate()
            has_voted = request.user in poll.users.all()
            if not post_request or not VotePollForm.FORM_NAME in request.POST:
                # It's not a POST request or: The reply form was send and not a poll vote
                if poll.active and not has_voted:
                    poll_form = VotePollForm(poll)
            else:
                if not poll.active:
                    messages.error(request, _("This poll is not active."))
                    return HttpResponseRedirect(topic.get_absolute_url())
                elif has_voted:
                    messages.error(request, _("You already voted on this poll."))
                    return HttpResponseRedirect(topic.get_absolute_url())

                poll_form = VotePollForm(poll, request.POST)
                if poll_form.is_valid():
                    ids = poll_form.cleaned_data["choice"]
                    queryset = poll.choices.filter(id__in=ids)
                    queryset.update(votes=F('votes') + 1)
                    poll.users.add(request.user) # save that this user has vote
                    messages.success(request, _("Vote saved."))
                    return HttpResponseRedirect(topic.get_absolute_url())

    highlight_word = request.GET.get('hl', '')
    if full:
        return render(request, 'djangobb_forum/topic.html', {'categories': Category.objects.all(),
                'topic': topic,
                'last_post': last_post,
                'form_url': form_url,
                'reply_form': reply_form,
                'back_url': back_url,
                'moderator': moderator,
                'subscribed': subscribed,
                'posts': posts,
                'first_post_number': first_post_number,
                'highlight_word': highlight_word,
                'poll': poll,
                'poll_form': poll_form,
                'editable': editable,
                'can_edit': can_edit,
                'can_close': can_close,
                'group_titles': group_titles,
                'simple_user_agent': simple_user_agent(request),
                })
    else:
        return render(request, 'djangobb_forum/mobile/topic.html', {'categories': Category.objects.all(),
                'topic': topic,
                'posts': posts,
                'poll': poll,
                'poll_form': poll_form,
                'reply_form': reply_form,
                })
Example #12
0
def show_topic(request, topic_id, full=True):
    topic = get_object_or_404(Topic.objects.select_related(), pk=topic_id)
    if not topic.forum.category.has_access(request.user):
        return HttpResponseForbidden()
    Topic.objects.filter(pk=topic.id).update(views=F('views') + 1)

    last_post = topic.last_post

    if request.user.is_authenticated():
        topic.update_read(request.user)

    posts = topic.posts.all().select_related()

    users = set(post.user.id for post in posts)
    profiles = Profile.objects.filter(user__pk__in=users)
    profiles = dict((profile.user_id, profile) for profile in profiles)

    for post in posts:
        post.user.forum_profile = profiles[post.user.id]

    if forum_settings.REPUTATION_SUPPORT:
        replies_list = Reputation.objects.filter(to_user__pk__in=users).values('to_user_id').annotate(Sum('sign'))
        replies = {}
        for r in replies_list:
            replies[r['to_user_id']] = r['sign__sum']

        for post in posts:
            post.user.forum_profile.reply_total = replies.get(post.user.id, 0)

    initial = {}
    if request.user.is_authenticated():
        initial = {'markup': request.user.forum_profile.markup}
    form = AddPostForm(topic=topic, initial=initial)

    moderator = request.user.is_superuser or\
        request.user in topic.forum.moderators.all()
    if request.user.is_authenticated() and request.user in topic.subscribers.all():
        subscribed = True
    else:
        subscribed = False

    highlight_word = request.GET.get('hl', '')
    if full:
        return {'categories': Category.objects.all(),
                'topic': topic,
                'last_post': last_post,
                'form': form,
                'moderator': moderator,
                'subscribed': subscribed,
                'paged_qs': posts,
                'highlight_word': highlight_word,
                }
    else:
        pages, paginator, paged_list_name = paginate(posts, request, forum_settings.TOPIC_PAGE_SIZE)
        return {'categories': Category.objects.all(),
                'topic': topic,
                'pages': pages,
                'paginator': paginator,
                'posts': paged_list_name,
                'TEMPLATE': 'forum/lofi/topic.html'
                }
Example #13
0
def show_topic(request, topic_id, full=True):
    topic = get_object_or_404(Topic.objects.select_related(), pk=topic_id)
    if not topic.forum.category.has_access(request.user):
        return HttpResponseForbidden()
    Topic.objects.filter(pk=topic.id).update(views=F('views') + 1)

    last_post = topic.last_post

    if request.user.is_authenticated():
        topic.update_read(request.user)
    #@paged can't be used in this view. (ticket #180)
    #TODO: must be refactored (ticket #39)
    from django.core.paginator import Paginator, EmptyPage, InvalidPage
    try:
        page = int(request.GET.get('page', 1))
    except ValueError:
        page = 1
    paginator = Paginator(topic.posts.all().select_related(),
                          forum_settings.TOPIC_PAGE_SIZE)
    try:
        page_obj = paginator.page(page)
    except (InvalidPage, EmptyPage):
        raise Http404
    posts = page_obj.object_list
    users = set(post.user.id for post in posts)
    profiles = Profile.objects.filter(user__pk__in=users)
    profiles = dict((profile.user_id, profile) for profile in profiles)

    for post in posts:
        post.user.forum_profile = profiles[post.user.id]

    if forum_settings.REPUTATION_SUPPORT:
        replies_list = Reputation.objects.filter(
            to_user__pk__in=users).values('to_user_id').annotate(Sum('sign'))
        replies = {}
        for r in replies_list:
            replies[r['to_user_id']] = r['sign__sum']

        for post in posts:
            post.user.forum_profile.reply_total = replies.get(post.user.id, 0)

    initial = {}
    if request.user.is_authenticated():
        initial = {'markup': request.user.forum_profile.markup}
    form = AddPostForm(topic=topic, initial=initial)

    moderator = request.user.is_superuser or\
        request.user in topic.forum.moderators.all()
    if request.user.is_authenticated(
    ) and request.user in topic.subscribers.all():
        subscribed = True
    else:
        subscribed = False

    highlight_word = request.GET.get('hl', '')
    if full:
        return {
            'categories': Category.objects.all(),
            'topic': topic,
            'last_post': last_post,
            'form': form,
            'moderator': moderator,
            'subscribed': subscribed,
            'posts': posts,
            'highlight_word': highlight_word,
            'page': page,
            'page_obj': page_obj,
            'pages': paginator.num_pages,
            'results_per_page': paginator.per_page,
            'is_paginated': page_obj.has_other_pages(),
        }
    else:
        return {
            'categories': Category.objects.all(),
            'topic': topic,
            'pages': paginator.num_pages,
            'paginator': paginator,
            'posts': posts,
            'TEMPLATE': 'forum/lofi/topic.html'
        }
Example #14
0
def move_posts(request, topic_id):

    topic = Topic.objects.select_related().get(pk=topic_id)
    from_forum = topic.forum

    if forum_moderated_by(topic, request.user):
        moved = False
        post_list = request.POST.getlist('post')
        if 'to_topic' in request.POST:
            match = re.match(r'.*?(\d+)', request.POST['to_topic'])
            if match is None:
                messages.error(request, _("The topic ID must be an integer."))
            else:
                to_topic_id = int(match.group(1))
                try:
                    to_topic = Topic.objects.select_related().get(
                        pk=to_topic_id)
                except Topic.DoesNotExist:
                    messages.error(request, _("That thread doesn't exist."))
                else:
                    if 'move_all' in request.POST:
                        Post.objects.filter(topic=topic).update(topic=to_topic)
                        topic.delete()
                        moved = True
                        deleted = True
                    else:
                        for post_id in post_list:
                            if not moved:
                                moved = True
                            post = get_object_or_404(Post, pk=post_id)
                            if post.topic != to_topic:
                                last = (topic.last_post == post)
                                if forum_moderated_by(to_topic, request.user):
                                    post.topic = to_topic
                                    post.save()
                        if Post.objects.filter(
                                topic__id=topic.id).count() == 0:
                            topic.delete()
                            deleted = True
                        else:
                            deleted = False
                            try:
                                topic.last_post = Post.objects.filter(
                                    topic__id=topic.id).latest()
                            except Post.DoesNotExist:
                                topic.last_post = None
                            topic.post_count = Post.objects.filter(
                                topic__id=topic.id).count()
                            topic.save()
                    try:
                        from_forum.last_post = Post.objects.filter(
                            topic__forum__id=from_forum.id).latest()
                    except Post.DoesNotExist:
                        from_forum.last_post = None
                    from_forum.post_count = Post.objects.filter(
                        topic__forum__id=from_forum.id).count()
                    from_forum.topic_count = Topic.objects.filter(
                        forum__id=from_forum.id).count()
                    from_forum.save()

                    to_topic.post_count = Post.objects.filter(
                        topic__id=to_topic.id).count()
                    to_topic.save()

                    if moved:
                        messages.success(request, _("Posts moved."))
                        if not deleted:
                            return HttpResponseRedirect(
                                topic.get_absolute_url())
                        else:
                            return HttpResponseRedirect(
                                from_forum.get_absolute_url())

    last_post = topic.posts.latest()

    if request.user.is_authenticated():
        topic.update_read(request.user)

    posts = topic.posts.all().select_related()

    initial = {}
    if request.user.is_authenticated():
        initial = {'markup': request.user.forum_profile.markup}
    form = AddPostForm(topic=topic,
                       initial=initial,
                       is_ip_banned=request.is_ip_banned)

    moderator = request.user.is_superuser or\
        request.user in topic.forum.moderators.all()
    if request.user.is_authenticated(
    ) and request.user in topic.subscribers.all():
        subscribed = True
    else:
        subscribed = False
    return render(
        request, 'djangobb_forum/move_posts.html', {
            'categories': Category.objects.all(),
            'exclude_topic': from_forum,
            'topic': topic,
            'last_post': last_post,
            'form': form,
            'moderator': moderator,
            'subscribed': subscribed,
            'posts': posts,
        })
Example #15
0
def add_topic(request, forum_id, full=True):
    """
    create a new topic, with or without poll
    """
    forum = get_object_or_404(Forum, pk=forum_id)
    if not forum.category.has_access(request.user) or (
            forum.moderator_only
            and not (request.user.is_superuser
                     or request.user in forum.moderators.all())):
        return HttpResponseForbidden()

    ip = get_client_ip(request)
    post_form_kwargs = {
        "forum": forum,
        "user": request.user,
        "ip": ip,
        "is_ip_banned": request.is_ip_banned,
        "request_data": request.META
    }

    if request.method == 'POST':
        form = AddPostForm(request.POST, request.FILES, **post_form_kwargs)
        if form.is_valid():
            all_valid = True
        else:
            all_valid = False

        poll_form = PollForm(request.POST)
        create_poll = poll_form.create_poll()
        if not create_poll:
            # All poll fields are empty: User didn't want to create a poll
            # Don't run validation and remove all form error messages
            poll_form = PollForm()  # create clean form without form errors
        elif not poll_form.is_valid():
            all_valid = False

        if all_valid:
            post = form.save()
            if create_poll:
                poll_form.save(post)
                messages.success(request, _("Topic with poll saved."))
            else:
                messages.success(request, _("Topic saved."))
            return HttpResponseRedirect(
                post.get_absolute_url() if full else post.get_mobile_url())
    else:
        form = AddPostForm(initial={
            'markup': request.user.forum_profile.markup,
            'subscribe': True,
        },
                           **post_form_kwargs)

    # if creating a new topic and allowed
    create_poll_form = forum_id and forum_settings.ALLOW_POLLS

    poll_form = PollForm()

    context = {
        'forum': forum,
        'create_poll_form': create_poll_form,
        'poll_form': poll_form,
        'form': form,
        'form_url': request.path,
        'back_url': forum.get_absolute_url(),
        'simple_user_agent': simple_user_agent(request),
    }
    return render(
        request, 'djangobb_forum/add_topic.html'
        if full else 'djangobb_forum/mobile/add_topic.html', context)
Example #16
0
def show_topic(request, topic_id, full=True):
    """
    * Display a topic
    * save a reply
    * save a poll vote
    """
    post_request = request.method == "POST"
    user_is_authenticated = request.user.is_authenticated()
    if post_request and (not user_is_authenticated or
                         not request.user.has_perm('userprofiles.is_social')):
        # Info: only user that are logged in should get forms in the page.
        return HttpResponseForbidden()

    topic = get_object_or_404(Topic.objects.select_related(), pk=topic_id)
    if not topic.forum.category.has_access(request.user):
        return HttpResponseForbidden()
    last_post = topic.last_post

    update_topic_on_view.delay(user_id=request.user.id,
                               topic_id=topic.id,
                               is_authenticated=user_is_authenticated)

    # without specifying, following query wouldn't select related properly
    posts = topic.posts.select_related(
        'user__userprofile', 'user__forum_profile', 'updated_by', 'user',
        'poststatus').prefetch_related('user__groups').all()
    edit_start = timezone.now() - timedelta(minutes=1)
    edit_end = timezone.now()
    editable = posts.filter(created__range=(edit_start, edit_end)).filter(
        user_id=request.user.id)
    can_edit = request.user.has_perm('djangobb_forum.change_post')
    try:
        page_url_parameter = int(request.GET.get('page') or 1)
    except:
        page_url_parameter = 1
    first_post_number = int(
        forum_settings.TOPIC_PAGE_SIZE) * (page_url_parameter - 1)
    can_close = can_close_topic(request.user, topic)

    moderator = request.user.is_superuser or request.user in topic.forum.moderators.all(
    )
    if user_is_authenticated and request.user in topic.subscribers.all():
        subscribed = True
    else:
        subscribed = False

    # reply form
    reply_form = None
    form_url = None
    back_url = None
    if user_is_authenticated and (not topic.closed or moderator):
        form_url = request.path + '?' + request.META[
            'QUERY_STRING'] + '#reply'  # if form validation failed: browser should scroll down to reply form ;)
        back_url = request.path
        ip = get_client_ip(request)
        post_form_kwargs = {
            "topic": topic,
            "user": request.user,
            "ip": ip,
            'is_ip_banned': request.is_ip_banned,
            "request_data": request.META,
            "url": "http://scratch.mit.edu%s" % back_url,
        }
        if post_request and AddPostForm.FORM_NAME in request.POST:

            reply_form = AddPostForm(request.POST, request.FILES,
                                     **post_form_kwargs)
            if reply_form.is_valid():
                post = reply_form.save()
                messages.success(request, _("Reply saved."))
                return HttpResponseRedirect(
                    post.get_absolute_url() if full else post.get_mobile_url())
        else:
            reply_form = AddPostForm(initial={
                'markup': request.user.forum_profile.markup,
                'subscribe': False,
            },
                                     **post_form_kwargs)

    group_titles = {}

    for post in posts:

        if post.user.is_superuser:
            group_titles[post.user] = "Scratch Team"

        else:
            temp_names = [group.name for group in post.user.groups.all()]
            if "Forum Moderators" in temp_names:
                group_titles[post.user] = "Forum Moderator"
            elif "Scratchers" in temp_names:
                group_titles[post.user] = "Scratcher"
            elif "New Scratchers" in temp_names:
                group_titles[post.user] = "New to Scratch"
            else:
                group_titles[post.user] = "Ungrouped"

    # handle poll, if exists
    poll_form = None
    polls = topic.poll_set.all()
    if not polls:
        poll = None
    else:
        poll = polls[0]
        if user_is_authenticated:  # Only logged in users can vote
            poll.auto_deactivate()
            has_voted = request.user in poll.users.all()
            if not post_request or not VotePollForm.FORM_NAME in request.POST:
                # It's not a POST request or: The reply form was send and not a poll vote
                if poll.active and not has_voted:
                    poll_form = VotePollForm(poll)
            else:
                if not poll.active:
                    messages.error(request, _("This poll is not active."))
                    return HttpResponseRedirect(topic.get_absolute_url())
                elif has_voted:
                    messages.error(request,
                                   _("You already voted on this poll."))
                    return HttpResponseRedirect(topic.get_absolute_url())

                poll_form = VotePollForm(poll, request.POST)
                if poll_form.is_valid():
                    ids = poll_form.cleaned_data["choice"]
                    queryset = poll.choices.filter(id__in=ids)
                    queryset.update(votes=F('votes') + 1)
                    poll.users.add(
                        request.user)  # save that this user has vote
                    messages.success(request, _("Vote saved."))
                    return HttpResponseRedirect(topic.get_absolute_url())

    highlight_word = request.GET.get('hl', '')
    if full:
        return render(
            request, 'djangobb_forum/topic.html', {
                'categories': Category.objects.all(),
                'topic': topic,
                'last_post': last_post,
                'form_url': form_url,
                'reply_form': reply_form,
                'back_url': back_url,
                'moderator': moderator,
                'subscribed': subscribed,
                'posts': posts,
                'first_post_number': first_post_number,
                'highlight_word': highlight_word,
                'poll': poll,
                'poll_form': poll_form,
                'editable': editable,
                'can_edit': can_edit,
                'can_close': can_close,
                'group_titles': group_titles,
                'simple_user_agent': simple_user_agent(request),
            })
    else:
        return render(
            request, 'djangobb_forum/mobile/topic.html', {
                'categories': Category.objects.all(),
                'topic': topic,
                'posts': posts,
                'poll': poll,
                'poll_form': poll_form,
                'reply_form': reply_form,
            })
Example #17
0
def show_topic(request, topic_id, full=True):
    """
    * Display a topic
    * save a reply
    * save a poll vote

    TODO: Add reply in lofi mode
    """
    post_request = request.method == "POST"
    user_is_authenticated = request.user.is_authenticated()
    if post_request and not user_is_authenticated:
        # Info: only user that are logged in should get forms in the page.
        raise PermissionDenied

    topic = get_object_or_404(Topic.objects.select_related(), pk=topic_id)
    if not topic.forum.category.has_access(request.user):
        raise PermissionDenied
    Topic.objects.filter(pk=topic.id).update(views=F('views') + 1)

    last_post = topic.last_post

    if request.user.is_authenticated():
        topic.update_read(request.user)
    posts = topic.posts.all().select_related()

    moderator = request.user.is_superuser or request.user in topic.forum.moderators.all()
    if user_is_authenticated and request.user in topic.subscribers.all():
        subscribed = True
    else:
        subscribed = False

    # reply form
    reply_form = None
    form_url = None
    back_url = None
    if user_is_authenticated and not topic.closed:
        form_url = request.path + "#reply" # if form validation failed: browser should scroll down to reply form ;)
        back_url = request.path
        ip = request.META.get('REMOTE_ADDR', None)
        post_form_kwargs = {"topic":topic, "user":request.user, "ip":ip}
        if post_request and AddPostForm.FORM_NAME in request.POST:
            reply_form = AddPostForm(request.POST, request.FILES, **post_form_kwargs)
            if reply_form.is_valid():
                post = reply_form.save()
                messages.success(request, _("Your reply saved."))
                return HttpResponseRedirect(post.get_absolute_url())
        else:
            reply_form = AddPostForm(
                initial={
                    'markup': request.user.forum_profile.markup,
                    'subscribe': request.user.forum_profile.auto_subscribe,
                },
                **post_form_kwargs
            )

    # handle poll, if exists
    poll_form = None
    polls = topic.poll_set.all()
    if not polls:
        poll = None
    else:
        poll = polls[0]
        if user_is_authenticated: # Only logged in users can vote
            poll.deactivate_if_expired()
            has_voted = request.user in poll.users.all()
            if not post_request or not VotePollForm.FORM_NAME in request.POST:
                # It's not a POST request or: The reply form was send and not a poll vote
                if poll.active and not has_voted:
                    poll_form = VotePollForm(poll)
            else:
                if not poll.active:
                    messages.error(request, _("This poll is not active!"))
                    return HttpResponseRedirect(topic.get_absolute_url())
                elif has_voted:
                    messages.error(request, _("You have already vote to this poll in the past!"))
                    return HttpResponseRedirect(topic.get_absolute_url())

                poll_form = VotePollForm(poll, request.POST)
                if poll_form.is_valid():
                    ids = poll_form.cleaned_data["choice"]
                    queryset = poll.choices.filter(id__in=ids)
                    queryset.update(votes=F('votes') + 1)
                    poll.users.add(request.user) # save that this user has vote
                    messages.success(request, _("Your votes are saved."))
                    return HttpResponseRedirect(topic.get_absolute_url())

    highlight_word = request.GET.get('hl', '')
    if full:
        return render(request, 'djangobb_forum/topic.html', {'categories': Category.objects.all(),
                'topic': topic,
                'last_post': last_post,
                'form_url': form_url,
                'reply_form': reply_form,
                'back_url': back_url,
                'moderator': moderator,
                'subscribed': subscribed,
                'posts': posts,
                'highlight_word': highlight_word,
                'poll': poll,
                'poll_form': poll_form,
                })
    else:
        return render(request, 'djangobb_forum/lofi/topic.html', {'categories': Category.objects.all(),
                'topic': topic,
                'posts': posts,
                'poll': poll,
                'poll_form': poll_form,
                })
Example #18
0
def add_topic(request, forum_id):
    """
    create a new topic, with or without poll
    """
    forum = get_object_or_404(Forum, pk=forum_id)
    if not forum.category.has_access(request.user):
        raise PermissionDenied

    ip = request.META.get('REMOTE_ADDR', None)

    contest = True if 'contest' in request.GET else False
    id = request.GET.get('id')
    if contest and id != '':
        try:
            ban = bans.Ban.objects.get(bid=request.GET.get('id'))
        except bans.Ban.DoesNotExist:
            ban = False
            messages.error(request, "No ban with this ID found.")
    else:
        ban = False
    post_form_kwargs = {
        "forum": forum,
        "user": request.user,
        "ip": ip,
        'contest': contest
    }

    poll_form = None
    if request.method == 'POST':
        form = AddPostForm(request.POST, request.FILES, **post_form_kwargs)
        if form.is_valid():
            all_valid = True
        else:
            all_valid = False

        if forum_settings.ENABLE_POLLS:
            poll_form = PollForm(request.POST)
            if not poll_form.has_data():
                # All poll fields are empty: User didn't want to create a poll
                # Don't run validation and remove all form error messages
                poll_form = PollForm()  # create clean form without form errors
            elif not poll_form.is_valid():
                all_valid = False

        if all_valid:
            post = form.save()
            if poll_form and poll_form.has_data():
                poll_form.save(post)
                messages.success(request, _("Topic with poll saved."))
            else:
                messages.success(request, _("Topic saved."))
            return HttpResponseRedirect(post.get_absolute_url())
    else:
        form = AddPostForm(initial={
            'contest':
            True if 'contest' in request.GET else False,
            'markup':
            request.user.forum_profile.markup,
            'subscribe':
            request.user.forum_profile.auto_subscribe,
        },
                           **post_form_kwargs)
        if forum_settings.ENABLE_POLLS and forum_id:  # Create a new topic
            poll_form = PollForm()

    context = {
        'contest': True if 'contest' in request.GET else False,
        'forum': forum,
        'create_poll_form': poll_form,
        'form': form,
        'form_url': request.path,
        'back_url': forum.get_absolute_url(),
        'ban': ban,
    }
    if contest:
        messages.warning(
            request,
            "Please complete the template below to submit your ban appeal to the forums.\n\
         Any alteration of the template will get your request denied and locked. You may attach your proof to the post \
        or link to Youtube for video proof. Links to other external sites will get your appeal denied and locked."
        )
    return render(request, 'djangobb_forum/add_topic.html', context)