Beispiel #1
0
    def process_request(self, request):
        if is_authenticated(request.user):
            try:
                # Here we try to load profile, but can get error
                # if user created during syncdb but profile model
                # under south control. (Like pybb.Profile).
                profile = util.get_pybb_profile(request.user)
            except ObjectDoesNotExist:
                # Ok, we should create new profile for this user
                # and grant permissions for add posts
                # It should be caused rarely, so we move import signal here
                # to prevent circular import
                from pybb.signals import user_saved
                user_saved(request.user, created=True)
                profile = util.get_pybb_profile(request.user)

            if not profile.language:
                profile.language = translation.get_language_from_request(
                    request)
                profile.save()

            request.session['django_language'] = profile.language
            # translation.activate(profile.language)
            translation.activate('en')
            request.LANGUAGE_CODE = translation.get_language()
Beispiel #2
0
def pybb_topic_unread(topics, user):
    """
    Mark all topics in queryset/list with .unread for target user
    """
    topic_list = list(topics)

    if is_authenticated(user):
        for topic in topic_list:
            topic.unread = True

        forums_ids = [f.forum_id for f in topic_list]
        forum_marks = dict([(m.forum_id, m.time_stamp)
                            for m
                            in ForumReadTracker.objects.filter(user=user, forum__in=forums_ids)])
        if len(forum_marks):
            for topic in topic_list:
                topic_updated = topic.updated or topic.created
                if topic.forum.id in forum_marks and topic_updated <= forum_marks[topic.forum.id]:
                    topic.unread = False

        qs = TopicReadTracker.objects.filter(user=user, topic__in=topic_list).select_related('topic')
        topic_marks = list(qs)
        topic_dict = dict(((topic.id, topic) for topic in topic_list))
        for mark in topic_marks:
            if topic_dict[mark.topic.id].updated <= mark.time_stamp:
                topic_dict[mark.topic.id].unread = False
    return topic_list
Beispiel #3
0
    def get_context_data(self, **kwargs):
        ctx = super(TopicView, self).get_context_data(**kwargs)

        if is_authenticated(self.request.user):
            self.request.user.is_moderator = perms.may_moderate_topic(self.request.user, self.topic)
            self.request.user.is_subscribed = self.request.user in self.topic.subscribers.all()
            if defaults.PYBB_ENABLE_ADMIN_POST_FORM and \
                    perms.may_post_as_admin(self.request.user):
                ctx['form'] = self.get_admin_post_form_class()(
                    initial={'login': getattr(self.request.user, username_field)},
                    topic=self.topic)
            else:
                ctx['form'] = self.get_post_form_class()(topic=self.topic)
        elif defaults.PYBB_ENABLE_ANONYMOUS_POST:
            ctx['form'] = self.get_post_form_class()(topic=self.topic)
        else:
            ctx['form'] = None
            ctx['next'] = self.get_login_redirect_url()
        if perms.may_attach_files(self.request.user):
            aformset = self.get_attachment_formset_class()()
            ctx['aformset'] = aformset
            ctx['attachment_max_size'] = defaults.PYBB_ATTACHMENT_SIZE_LIMIT
        if defaults.PYBB_FREEZE_FIRST_POST:
            ctx['first_post'] = self.topic.head
        else:
            ctx['first_post'] = None
        ctx['topic'] = self.topic

        if perms.may_vote_in_topic(self.request.user, self.topic) and \
                pybb_topic_poll_not_voted(self.topic, self.request.user):
            ctx['poll_form'] = self.get_poll_form_class()(self.topic)

        return ctx
Beispiel #4
0
    def get_context_data(self, **kwargs):
        ctx = super(TopicView, self).get_context_data(**kwargs)

        if is_authenticated(self.request.user):
            self.request.user.is_moderator = perms.may_moderate_topic(
                self.request.user, self.topic)
            if defaults.PYBB_ENABLE_ADMIN_POST_FORM and \
                    perms.may_post_as_admin(self.request.user):
                ctx['form'] = self.get_admin_post_form_class()(
                    initial={
                        'login': getattr(self.request.user, username_field)
                    },
                    topic=self.topic)
            else:
                ctx['form'] = self.get_post_form_class()(topic=self.topic)
        elif defaults.PYBB_ENABLE_ANONYMOUS_POST:
            ctx['form'] = self.get_post_form_class()(topic=self.topic)
        else:
            ctx['form'] = None
            ctx['next'] = self.get_login_redirect_url()
        if perms.may_attach_files(self.request.user):
            aformset = self.get_attachment_formset_class()()
            ctx['aformset'] = aformset
            ctx['attachment_max_size'] = defaults.PYBB_ATTACHMENT_SIZE_LIMIT
        if defaults.PYBB_FREEZE_FIRST_POST:
            ctx['first_post'] = self.topic.head
        else:
            ctx['first_post'] = None
        ctx['topic'] = self.topic

        if perms.may_vote_in_topic(self.request.user, self.topic) and \
                pybb_topic_poll_not_voted(self.topic, self.request.user):
            ctx['poll_form'] = self.get_poll_form_class()(self.topic)

        return ctx
Beispiel #5
0
    def dispatch(self, request, *args, **kwargs):
        self.topic = self.get_topic(**kwargs)

        if request.GET.get('first-unread'):
            if is_authenticated(request.user):
                read_dates = []
                try:
                    read_dates.append(
                        TopicReadTracker.objects.get(
                            user=request.user, topic=self.topic).time_stamp)
                except TopicReadTracker.DoesNotExist:
                    pass
                try:
                    read_dates.append(
                        ForumReadTracker.objects.get(
                            user=request.user,
                            forum=self.topic.forum).time_stamp)
                except ForumReadTracker.DoesNotExist:
                    pass

                read_date = read_dates and max(read_dates)
                if read_date:
                    try:
                        first_unread_topic = self.topic.posts.filter(
                            created__gt=read_date).order_by('created', 'id')[0]
                    except IndexError:
                        first_unread_topic = self.topic.last_post
                else:
                    first_unread_topic = self.topic.head
                return HttpResponseRedirect(
                    reverse('pybb:post', kwargs={'pk': first_unread_topic.id}))

        return super(TopicView, self).dispatch(request, *args, **kwargs)
Beispiel #6
0
def pybb_user_time(context_time, user):
    delta = tznow() - context_time
    today = tznow().replace(hour=0, minute=0, second=0)
    yesterday = today - timedelta(days=1)
    tomorrow = today + timedelta(days=1)

    if delta.days == 0:
        if delta.seconds < 60:
            msg = ungettext('%d second ago', '%d seconds ago', delta.seconds)
            return msg % delta.seconds
        elif delta.seconds < 3600:
            minutes = int(delta.seconds / 60)
            msg = ungettext('%d minute ago', '%d minutes ago', minutes)
            return msg % minutes
    if is_authenticated(user):
        if time.daylight: # pragma: no cover
            tz1 = time.altzone
        else: # pragma: no cover
            tz1 = time.timezone
        tz = tz1 + util.get_pybb_profile(user).time_zone * 60 * 60
        context_time = context_time + timedelta(seconds=tz)
    if today < context_time < tomorrow:
        return _('today, %s') % context_time.strftime('%H:%M')
    elif yesterday < context_time < today:
        return _('yesterday, %s') % context_time.strftime('%H:%M')
    else:
        return dateformat.format(context_time, 'd M, Y H:i')
Beispiel #7
0
def pybb_user_time(context_time, user):
    delta = tznow() - context_time
    today = tznow().replace(hour=0, minute=0, second=0)
    yesterday = today - timedelta(days=1)
    tomorrow = today + timedelta(days=1)

    if delta.days == 0:
        if delta.seconds < 60:
            msg = ungettext('%d second ago', '%d seconds ago', delta.seconds)
            return msg % delta.seconds
        elif delta.seconds < 3600:
            minutes = int(delta.seconds / 60)
            msg = ungettext('%d minute ago', '%d minutes ago', minutes)
            return msg % minutes
    if is_authenticated(user):
        if time.daylight:  # pragma: no cover
            tz1 = time.altzone
        else:  # pragma: no cover
            tz1 = time.timezone
        tz = tz1 + util.get_pybb_profile(user).time_zone * 60 * 60
        context_time = context_time + timedelta(seconds=tz)
    if today < context_time < tomorrow:
        return _('today, %s') % context_time.strftime('%H:%M')
    elif yesterday < context_time < today:
        return _('yesterday, %s') % context_time.strftime('%H:%M')
    else:
        return dateformat.format(context_time, 'd M, Y H:i')
Beispiel #8
0
def pybb_topic_unread(topics, user):
    """
    Mark all topics in queryset/list with .unread for target user
    """
    topic_list = list(topics)

    if is_authenticated(user):
        for topic in topic_list:
            topic.unread = True

        forums_ids = [f.forum_id for f in topic_list]
        forum_marks = dict([(m.forum_id, m.time_stamp)
                            for m in ForumReadTracker.objects.filter(
                                user=user, forum__in=forums_ids)])
        if len(forum_marks):
            for topic in topic_list:
                topic_updated = topic.updated or topic.created
                if topic.forum.id in forum_marks and topic_updated <= forum_marks[
                        topic.forum.id]:
                    topic.unread = False

        qs = TopicReadTracker.objects.filter(
            user=user, topic__in=topic_list).select_related('topic')
        topic_marks = list(qs)
        topic_dict = dict(((topic.id, topic) for topic in topic_list))
        for mark in topic_marks:
            if topic_dict[mark.topic.id].updated <= mark.time_stamp:
                topic_dict[mark.topic.id].unread = False
    return topic_list
Beispiel #9
0
 def may_moderate_topic(self, user, topic):
     if user.is_superuser:
         return True
     if not is_authenticated(user):
         return False
     return user.has_perm(
         'pybb.change_topic') or user in topic.forum.moderators.all()
Beispiel #10
0
    def mark_read(self):
        if not is_authenticated(self.request.user):
            return
        try:
            forum_mark = ForumReadTracker.objects.get(forum=self.topic.forum,
                                                      user=self.request.user)
        except ForumReadTracker.DoesNotExist:
            forum_mark = None
        if (forum_mark is None) or (forum_mark.time_stamp <
                                    self.topic.updated):
            topic_mark, new = TopicReadTracker.objects.get_or_create_tracker(
                topic=self.topic, user=self.request.user)
            if not new and topic_mark.time_stamp > self.topic.updated:
                # Bail early if we already read this thread.
                return

            # Check, if there are any unread topics in forum
            readed_trackers = TopicReadTracker.objects.filter(
                user=self.request.user,
                topic__forum=self.topic.forum,
                time_stamp__gte=F('topic__updated'))
            unread = self.topic.forum.topics.exclude(
                topicreadtracker__in=readed_trackers)
            if forum_mark is not None:
                unread = unread.filter(updated__gte=forum_mark.time_stamp)

            if not unread.exists():
                # Clear all topic marks for this forum, mark forum as read
                TopicReadTracker.objects.filter(
                    user=self.request.user,
                    topic__forum=self.topic.forum).delete()
                forum_mark, new = ForumReadTracker.objects.get_or_create_tracker(
                    forum=self.topic.forum, user=self.request.user)
                forum_mark.save()
Beispiel #11
0
    def mark_read(self):
        if not is_authenticated(self.request.user):
            return
        try:
            forum_mark = ForumReadTracker.objects.get(forum=self.topic.forum, user=self.request.user)
        except ForumReadTracker.DoesNotExist:
            forum_mark = None
        if (forum_mark is None) or (forum_mark.time_stamp <= self.topic.updated):
            topic_mark, topic_mark_new = TopicReadTracker.objects.get_or_create_tracker(topic=self.topic, user=self.request.user)
            if not topic_mark_new:
                # Bail early if we already read this thread.
                if topic_mark.time_stamp >= self.topic.updated:
                    return
                topic_mark.save()  # update read time

            # Check, if there are any unread topics in forum
            readed_trackers = TopicReadTracker.objects.filter(
                user=self.request.user, topic__forum=self.topic.forum, time_stamp__gte=F('topic__updated'))
            unread = self.topic.forum.topics.exclude(topicreadtracker__in=readed_trackers)
            if forum_mark is not None:
                unread = unread.filter(updated__gte=forum_mark.time_stamp)

            if not unread.exists():
                # Clear all topic marks for this forum, mark forum as read
                TopicReadTracker.objects.filter(user=self.request.user, topic__forum=self.topic.forum).delete()
                forum_mark, forum_mark_new = ForumReadTracker.objects.get_or_create_tracker(
                    forum=self.topic.forum, user=self.request.user)
                if not forum_mark_new:
                    forum_mark.save()  # update read time
Beispiel #12
0
    def dispatch(self, request, *args, **kwargs):
        self.topic = self.get_topic(**kwargs)

        if request.GET.get('first-unread'):
            if is_authenticated(request.user):
                read_dates = []
                try:
                    read_dates.append(TopicReadTracker.objects.get(user=request.user, topic=self.topic).time_stamp)
                except TopicReadTracker.DoesNotExist:
                    pass
                try:
                    read_dates.append(ForumReadTracker.objects.get(user=request.user, forum=self.topic.forum).time_stamp)
                except ForumReadTracker.DoesNotExist:
                    pass

                read_date = read_dates and max(read_dates)
                if read_date:
                    try:
                        first_unread_topic = self.topic.posts.filter(created__gt=read_date).order_by('created', 'id')[0]
                    except IndexError:
                        first_unread_topic = self.topic.last_post
                else:
                    first_unread_topic = self.topic.head
                return HttpResponseRedirect(reverse('pybb:post', kwargs={'pk': first_unread_topic.id}))

        return super(TopicView, self).dispatch(request, *args, **kwargs)
Beispiel #13
0
 def may_delete_post(self, user, post):
     """ return True if `user` may delete `post` """
     if user.is_superuser:
         return True
     if not is_authenticated(user):
         return False
     return (defaults.PYBB_ALLOW_DELETE_OWN_POST and post.user == user) or \
            user.has_perm('pybb.delete_post') or \
            user in post.topic.forum.moderators.all()
Beispiel #14
0
 def may_delete_post(self, user, post):
     """ return True if `user` may delete `post` """
     if user.is_superuser:
         return True
     if not is_authenticated(user):
         return False
     return (defaults.PYBB_ALLOW_DELETE_OWN_POST and post.user == user) or \
            user.has_perm('pybb.delete_post') or \
            user in post.topic.forum.moderators.all()
Beispiel #15
0
 def may_vote_in_topic(self, user, topic):
     """ return True if `user` may unstick `topic` """
     if topic.poll_type == topic.POLL_TYPE_NONE or not is_authenticated(user):
         return False
     elif user.is_superuser:
         return True
     elif not topic.closed and not user.poll_answers.filter(poll_answer__topic=topic).exists():
         return True
     return False
Beispiel #16
0
 def dispatch(self, request, *args, **kwargs):
     try:
         return super(RedirectToLoginMixin, self).dispatch(request, *args, **kwargs)
     except PermissionDenied:
         if not is_authenticated(request.user):
             from django.contrib.auth.views import redirect_to_login
             return redirect_to_login(self.get_login_redirect_url())
         else:
             return HttpResponseForbidden()
Beispiel #17
0
 def get_objects(self):
     if not is_authenticated(self.request.user):
         raise PermissionDenied
     self.forum = get_object_or_404(Forum.objects.all(),
                                    pk=self.kwargs['pk'])
     try:
         self.forum_subscription = ForumSubscription.objects.get(
             user=self.request.user, forum=self.forum)
     except ForumSubscription.DoesNotExist:
         self.forum_subscription = None
Beispiel #18
0
 def dispatch(self, request, *args, **kwargs):
     try:
         return super(RedirectToLoginMixin,
                      self).dispatch(request, *args, **kwargs)
     except PermissionDenied:
         if not is_authenticated(request.user):
             from django.contrib.auth.views import redirect_to_login
             return redirect_to_login(self.get_login_redirect_url())
         else:
             return HttpResponseForbidden()
Beispiel #19
0
 def get_objects(self):
     if not is_authenticated(self.request.user):
         raise PermissionDenied
     self.forum = get_object_or_404(Forum.objects.all(), pk=self.kwargs['pk'])
     try:
         self.forum_subscription = ForumSubscription.objects.get(
             user=self.request.user,
             forum=self.forum
         )
     except ForumSubscription.DoesNotExist:
         self.forum_subscription = None
Beispiel #20
0
 def may_vote_in_topic(self, user, topic):
     """ return True if `user` may unstick `topic` """
     if topic.poll_type == topic.POLL_TYPE_NONE or not is_authenticated(
             user):
         return False
     elif user.is_superuser:
         return True
     elif not topic.closed and not user.poll_answers.filter(
             poll_answer__topic=topic).exists():
         return True
     return False
Beispiel #21
0
def pybb_is_topic_unread(topic, user):
    if not is_authenticated(user):
        return False

    last_topic_update = topic.updated or topic.created

    unread = not ForumReadTracker.objects.filter(
        forum=topic.forum, user=user.id,
        time_stamp__gte=last_topic_update).exists()
    unread &= not TopicReadTracker.objects.filter(
        topic=topic, user=user.id, time_stamp__gte=last_topic_update).exists()
    return unread
Beispiel #22
0
def get_pybb_profile(user):
    from pybb import defaults

    if not is_authenticated(user):
        if defaults.PYBB_ENABLE_ANONYMOUS_POST:
            user = get_user_model().objects.get(**{get_username_field(): defaults.PYBB_ANONYMOUS_USERNAME})
        else:
            raise ValueError(_('Can\'t get profile for anonymous user'))

    if defaults.PYBB_PROFILE_RELATED_NAME:
        return getattr(user, defaults.PYBB_PROFILE_RELATED_NAME)
    else:
        return user
Beispiel #23
0
    def may_create_post(self, user, topic):
        """ return True if `user` is allowed to create a new post in `topic` """

        if user.is_superuser:
            return True
        if not defaults.PYBB_ENABLE_ANONYMOUS_POST and not is_authenticated(user):
            return False
        if not self.may_view_topic(user, topic):
            return False
        if not user.has_perm('pybb.add_post'):
            return False
        if topic.closed or topic.on_moderation:
            return self.may_moderate_topic(user, topic)
        return True
Beispiel #24
0
def get_pybb_profile(user):
    from pybb import defaults

    if not is_authenticated(user):
        if defaults.PYBB_ENABLE_ANONYMOUS_POST:
            user = get_user_model().objects.get(
                **{get_username_field(): defaults.PYBB_ANONYMOUS_USERNAME})
        else:
            raise ValueError(_('Can\'t get profile for anonymous user'))

    if defaults.PYBB_PROFILE_RELATED_NAME:
        return getattr(user, defaults.PYBB_PROFILE_RELATED_NAME)
    else:
        return user
Beispiel #25
0
 def get_context_data(self, **kwargs):
     ctx = super(ForumView, self).get_context_data(**kwargs)
     ctx['forum'] = self.forum
     if is_authenticated(self.request.user):
         try:
             ctx['subscription'] = ForumSubscription.objects.get(
                 user=self.request.user, forum=self.forum)
         except ForumSubscription.DoesNotExist:
             ctx['subscription'] = None
     else:
         ctx['subscription'] = None
     ctx['forum'].forums_accessed = perms.filter_forums(
         self.request.user, self.forum.child_forums.all())
     return ctx
Beispiel #26
0
def pybb_is_topic_unread(topic, user):
    if not is_authenticated(user):
        return False

    last_topic_update = topic.updated or topic.created

    unread = not ForumReadTracker.objects.filter(
        forum=topic.forum,
        user=user.id,
        time_stamp__gte=last_topic_update).exists()
    unread &= not TopicReadTracker.objects.filter(
        topic=topic,
        user=user.id,
        time_stamp__gte=last_topic_update).exists()
    return unread
Beispiel #27
0
    def may_create_post(self, user, topic):
        """ return True if `user` is allowed to create a new post in `topic` """

        if user.is_superuser:
            return True
        if not defaults.PYBB_ENABLE_ANONYMOUS_POST and not is_authenticated(
                user):
            return False
        if not self.may_view_topic(user, topic):
            return False
        if not user.has_perm('pybb.add_post'):
            return False
        if topic.closed or topic.on_moderation:
            return self.may_moderate_topic(user, topic)
        return True
Beispiel #28
0
 def get_context_data(self, **kwargs):
     ctx = super(ForumView, self).get_context_data(**kwargs)
     ctx['forum'] = self.forum
     if is_authenticated(self.request.user):
         try:
             ctx['subscription'] = ForumSubscription.objects.get(
                 user=self.request.user,
                 forum=self.forum
             )
         except ForumSubscription.DoesNotExist:
             ctx['subscription'] = None
     else:
         ctx['subscription'] = None
     ctx['forum'].forums_accessed = perms.filter_forums(self.request.user, self.forum.child_forums.all())
     return ctx
Beispiel #29
0
 def get_queryset(self):
     if not perms.may_view_topic(self.request.user, self.topic):
         raise PermissionDenied
     if is_authenticated(self.request.user) or not defaults.PYBB_ANONYMOUS_VIEWS_CACHE_BUFFER:
         Topic.objects.filter(id=self.topic.id).update(views=F('views') + 1)
     else:
         cache_key = util.build_cache_key('anonymous_topic_views', topic_id=self.topic.id)
         cache.add(cache_key, 0)
         if cache.incr(cache_key) % defaults.PYBB_ANONYMOUS_VIEWS_CACHE_BUFFER == 0:
             Topic.objects.filter(id=self.topic.id).update(views=F('views') +
                                                             defaults.PYBB_ANONYMOUS_VIEWS_CACHE_BUFFER)
             cache.set(cache_key, 0)
     qs = self.topic.posts.all().select_related('user')
     if defaults.PYBB_PROFILE_RELATED_NAME:
         qs = qs.select_related('user__%s' % defaults.PYBB_PROFILE_RELATED_NAME)
     if not perms.may_moderate_topic(self.request.user, self.topic):
         qs = perms.filter_posts(self.request.user, qs)
     return qs
Beispiel #30
0
def pybb_forum_unread(forums, user):
    """
    Check if forum has unread messages.
    """
    forum_list = list(forums)
    if is_authenticated(user):
        for forum in forum_list:
            forum.unread = forum.topic_count > 0
        forum_marks = ForumReadTracker.objects.filter(
            user=user, forum__in=forum_list).select_related('forum')
        forum_dict = dict(((forum.id, forum) for forum in forum_list))
        for mark in forum_marks:
            curr_forum = forum_dict[mark.forum.id]
            if (curr_forum.updated is None) or (curr_forum.updated <=
                                                mark.time_stamp):
                if not any((f.unread for f in pybb_forum_unread(
                        curr_forum.child_forums.all(), user))):
                    forum_dict[mark.forum.id].unread = False
    return forum_list
Beispiel #31
0
def pybb_forum_unread(forums, user):
    """
    Check if forum has unread messages.
    """
    forum_list = list(forums)
    if is_authenticated(user):
        for forum in forum_list:
            forum.unread = forum.topic_count > 0
        forum_marks = ForumReadTracker.objects.filter(
            user=user,
            forum__in=forum_list
        ).select_related('forum')
        forum_dict = dict(((forum.id, forum) for forum in forum_list))
        for mark in forum_marks:
            curr_forum = forum_dict[mark.forum.id]
            if (curr_forum.updated is None) or (curr_forum.updated <= mark.time_stamp):
                if not any((f.unread for f in pybb_forum_unread(curr_forum.child_forums.all(), user))):
                    forum_dict[mark.forum.id].unread = False
    return forum_list
Beispiel #32
0
    def dispatch(self, request, *args, **kwargs):
        if is_authenticated(request.user):
            self.user = request.user
        else:
            if defaults.PYBB_ENABLE_ANONYMOUS_POST:
                self.user, new = User.objects.get_or_create(
                    **{username_field: defaults.PYBB_ANONYMOUS_USERNAME})
            else:
                from django.contrib.auth.views import redirect_to_login
                return redirect_to_login(request.get_full_path())

        self.forum = None
        self.topic = None
        if 'forum_id' in kwargs:
            self.forum = get_object_or_404(perms.filter_forums(
                request.user, Forum.objects.all()),
                                           pk=kwargs['forum_id'])
            if not perms.may_create_topic(self.user, self.forum):
                raise PermissionDenied
        elif 'topic_id' in kwargs:
            self.topic = get_object_or_404(perms.filter_topics(
                request.user, Topic.objects.all()),
                                           pk=kwargs['topic_id'])
            if not perms.may_create_post(self.user, self.topic):
                raise PermissionDenied

            self.quote = ''
            if 'quote_id' in request.GET:
                try:
                    quote_id = int(request.GET.get('quote_id'))
                except TypeError:
                    raise Http404
                else:
                    post = get_object_or_404(Post, pk=quote_id)
                    if not perms.may_view_post(request.user, post):
                        raise PermissionDenied
                    profile = util.get_pybb_profile(post.user)
                    self.quote = util._get_markup_quoter(defaults.PYBB_MARKUP)(
                        post.body, profile.get_display_name())

                if self.quote and request.is_ajax():
                    return HttpResponse(self.quote)
        return super(AddPostView, self).dispatch(request, *args, **kwargs)
Beispiel #33
0
    def filter_posts(self, user, qs):
        """ return a queryset with posts `user` is allowed to see """

        # first filter by topic availability
        if user.is_superuser:
            return qs
        if user.has_perm('pybb.change_post'):
            # If I can edit all posts, I can view all posts
            return qs
        if not user.is_staff:
            # remove hidden forum/cats posts
            query = Q(topic__forum__hidden=False, topic__forum__category__hidden=False)
        else:
            query = Q(pk__isnull=False)
        if defaults.PYBB_PREMODERATION:
            # remove moderated posts
            query = query & Q(on_moderation=False, topic__on_moderation=False)
        if is_authenticated(user):
            # cancel previous remove if it's my post, or if I'm moderator of the forum
            query = query | Q(user=user) | Q(topic__forum__moderators=user)
        return qs.filter(query).distinct()
Beispiel #34
0
    def filter_posts(self, user, qs):
        """ return a queryset with posts `user` is allowed to see """

        # first filter by topic availability
        if user.is_superuser:
            return qs
        if user.has_perm('pybb.change_post'):
            # If I can edit all posts, I can view all posts
            return qs
        if not user.is_staff:
            # remove hidden forum/cats posts
            query = Q(topic__forum__hidden=False,
                      topic__forum__category__hidden=False)
        else:
            query = Q(pk__isnull=False)
        if defaults.PYBB_PREMODERATION:
            # remove moderated posts
            query = query & Q(on_moderation=False, topic__on_moderation=False)
        if is_authenticated(user):
            # cancel previous remove if it's my post, or if I'm moderator of the forum
            query = query | Q(user=user) | Q(topic__forum__moderators=user)
        return qs.filter(query).distinct()
Beispiel #35
0
    def process_request(self, request):
        if is_authenticated(request.user):
            try:
                # Here we try to load profile, but can get error
                # if user created during syncdb but profile model
                # under south control. (Like pybb.Profile).
                profile = util.get_pybb_profile(request.user)
            except ObjectDoesNotExist:
                # Ok, we should create new profile for this user
                # and grant permissions for add posts
                # It should be caused rarely, so we move import signal here
                # to prevent circular import
                from pybb.signals import user_saved
                user_saved(request.user, created=True)
                profile = util.get_pybb_profile(request.user)

            if not profile.language:
                profile.language = translation.get_language_from_request(request)
                profile.save()

            request.session['django_language'] = profile.language
            translation.activate(profile.language)
            request.LANGUAGE_CODE = translation.get_language()
Beispiel #36
0
    def dispatch(self, request, *args, **kwargs):
        if is_authenticated(request.user):
            self.user = request.user
        else:
            if defaults.PYBB_ENABLE_ANONYMOUS_POST:
                self.user, new = User.objects.get_or_create(**{username_field: defaults.PYBB_ANONYMOUS_USERNAME})
            else:
                from django.contrib.auth.views import redirect_to_login
                return redirect_to_login(request.get_full_path())

        self.forum = None
        self.topic = None
        if 'forum_id' in kwargs:
            self.forum = get_object_or_404(perms.filter_forums(request.user, Forum.objects.all()), pk=kwargs['forum_id'])
            if not perms.may_create_topic(self.user, self.forum):
                raise PermissionDenied
        elif 'topic_id' in kwargs:
            self.topic = get_object_or_404(perms.filter_topics(request.user, Topic.objects.all()), pk=kwargs['topic_id'])
            if not perms.may_create_post(self.user, self.topic):
                raise PermissionDenied

            self.quote = ''
            if 'quote_id' in request.GET:
                try:
                    quote_id = int(request.GET.get('quote_id'))
                except TypeError:
                    raise Http404
                else:
                    post = get_object_or_404(Post, pk=quote_id)
                    if not perms.may_view_post(request.user, post):
                        raise PermissionDenied
                    profile = util.get_pybb_profile(post.user)
                    self.quote = util._get_markup_quoter(defaults.PYBB_MARKUP)(post.body, profile.get_display_name())

                if self.quote and request.is_ajax():
                    return HttpResponse(self.quote)
        return super(AddPostView, self).dispatch(request, *args, **kwargs)
Beispiel #37
0
 def filter_topics(self, user, qs):
     """ return a queryset with topics `user` is allowed to see """
     if user.is_superuser:
         return qs
     if user.has_perm('pybb.change_topic'):
         # if I can edit, I can view
         return qs
     if not user.is_staff:
         # FIXME: is_staff only allow user to access /admin but does not mean user has extra
         # permissions on pybb models. We should add pybb perm test
         qs = qs.filter(Q(forum__hidden=False) & Q(forum__category__hidden=False))
     if is_authenticated(user):
         qs = qs.filter(
             # moderator can view on_moderation
             Q(forum__moderators=user) |
             # author can view on_moderation only if there is one post in the topic
             # (mean that post is owned by author)
             Q(user=user, post_count=1) |
             # posts not on_moderation are accessible
             Q(on_moderation=False)
         )
     else:
         qs = qs.filter(on_moderation=False)
     return qs.distinct()
Beispiel #38
0
 def get_queryset(self):
     if not perms.may_view_topic(self.request.user, self.topic):
         raise PermissionDenied
     if is_authenticated(
             self.request.user
     ) or not defaults.PYBB_ANONYMOUS_VIEWS_CACHE_BUFFER:
         Topic.objects.filter(id=self.topic.id).update(views=F('views') + 1)
     else:
         cache_key = util.build_cache_key('anonymous_topic_views',
                                          topic_id=self.topic.id)
         cache.add(cache_key, 0)
         if cache.incr(cache_key
                       ) % defaults.PYBB_ANONYMOUS_VIEWS_CACHE_BUFFER == 0:
             Topic.objects.filter(id=self.topic.id).update(
                 views=F('views') +
                 defaults.PYBB_ANONYMOUS_VIEWS_CACHE_BUFFER)
             cache.set(cache_key, 0)
     qs = self.topic.posts.all().select_related('user')
     if defaults.PYBB_PROFILE_RELATED_NAME:
         qs = qs.select_related('user__%s' %
                                defaults.PYBB_PROFILE_RELATED_NAME)
     if not perms.may_moderate_topic(self.request.user, self.topic):
         qs = perms.filter_posts(self.request.user, qs)
     return qs
Beispiel #39
0
 def filter_topics(self, user, qs):
     """ return a queryset with topics `user` is allowed to see """
     if user.is_superuser:
         return qs
     if user.has_perm('pybb.change_topic'):
         # if I can edit, I can view
         return qs
     if not user.is_staff:
         # FIXME: is_staff only allow user to access /admin but does not mean user has extra
         # permissions on pybb models. We should add pybb perm test
         qs = qs.filter(
             Q(forum__hidden=False) & Q(forum__category__hidden=False))
     if is_authenticated(user):
         qs = qs.filter(
             # moderator can view on_moderation
             Q(forum__moderators=user) |
             # author can view on_moderation only if there is one post in the topic
             # (mean that post is owned by author)
             Q(user=user, post_count=1) |
             # posts not on_moderation are accessible
             Q(on_moderation=False))
     else:
         qs = qs.filter(on_moderation=False)
     return qs.distinct()
Beispiel #40
0
 def may_moderate_topic(self, user, topic):
     if user.is_superuser:
         return True
     if not is_authenticated(user):
         return False
     return user.has_perm('pybb.change_topic') or user in topic.forum.moderators.all()
Beispiel #41
0
 def get_success_url(self):
     if (not is_authenticated(self.request.user)) and defaults.PYBB_PREMODERATION:
         return reverse('pybb:index')
     return self.object.get_absolute_url()
Beispiel #42
0
 def may_subscribe_topic(self, user, topic):
     """ return True if `user` is allowed to subscribe to a `topic` """
     return not defaults.PYBB_DISABLE_SUBSCRIPTIONS and is_authenticated(
         user)
Beispiel #43
0
 def get_success_url(self):
     if (not is_authenticated(
             self.request.user)) and defaults.PYBB_PREMODERATION:
         return reverse('pybb:index')
     return self.object.get_absolute_url()
Beispiel #44
0
 def may_subscribe_topic(self, user, topic):
     """ return True if `user` is allowed to subscribe to a `topic` """
     return not defaults.PYBB_DISABLE_SUBSCRIPTIONS and is_authenticated(user)