Exemple #1
0
def destroy_user(request, user, username):
    try:
        user = User.objects.get(pk=user)
    except User.DoesNotExist:
        return error404(request)

    if user.pk == request.user.pk:
        return error403(request, _("You can't destroy your own account."))

    try:
        request.acl.destroy_users.allow_destroy_user(user)
    except ACLError403 as e:
        return error403(request, unicode(e))

    forums_to_sync = []

    for thread in user.thread_set.iterator():
        if not thread.forum_id in forums_to_sync:
            forums_to_sync.append(thread.forum_id)
        thread.delete()

    if forums_to_sync:
        for forum in Forum.objects.filter(id__in=forums_to_sync).iterator():
            forum.sync()
            forum.save()

    user.post_set.update(deleted=True)
    user.delete()

    messages.success(request, _('User Account "%(username)s" has been destroyed.') % {'username': user.username})
    return redirect('users')
Exemple #2
0
 def decorator(*args, **kwargs):
     try:
         return f(*args, **kwargs)
     except ACLError403 as e:
         return error403(args[0], e)
     except ACLError404 as e:
         return error404(args[0], e)
Exemple #3
0
def signature(request):
    # Intercept all requests if we can't use signature
    if not request.acl.usercp.can_use_signature():
        return error403(request)
    if request.user.signature_ban:
        return request.theme.render_to_response('usercp/signature_banned.html',
                                                context_instance=RequestContext(request, {
                                                 'tab': 'signature',
                                                 }));

    siggy_text = ''
    message = request.messages.get_message('usercp_signature')
    if request.method == 'POST':
        form = SignatureForm(request.POST, request=request, initial={'signature': request.user.signature})
        if form.is_valid():
            request.user.signature = form.cleaned_data['signature']
            if request.user.signature:
                request.user.signature_preparsed = signature_markdown(request.acl,
                                                                      request.user.signature)
            else:
                request.user.signature_preparsed = None
            request.user.save(force_update=True)
            request.messages.set_flash(Message(_("Your signature has been changed.")), 'success', 'usercp_signature')
            return redirect(reverse('usercp_signature'))
        else:
            message = Message(form.non_field_errors()[0], 'error')
    else:
        form = SignatureForm(request=request, initial={'signature': request.user.signature})

    return request.theme.render_to_response('usercp/signature.html',
                                            context_instance=RequestContext(request, {
                                             'message': message,
                                             'tab': 'signature',
                                             'form': FormLayout(form),
                                             }));
Exemple #4
0
 def decorator(*args, **kwargs):
     request = args[0]
     if not request.csrf.request_secure(request):
         return error403(
             request,
             _("Request authorization is invalid. Please try again."))
     return f(*args, **kwargs)
Exemple #5
0
def signature(request):
    # Intercept all requests if we can't use signature
    if not request.acl.usercp.can_use_signature():
        return error403(request)
    if request.user.signature_ban:
        return render_to_response('usercp/signature_banned.html',
                                  context_instance=RequestContext(request, {
                                      'tab': 'signature'}));

    siggy_text = ''
    message = request.messages.get_message('usercp_signature')
    if request.method == 'POST':
        form = SignatureForm(request.POST, request=request, initial={'signature': request.user.signature})
        if form.is_valid():
            request.user.signature = form.cleaned_data['signature']
            if request.user.signature:
                request.user.signature_preparsed = signature_markdown(request.acl,
                                                                      request.user.signature)
            else:
                request.user.signature_preparsed = None
            request.user.save(force_update=True)
            messages.success(request, _("Your signature has been changed."), 'usercp_signature')
            return redirect(reverse('usercp_signature'))
        else:
            message = Message(form.non_field_errors()[0], messages.ERROR)
    else:
        form = SignatureForm(request=request, initial={'signature': request.user.signature})

    return render_to_response('usercp/signature.html',
                              context_instance=RequestContext(request, {
                                  'message': message,
                                  'tab': 'signature',
                                  'form': form}));
Exemple #6
0
def server(request, attachment, thumb=False):
    try:
        attachment = Attachment.objects.select_related('forum', 'thread', 'post', 'user').get(hash_id=attachment)
        if attachment.forum:
            request.acl.forums.allow_forum_view(attachment.forum)
        if attachment.thread:
            request.acl.threads.allow_thread_view(request.user, attachment.thread)
            if attachment.forum.special == 'private_threads':
                if not request.user.is_authenticated():
                    raise ACLError404()
                can_see_thread_because_reported = (
                    request.acl.private_threads.is_mod() and attachment.thread.replies_reported)
                can_see_thread_because_participates = request.user in attachment.thread.participants.all()
                if not (can_see_thread_because_reported or can_see_thread_because_participates):
                    raise ACLError404()
            if attachment.post:
                request.acl.threads.allow_post_view(request.user, attachment.thread, attachment.post)
                request.acl.threads.allow_attachment_download(request.user, attachment.forum, attachment.post)
        return serve_file(attachment, thumb)
    except ACLError403:
        if attachment.is_image:
            return serve_403_image()
        return error403(request,  _("You don't have permission to download this file."))
    except (Attachment.DoesNotExist, ACLError404):
        if thumb:
            return serve_404_image()
        return error404(request, _("Requested file could not be found."))
Exemple #7
0
 def decorator(*args, **kwargs):
     request = args[0]
     try:
         if not request.firewall.admin and request.jam.is_jammed():
             return error403(request, _("You have used up allowed attempts quota and we temporarily banned you from accessing this page."))
     except AttributeError:
         pass
     return f(*args, **kwargs)
Exemple #8
0
 def decorator(*args, **kwargs):
     request = args[0]
     if not request.user.is_authenticated():
         return error403(
             request,
             _("Dear Guest, only signed in members are allowed to access this page. Please sign in or register and try again."
               ))
     return f(*args, **kwargs)
Exemple #9
0
 def decorator(*args, **kwargs):
     request = args[0]
     if not request.firewall.admin and request.user.is_authenticated():
         return error403(
             request,
             _("%(username)s, this page is not available to signed in users."
               ) % {'username': request.user.username})
     return f(*args, **kwargs)
Exemple #10
0
    def __call__(self, request, **kwargs):
        self.request = request
        self.kwargs = kwargs
        self.parents = []
        self.ignored = False
        self.watcher = False
        self.message = request.messages.get_message("threads")
        try:
            self._type_available()
            self.fetch_thread()
            self.check_forum_type()
            self._check_permissions()
            response = self.fetch_posts()
            if response:
                return response
            self.make_thread_form()
            if self.thread_form:
                response = self.handle_thread_form()
                if response:
                    return response
            self.make_posts_form()
            if self.posts_form:
                response = self.handle_posts_form()
                if response:
                    return response
        except (Forum.DoesNotExist, Thread.DoesNotExist):
            return error404(request)
        except ACLError403 as e:
            return error403(request, unicode(e))
        except ACLError404 as e:
            return error404(request, unicode(e))

        # Merge proxy into forum
        self.forum.closed = self.proxy.closed

        return render_to_response(
            "%ss/thread.html" % self.type_prefix,
            self._template_vars(
                {
                    "message": self.message,
                    "forum": self.forum,
                    "parents": self.parents,
                    "thread": self.thread,
                    "is_read": self.tracker.is_read(self.thread),
                    "count": self.count,
                    "posts": self.posts,
                    "ignored_posts": self.ignored,
                    "watcher": self.watcher,
                    "pagination": self.pagination,
                    "emojis": emojis(),
                    "quick_reply": QuickReplyForm(request=request),
                    "thread_form": self.thread_form or None,
                    "posts_form": self.posts_form or None,
                }
            ),
            context_instance=RequestContext(request),
        )
Exemple #11
0
    def __call__(self, request, **kwargs):
        self.request = request
        self.kwargs = kwargs
        self.parents = []
        self.ignored = False
        self.watcher = False
        self.message = request.messages.get_message('threads')
        try:
            self._type_available()
            self.fetch_thread()
            self.check_forum_type()
            self._check_permissions()
            response = self.fetch_posts()
            if response:
                return response
            self.make_thread_form()
            if self.thread_form:
                response = self.handle_thread_form()
                if response:
                    return response
            self.make_posts_form()
            if self.posts_form:
                response = self.handle_posts_form()
                if response:
                    return response
        except (Forum.DoesNotExist, Thread.DoesNotExist):
            return error404(request)
        except ACLError403 as e:
            return error403(request, unicode(e))
        except ACLError404 as e:
            return error404(request, unicode(e))

        # Merge proxy into forum
        self.forum.closed = self.proxy.closed

        return request.theme.render_to_response('%ss/thread.html' % self.type_prefix,
                                                self.template_vars({
                                                 'type_prefix': self.type_prefix,
                                                 'message': self.message,
                                                 'forum': self.forum,
                                                 'parents': self.parents,
                                                 'thread': self.thread,
                                                 'is_read': self.tracker.is_read(self.thread),
                                                 'count': self.count,
                                                 'posts': self.posts,
                                                 'ignored_posts': self.ignored,
                                                 'watcher': self.watcher,
                                                 'pagination': self.pagination,
                                                 'emojis': emojis(),
                                                 'quick_reply': FormFields(QuickReplyForm(request=request)).fields,
                                                 'thread_form': FormFields(self.thread_form).fields if self.thread_form else None,
                                                 'posts_form': FormFields(self.posts_form).fields if self.posts_form else None,
                                                 }),
                                                context_instance=RequestContext(request));
Exemple #12
0
    def __call__(self, request, **kwargs):
        self.request = request
        self.kwargs = kwargs
        self.parents = []
        self.ignored = False
        self.watcher = False
        self.message = request.messages.get_message('threads')
        try:
            self._type_available()
            self.fetch_thread()
            self.check_forum_type()
            self._check_permissions()
            response = self.fetch_posts()
            if response:
                return response
            self.make_thread_form()
            if self.thread_form:
                response = self.handle_thread_form()
                if response:
                    return response
            self.make_posts_form()
            if self.posts_form:
                response = self.handle_posts_form()
                if response:
                    return response
        except (Forum.DoesNotExist, Thread.DoesNotExist):
            return error404(request)
        except ACLError403 as e:
            return error403(request, unicode(e))
        except ACLError404 as e:
            return error404(request, unicode(e))

        # Merge proxy into forum
        self.forum.closed = self.proxy.closed

        return render_to_response('%ss/thread.html' % self.type_prefix,
                                  self._template_vars({
                                        'message': self.message,
                                        'forum': self.forum,
                                        'parents': self.parents,
                                        'thread': self.thread,
                                        'is_read': self.tracker.is_read(self.thread),
                                        'count': self.count,
                                        'posts': self.posts,
                                        'ignored_posts': self.ignored,
                                        'watcher': self.watcher,
                                        'pagination': self.pagination,
                                        'emojis': emojis(),
                                        'quick_reply': QuickReplyForm(request=request),
                                        'thread_form': self.thread_form or None,
                                        'posts_form': self.posts_form or None,
                                      }),
                                  context_instance=RequestContext(request));
Exemple #13
0
 def __call__(self, request, **kwargs):
     try:
         if request.user.is_crawler():
             raise ACLError404()
         if not request.acl.search.can_search():
             raise ACLError403(_("You don't have permission to search community."))
         self.request = request
         return self.call(**kwargs)
     except ACLError403 as e:
         return error403(request, unicode(e))
     except ACLError404 as e:
         return error404(request, unicode(e))
Exemple #14
0
def watched_threads(request, page=0, new=False):
    # Find mode and fetch threads
    readable_forums = Forum.objects.readable_forums(request.acl, True)
    starter_readable_forums = Forum.objects.starter_readable_forums(request.acl)

    if not readable_forums and not readable_forums:
        return error403(request, _("%(username), you cannot read any forums.") % {'username': request.user.username})

    private_threads_pk = Forum.objects.special_pk('private_threads')
    if not settings.enable_private_threads and private_threads_pk in readable_forums:
        readable_forums.remove(private_threads_pk)

    queryset = WatchedThread.objects.filter(user=request.user).filter(thread__moderated=False).filter(thread__deleted=False).select_related('thread')
    if starter_readable_forums and readable_forums:
        queryset = queryset.filter(Q(forum_id__in=readable_forums) | Q(forum_id__in=starter_readable_forums, starter_id=request.user.pk))
    elif starter_readable_forums:
        queryset = queryset.filter(starter_id__in=request.user.pk).filter(forum_id__in=starter_readable_forums)
    else:
        queryset = queryset.filter(forum_id__in=readable_forums)

    if settings.avatars_on_threads_list:
        queryset = queryset.prefetch_related('thread__last_poster')
    if new:
        queryset = queryset.filter(last_read__lt=F('thread__last'))
    count = queryset.count()
    try:
        pagination = make_pagination(page, count, settings.threads_per_page)
    except Http404:
        if new:
            return redirect(reverse('watched_threads_new'))
        return redirect(reverse('watched_threads'))
    queryset = queryset.order_by('-thread__last')
    if settings.threads_per_page < count:
        queryset = queryset[pagination['start']:pagination['stop']]
    queryset.prefetch_related('thread__forum', 'thread__start_poster', 'thread__last_poster')
    threads = []
    for thread in queryset:
        thread.thread.send_email = thread.email
        thread.thread.is_read = thread.thread.last <= thread.last_read
        threads.append(thread.thread)

    # Display page
    return render_to_response('watched.html',
                              {
                              'items_total': count,
                              'pagination': pagination,
                              'new': new,
                              'threads': threads,
                              'prefixes': ThreadPrefix.objects.all_prefixes(),
                              'message': request.messages.get_message('threads'),
                              },
                              context_instance=RequestContext(request))
Exemple #15
0
 def process_view(self, request, callback, callback_args, callback_kwargs):
     # Block all crawlers with 403
     if request.user.is_crawler():
         request.theme.reset_theme()
         return error403(request)
     else:
         # If we are not authenticated or not admin, force us to sign in right way
         if not request.user.is_authenticated():
             return signin(request)
         elif not request.user.is_god() and not request.acl.special.is_admin():
             request.messages.set_message(Message(_("Your account does not have admin privileges")), 'error', 'security')
             return signin(request)
         return None
Exemple #16
0
 def __call__(self, request, **kwargs):
     try:
         if request.user.is_crawler():
             raise ACLError404()
         if not request.acl.search.can_search():
             raise ACLError403(
                 _("You don't have permission to search community."))
         self.request = request
         return self.call(**kwargs)
     except ACLError403 as e:
         return error403(request, unicode(e))
     except ACLError404 as e:
         return error404(request, unicode(e))
Exemple #17
0
    def __call__(self, request, **kwargs):
        self.request = request
        self.kwargs = kwargs
        self.pagination = {}
        self.parents = []
        self.threads = []
        self.message = request.messages.get_message('threads')
        try:
            self._type_available()
            self._fetch_forum()
            self._check_permissions()
            response = self.fetch_threads()
            if response:
                return response
            self.form = None
            self.make_form()
            if self.form:
                response = self.handle_form()
                if response:
                    return response
        except (Forum.DoesNotExist, Thread.DoesNotExist):
            return error404(request)
        except ACLError403 as e:
            return error403(request, unicode(e))
        except ACLError404 as e:
            return error404(request, unicode(e))

        # Merge proxy into forum
        self.forum.closed = self.proxy.closed

        return request.theme.render_to_response(
            '%ss/%s.html' % (self.type_prefix, self.template),
            self.template_vars({
                'type_prefix':
                self.type_prefix,
                'message':
                self.message,
                'forum':
                self.forum,
                'parents':
                self.parents,
                'count':
                self.count,
                'list_form':
                FormFields(self.form).fields if self.form else None,
                'threads':
                self.threads,
                'pagination':
                self.pagination,
            }),
            context_instance=RequestContext(request))
Exemple #18
0
def redirect(request, forum, slug):
    if not request.acl.forums.can_see(forum):
        return error404(request)
    try:
        forum = Forum.objects.get(pk=forum, type='redirect')
        if not request.acl.forums.can_browse(forum):
            return error403(request, _("You don't have permission to follow this redirect."))
        redirects_tracker = request.session.get('redirects', [])
        if forum.pk not in redirects_tracker:
            redirects_tracker.append(forum.pk)
            request.session['redirects'] = redirects_tracker
            forum.redirects += 1
            forum.save(force_update=True)
        return django_redirect(forum.redirect)
    except Forum.DoesNotExist:
        return error404(request)
Exemple #19
0
 def process_view(self, request, callback, callback_args, callback_kwargs):
     # Block all crawlers with 403
     if request.user.is_crawler():
         request.theme.reset_theme()
         return error403(request)
     else:
         # If we are not authenticated or not admin, force us to sign in right way
         if not request.user.is_authenticated():
             return signin(request)
         elif not request.user.is_god(
         ) and not request.acl.special.is_admin():
             request.messages.set_message(
                 Message(_("Your account does not have admin privileges")),
                 'error', 'security')
             return signin(request)
         return None
Exemple #20
0
 def __call__(self, request, **kwargs):
     self.request = request
     self.kwargs = kwargs
     self.parents = []
     try:
         self._type_available()
         self._set_context()
         self._check_permissions()
         self.delete()
         self.message()
         return self.response()
     except (Forum.DoesNotExist, Thread.DoesNotExist, Post.DoesNotExist, Checkpoint.DoesNotExist):
         return error404(request)
     except ACLError403 as e:
         return error403(request, unicode(e))
     except ACLError404 as e:
         return error404(request, unicode(e))
Exemple #21
0
def category(request, forum, slug):
    if not request.acl.forums.can_see(forum):
        return error404(request)
    try:
        forum = Forum.objects.get(pk=forum, type='category')
        if not request.acl.forums.can_browse(forum):
            return error403(request, _("You don't have permission to browse this category."))
    except Forum.DoesNotExist:
        return error404(request)

    forum.subforums = Forum.objects.treelist(request.acl.forums, forum, tracker=ForumsTracker(request.user))
    return render_to_response('category.html',
                              {
                              'category': forum,
                              'parents': Forum.objects.forum_parents(forum.pk),
                              },
                              context_instance=RequestContext(request));
Exemple #22
0
 def __call__(self, request, **kwargs):
     self.search_route = self.default_search_route
     self.search_form = self.default_search_form
     try:
         self.request = request
         if request.user.is_crawler():
             raise ACLError404()
         self.check_acl()
         if not request.acl.search.can_search():
             raise ACLError403(_("You don't have permission to search community."))
         if self.request.method == "POST":
             return self.search(request)
         return self.draw_form(request)
     except ACLError403 as e:
         return error403(request, unicode(e))
     except ACLError404 as e:
         return error404(request, unicode(e))
Exemple #23
0
 def __call__(self, request, **kwargs):
     self.search_route = self.default_search_route
     self.search_form = self.default_search_form
     try:
         self.request = request
         if request.user.is_crawler():
             raise ACLError404()
         self.check_acl()
         if not request.acl.search.can_search():
             raise ACLError403(
                 _("You don't have permission to search community."))
         if self.request.method == "POST":
             return self.search(request)
         return self.draw_form(request)
     except ACLError403 as e:
         return error403(request, unicode(e))
     except ACLError404 as e:
         return error404(request, unicode(e))
Exemple #24
0
def redirect(request, forum, slug):
    if not request.acl.forums.can_see(forum):
        return error404(request)
    try:
        forum = Forum.objects.get(pk=forum, type='redirect')
        if not request.acl.forums.can_browse(forum):
            return error403(
                request,
                _("You don't have permission to follow this redirect."))
        redirects_tracker = request.session.get('redirects', [])
        if forum.pk not in redirects_tracker:
            redirects_tracker.append(forum.pk)
            request.session['redirects'] = redirects_tracker
            forum.redirects += 1
            forum.save(force_update=True)
        return django_redirect(forum.redirect)
    except Forum.DoesNotExist:
        return error404(request)
Exemple #25
0
 def __call__(self, request, **kwargs):
     self.request = request
     self.kwargs = kwargs
     self.parents = []
     try:
         self._type_available()
         self._set_context()
         self._check_permissions()
         self.delete()
         self.message()
         return self.response()
     except (Forum.DoesNotExist, Thread.DoesNotExist, Post.DoesNotExist,
             Checkpoint.DoesNotExist):
         return error404(request)
     except ACLError403 as e:
         return error403(request, unicode(e))
     except ACLError404 as e:
         return error404(request, unicode(e))
Exemple #26
0
 def inner_decorator(request, user, username, *args, **kwargs):
     request = request
     user_pk = int(user)
     user_slug = username
     try:
         user = User.objects
         if settings.PROFILE_EXTENSIONS_PRELOAD:
             user = user.select_related(*settings.PROFILE_EXTENSIONS_PRELOAD)
         user = user.get(pk=user_pk)
         if user.username_slug != user_slug:
             # Force crawlers to take notice of updated username
             return redirect(reverse(fallback, args=(user.username_slug, user.pk)), permanent=True)
         return f(request, user, *args, **kwargs)
     except User.DoesNotExist:
         return error404(request)
     except ACLError404:
         return error404(request)
     except ACLError403 as e:
         return error403(request, e.message)
Exemple #27
0
 def __call__(self, request, **kwargs):
     self.request = request
     self.kwargs = kwargs
     self.forum = None
     self.thread = None
     self.post = None
     self.parents = []
     try:
         self._type_available()
         self.fetch_target()
         self.check_acl()
         self._check_permissions()
     except (Forum.DoesNotExist, Thread.DoesNotExist, Post.DoesNotExist):
         return error404(self.request)
     except ACLError403 as e:
         return error403(request, e)
     except ACLError404 as e:
         return error404(request, e)
     return self.response()
Exemple #28
0
 def __call__(self, request, **kwargs):
     self.request = request
     self.kwargs = kwargs
     self.forum = None
     self.thread = None
     self.post = None
     self.parents = []
     try:
         self._type_available()
         self.fetch_target()
         self.check_acl()
         self._check_permissions()
     except (Forum.DoesNotExist, Thread.DoesNotExist, Post.DoesNotExist):
         return error404(self.request)
     except ACLError403 as e:
         return error403(request, e)
     except ACLError404 as e:
         return error404(request, e)
     return self.response()
Exemple #29
0
 def __call__(self, request, slug=None, thread=None, post=None):
     self.request = request
     self.parents = []
     try:
         self._type_available()
         self.fetch_thread(thread)
         if self.forum.level:
             self.parents = Forum.objects.forum_parents(self.forum.pk, True)
         self.check_forum_type()
         self._check_permissions()
         if post:
             self.fetch_post(post)
         return self.make_jump()
     except (Thread.DoesNotExist, Post.DoesNotExist):
         return error404(self.request)
     except ACLError403 as e:
         return error403(request, e)
     except ACLError404 as e:
         return error404(request, e)
Exemple #30
0
 def __call__(self, request, slug=None, thread=None, post=None):
     self.request = request
     self.parents = []
     try:
         self._type_available()
         self.fetch_thread(thread)
         if self.forum.level:
             self.parents = Forum.objects.forum_parents(self.forum.pk, True)
         self.check_forum_type()
         self._check_permissions()
         if post:
             self.fetch_post(post)
         return self.make_jump()
     except (Thread.DoesNotExist, Post.DoesNotExist):
         return error404(self.request)
     except ACLError403 as e:
         return error403(request, e)
     except ACLError404 as e:
         return error404(request, e)
Exemple #31
0
    def __call__(self, request, **kwargs):
        self.request = request
        self.kwargs = kwargs
        self.pagination = {}
        self.parents = []
        self.threads = []
        self.message = request.messages.get_message('threads')
        try:
            self._type_available()
            self._fetch_forum()
            self._check_permissions()
            response = self.fetch_threads()
            if response:
                return response
            self.form = None
            self.make_form()
            if self.form:
                response = self.handle_form()
                if response:
                    return response
        except (Forum.DoesNotExist, Thread.DoesNotExist):
            return error404(request)
        except ACLError403 as e:
            return error403(request, unicode(e))
        except ACLError404 as e:
            return error404(request, unicode(e))

        # Merge proxy into forum
        self.forum.closed = self.proxy.closed

        return request.theme.render_to_response('%ss/%s.html' % (self.type_prefix, self.template),
                                                self.template_vars({
                                                 'type_prefix': self.type_prefix,
                                                 'message': self.message,
                                                 'forum': self.forum,
                                                 'parents': self.parents,
                                                 'count': self.count,
                                                 'list_form': FormFields(self.form).fields if self.form else None,
                                                 'threads': self.threads,
                                                 'pagination': self.pagination,
                                                 }),
                                                context_instance=RequestContext(request));
Exemple #32
0
 def __call__(self, request, **kwargs):
     self.request = request
     self.kwargs = kwargs
     self.forum = None
     self.thread = None
     self.post = None
     self.parents = []
     try:
         self._type_available()
         self.fetch_target()
         self._check_permissions()
         if not request.user.is_authenticated():
             raise ACLError403(_("Guest, you have to sign-in in order to see posts changelogs."))
     except (Forum.DoesNotExist, Thread.DoesNotExist, Post.DoesNotExist, Change.DoesNotExist):
         return error404(self.request)
     except ACLError403 as e:
         return error403(request, e)
     except ACLError404 as e:
         return error404(request, e)
     return self.dispatch(request)
Exemple #33
0
def category(request, forum, slug):
    if not request.acl.forums.can_see(forum):
        return error404(request)
    try:
        forum = Forum.objects.get(pk=forum, type='category')
        if not request.acl.forums.can_browse(forum):
            return error403(
                request,
                _("You don't have permission to browse this category."))
    except Forum.DoesNotExist:
        return error404(request)

    forum.subforums = Forum.objects.treelist(request.acl.forums,
                                             forum,
                                             tracker=ForumsTracker(
                                                 request.user))
    return render_to_response('category.html', {
        'category': forum,
        'parents': Forum.objects.forum_parents(forum.pk),
    },
                              context_instance=RequestContext(request))
Exemple #34
0
 def inner_decorator(request, user, username, *args, **kwargs):
     request = request
     user_pk = int(user)
     user_slug = username
     try:
         user = User.objects
         if settings.PROFILE_EXTENSIONS_PRELOAD:
             user = user.select_related(
                 *settings.PROFILE_EXTENSIONS_PRELOAD)
         user = user.get(pk=user_pk)
         if user.username_slug != user_slug:
             # Force crawlers to take notice of updated username
             return redirect(reverse(fallback,
                                     args=(user.username_slug,
                                           user.pk)),
                             permanent=True)
         return f(request, user, *args, **kwargs)
     except User.DoesNotExist:
         return error404(request)
     except ACLError404:
         return error404(request)
     except ACLError403 as e:
         return error403(request, e.message)
Exemple #35
0
 def __call__(self, request, **kwargs):
     self.request = request
     self.kwargs = kwargs
     self.forum = None
     self.thread = None
     self.post = None
     self.parents = []
     try:
         self._type_available()
         self.fetch_target()
         self._check_permissions()
         if not request.user.is_authenticated():
             raise ACLError403(
                 _("Guest, you have to sign-in in order to see posts changelogs."
                   ))
     except (Forum.DoesNotExist, Thread.DoesNotExist, Post.DoesNotExist,
             Change.DoesNotExist):
         return error404(self.request)
     except ACLError403 as e:
         return error403(request, e)
     except ACLError404 as e:
         return error404(request, e)
     return self.dispatch(request)
Exemple #36
0
    def __call__(self, request, **kwargs):
        self.request = request
        self.kwargs = kwargs
        self.forum = None
        self.thread = None
        self.quote = None
        self.post = None
        self.parents = []
        self.message = request.messages.get_message('threads')

        post_preview = ''
        form = None

        try:
            self._type_available()
            self._set_context()
            self.check_forum_type()
            self._check_permissions()
            request.block_flood_requests = self.block_flood_requests
            self.make_attachments_token()
            self.fetch_attachments()
            if request.method == 'POST':
                # Create correct form instance
                if self.allow_quick_reply and 'quick_reply' in request.POST:
                    form = QuickReplyForm(request.POST, request=request)
                if not form or 'preview' in request.POST or not form.is_valid(
                ):
                    # Override "quick reply" form with full one
                    try:
                        form = self.form_type(request.POST,
                                              request.FILES,
                                              request=request,
                                              forum=self.forum,
                                              thread=self.thread)
                    except AttributeError:
                        form = self.form_type(request.POST,
                                              request=request,
                                              forum=self.forum,
                                              thread=self.thread)
                # Handle specific submit
                if list(
                        set(request.POST.keys())
                        & set(('preview', 'upload', 'remove_attachment',
                               'restore_attachment'))):
                    form.empty_errors()
                    if form['post'].value():
                        md, post_preview = post_markdown(form['post'].value())
                    else:
                        md, post_preview = None, None
                    if 'upload' in request.POST:
                        try:
                            uploaded_file = form['new_file'].value()
                        except KeyError:
                            uploaded_file = None
                        self._upload_file(uploaded_file)
                    if 'remove_attachment' in request.POST:
                        try:
                            self.remove_attachment(
                                int(request.POST.get('remove_attachment')))
                        except ValueError:
                            self.message = Message(
                                _("Requested attachment could not be found."),
                                messages.ERROR)
                    if 'restore_attachment' in request.POST:
                        try:
                            self.restore_attachment(
                                int(request.POST.get('restore_attachment')))
                        except ValueError:
                            self.message = Message(
                                _("Requested attachment could not be found."),
                                messages.ERROR)
                else:
                    if form.is_valid():
                        self.post_form(form)
                        self.watch_thread()
                        self.after_form(form)
                        self.finalize_attachments()
                        self.notify_users()
                        return self.response()
                    else:
                        self.message = Message(form.non_field_errors()[0],
                                               messages.ERROR)
            else:
                form = self.form_type(request=request,
                                      forum=self.forum,
                                      thread=self.thread,
                                      initial=self.form_initial_data())
        except (Forum.DoesNotExist, Thread.DoesNotExist, Post.DoesNotExist):
            return error404(request)
        except ACLError403 as e:
            return error403(request, unicode(e))
        except ACLError404 as e:
            return error404(request, unicode(e))

        return render_to_response('%ss/posting.html' % self.type_prefix,
                                  self._template_vars({
                                      'action':
                                      self.action,
                                      'attachments':
                                      self.attachments,
                                      'attachments_types':
                                      AttachmentType.objects.all_types(),
                                      'attachments_removed':
                                      self.attachments_removed,
                                      'attachments_number':
                                      self.user_attachments,
                                      'message':
                                      self.message,
                                      'forum':
                                      self.forum,
                                      'thread':
                                      self.thread,
                                      'quote':
                                      self.quote,
                                      'post':
                                      self.post,
                                      'parents':
                                      self.parents,
                                      'preview':
                                      post_preview,
                                      'form':
                                      form,
                                      'emojis':
                                      emojis(),
                                  }),
                                  context_instance=RequestContext(request))
Exemple #37
0
 def decorator(*args, **kwargs):
     request = args[0]
     if not request.firewall.admin and request.user.is_authenticated():
         return error403(request, _("%(username)s, this page is not available to signed in users.") % {'username': request.user.username})
     return f(*args, **kwargs)
Exemple #38
0
 def decorator(*args, **kwargs):
     request = args[0]
     if request.user.is_crawler():
         return error403(request)
     return f(*args, **kwargs)
Exemple #39
0
def list(request, slug=None, page=1):
    ranks = Rank.objects.filter(as_tab=1).order_by('order')

    # Find active rank
    default_rank = False
    active_rank = None
    if slug:
        for rank in ranks:
            if rank.slug == slug:
                active_rank = rank
        if not active_rank:
            return error404(request)
        if ranks and active_rank.slug == ranks[0].slug:
            return redirect(reverse('users'))
    elif ranks:
        default_rank = True
        active_rank = ranks[0]

    # Empty Defaults
    message = None
    users = []
    items_total = 0
    pagination = None
    in_search = False

    # Users search?
    if request.method == 'POST':
        if not request.acl.users.can_search_users():
            return error403(request)
        in_search = True
        active_rank = None
        search_form = QuickFindUserForm(request.POST, request=request)
        if search_form.is_valid():
            # Direct hit?
            username = search_form.cleaned_data['username']
            try:
                user = User.objects.get(username__iexact=username)
                return redirect(reverse('user', args=(user.username_slug, user.pk)))
            except User.DoesNotExist:
                pass

            # Looks like well have to find near match
            if len(username) > 6:
                username = username[0:-3]
            elif len(username) > 5:
                username = username[0:-2]
            elif len(username) > 4:
                username = username[0:-1]
            username = slugify(username.strip())

            # Go for rought match
            if len(username) > 0:
                users = User.objects.filter(username_slug__startswith=username).order_by('username_slug')[:10]
        elif search_form.non_field_errors()[0] == 'form_contains_errors':
            message = Message(_("To search users you have to enter username in search field."), 'error')
        else:
            message = Message(search_form.non_field_errors()[0], 'error')
    else:
        search_form = QuickFindUserForm(request=request)
        if active_rank:
            users = User.objects.filter(rank=active_rank)
            items_total = users.count()
            pagination = make_pagination(page, items_total, request.settings['profiles_per_list'])
            users = users.order_by('username_slug')[pagination['start']:pagination['stop']]

    return request.theme.render_to_response('profiles/list.html',
                                        {
                                         'message': message,
                                         'search_form': FormFields(search_form).fields,
                                         'in_search': in_search,
                                         'active_rank': active_rank,
                                         'default_rank': default_rank,
                                         'items_total': items_total,
                                         'ranks': ranks,
                                         'users': users,
                                         'pagination': pagination,
                                        },
                                        context_instance=RequestContext(request));
Exemple #40
0
    def __call__(self, request, **kwargs):
        self.request = request
        self.kwargs = kwargs
        self.forum = None
        self.thread = None
        self.quote = None
        self.post = None
        self.parents = []
        self.message = request.messages.get_message('threads')

        post_preview = ''
        form = None

        try:
            self._type_available()
            self._set_context()
            self.check_forum_type()
            self._check_permissions()
            if request.method == 'POST':
                # Create correct form instance
                if self.allow_quick_reply and 'quick_reply' in request.POST:
                    form = QuickReplyForm(request.POST, request=request)
                if not form or 'preview' in request.POST or not form.is_valid():
                    # Override "quick reply" form with full one
                    try:
                        form = self.form_type(request.POST, request.FILE, request=request, forum=self.forum, thread=self.thread)
                    except AttributeError:
                        form = self.form_type(request.POST, request=request, forum=self.forum, thread=self.thread)
                
                # Handle specific submit
                if 'preview' in request.POST:
                    form.empty_errors()
                    if form['post'].value():
                        md, post_preview = post_markdown(request, form['post'].value())
                    else:
                        md, post_preview = None, None
                else:
                    if form.is_valid():
                        self.post_form(form)
                        self.watch_thread()
                        self.after_form(form)
                        self.notify_users()
                        return self.response()
                    else:
                        self.message = Message(form.non_field_errors()[0], 'error')
            else:
                form = self.form_type(request=request, forum=self.forum, thread=self.thread, initial=self.form_initial_data())
        except (Forum.DoesNotExist, Thread.DoesNotExist, Post.DoesNotExist):
            return error404(request)
        except ACLError403 as e:
            return error403(request, unicode(e))
        except ACLError404 as e:
            return error404(request, unicode(e))

        return request.theme.render_to_response(('%ss/posting.html' % self.type_prefix),
                                                self.template_vars({
                                                 'type_prefix': self.type_prefix,
                                                 'action': self.action,
                                                 'message': self.message,
                                                 'forum': self.forum,
                                                 'thread': self.thread,
                                                 'quote': self.quote,
                                                 'post': self.post,
                                                 'parents': self.parents,
                                                 'preview': post_preview,
                                                 'form': FormLayout(form),
                                                 }),
                                                context_instance=RequestContext(request));
Exemple #41
0
    def __call__(self, request, **kwargs):
        self.request = request
        self.kwargs = kwargs
        self.forum = None
        self.thread = None
        self.quote = None
        self.post = None
        self.parents = []
        self.message = request.messages.get_message('threads')

        post_preview = ''
        form = None

        try:
            self._type_available()
            self._set_context()
            self.check_forum_type()
            self._check_permissions()
            request.block_flood_requests = self.block_flood_requests
            self.make_attachments_token()
            self.fetch_attachments()
            if request.method == 'POST':
                # Create correct form instance
                if self.allow_quick_reply and 'quick_reply' in request.POST:
                    form = QuickReplyForm(request.POST, request=request)
                if not form or 'preview' in request.POST or not form.is_valid():
                    # Override "quick reply" form with full one
                    try:
                        form = self.form_type(request.POST, request.FILES, request=request, forum=self.forum, thread=self.thread)
                    except AttributeError:
                        form = self.form_type(request.POST, request=request, forum=self.forum, thread=self.thread)
                # Handle specific submit
                if list(set(request.POST.keys()) & set(('preview', 'upload', 'remove_attachment', 'restore_attachment'))):
                    form.empty_errors()
                    if form['post'].value():
                        md, post_preview = post_markdown(form['post'].value())
                    else:
                        md, post_preview = None, None
                    if 'upload' in request.POST:
                        try:
                            uploaded_file = form['new_file'].value()
                        except KeyError:
                            uploaded_file = None
                        self._upload_file(uploaded_file)
                    if 'remove_attachment' in request.POST:
                        try:
                            self.remove_attachment(int(request.POST.get('remove_attachment')))
                        except ValueError:
                            self.message = Message(_("Requested attachment could not be found."), messages.ERROR)
                    if 'restore_attachment' in request.POST:
                        try:
                            self.restore_attachment(int(request.POST.get('restore_attachment')))
                        except ValueError:
                            self.message = Message(_("Requested attachment could not be found."), messages.ERROR)
                else:
                    if form.is_valid():
                        self.post_form(form)
                        self.watch_thread()
                        self.after_form(form)
                        self.finalize_attachments()
                        self.notify_users()
                        return self.response()
                    else:
                        self.message = Message(form.non_field_errors()[0], messages.ERROR)
            else:
                form = self.form_type(request=request, forum=self.forum, thread=self.thread, initial=self.form_initial_data())
        except (Forum.DoesNotExist, Thread.DoesNotExist, Post.DoesNotExist):
            return error404(request)
        except ACLError403 as e:
            return error403(request, unicode(e))
        except ACLError404 as e:
            return error404(request, unicode(e))

        return render_to_response('%ss/posting.html' % self.type_prefix,
                                  self._template_vars({
                                        'action': self.action,
                                        'attachments': self.attachments,
                                        'attachments_types': AttachmentType.objects.all_types(),
                                        'attachments_removed': self.attachments_removed,
                                        'attachments_number': self.user_attachments,
                                        'message': self.message,
                                        'forum': self.forum,
                                        'thread': self.thread,
                                        'quote': self.quote,
                                        'post': self.post,
                                        'parents': self.parents,
                                        'preview': post_preview,
                                        'form': form,
                                        'emojis': emojis(),
                                      }),
                                  context_instance=RequestContext(request));
Exemple #42
0
 def decorator(*args, **kwargs):
     request = args[0]
     if not request.user.is_authenticated():
         return error403(request, _("Dear Guest, only signed in members are allowed to access this page. Please sign in or register and try again."))
     return f(*args, **kwargs)
Exemple #43
0
 def decorator(*args, **kwargs):
     request = args[0]
     if not request.csrf.request_secure(request):
         return error403(request, _("Request authorization is invalid. Please try again."))
     return f(*args, **kwargs)
Exemple #44
0
def warn_user(request, user, slug):
    try:
        user = User.objects.get(pk=user)
    except User.DoesNotExist:
        return error404(request, _("Requested user could not be found."))

    try:
        request.acl.warnings.allow_warning_members()
        user.acl().warnings.allow_warning()
    except ACLError403 as e:
        return error403(request, e)

    if not WarnLevel.objects.get_level(1):
        messages.error(request, _("No warning levels have been defined."))
        return redirect(request.POST.get('retreat',
            reverse('user', kwargs={
                'user': user.pk,
                'username': user.username_slug,
                })))

    current_warning_level = user.get_current_warning_level()
    next_warning_level = WarnLevel.objects.get_level(user.warning_level + 1)

    if not next_warning_level:
        return render_to_response('warn_user/max_level.html',
                                  {
                                   'warned_user': user,
                                   'retreat': request.POST.get('retreat'),
                                  },
                                  context_instance=RequestContext(request))

    form = WarnMemberForm(
        initial={'reason': request.POST.get('reason')}, request=request)
    if ('origin' in request.POST
            and request.POST.get('origin') == 'warning-form'):
        form = WarnMemberForm(request.POST, request=request)
        if form.is_valid():
            user.warning_level += 1
            if next_warning_level.expires_after_minutes:
                user.warning_level_update_on = timezone.now()
                user.warning_level_update_on += timedelta(
                    minutes=next_warning_level.expires_after_minutes)
            else:
                user.warning_level_update_on = None
            user.save(force_update=True)

            reason_preparsed = None
            if form.cleaned_data['reason']:
                reason_preparsed = basic_markdown(form.cleaned_data['reason'])

            warning = Warn.objects.create(
                user=user,
                reason=form.cleaned_data['reason'],
                reason_preparsed=reason_preparsed,
                given_on=timezone.now(),
                giver=request.user,
                giver_username=request.user.username,
                giver_slug=request.user.username_slug,
                giver_ip=request.session.get_ip(request),
                giver_agent=request.META.get('HTTP_USER_AGENT'))

            alerts.you_have_been_warned(request.user, user, warning)
            messages.success(request,
                _("%(user)s warning level has been increased.") % {
                    'user': user.username})
            return redirect(request.POST.get('retreat',
                reverse('user', kwargs={
                    'user': user.pk,
                    'username': user.username_slug,
                    })))

    return render_to_response('warn_user/form.html',
                              {
                               'warned_user': user,
                               'current_warning_level': current_warning_level,
                               'next_warning_level': next_warning_level,
                               'form': form,
                               'retreat': request.POST.get('retreat'),
                              },
                              context_instance=RequestContext(request))
Exemple #45
0
    def __call__(self, request, **kwargs):
        self.request = request
        self.kwargs = kwargs
        self.forum = None
        self.thread = None
        self.quote = None
        self.post = None
        self.parents = []
        self.message = request.messages.get_message('threads')

        post_preview = ''
        form = None

        try:
            self._type_available()
            self._set_context()
            self.check_forum_type()
            self._check_permissions()
            request.block_flood_requests = self.block_flood_requests
            if request.method == 'POST':
                # Create correct form instance
                if self.allow_quick_reply and 'quick_reply' in request.POST:
                    form = QuickReplyForm(request.POST, request=request)
                if not form or 'preview' in request.POST or not form.is_valid(
                ):
                    # Override "quick reply" form with full one
                    try:
                        form = self.form_type(request.POST,
                                              request.FILE,
                                              request=request,
                                              forum=self.forum,
                                              thread=self.thread)
                    except AttributeError:
                        form = self.form_type(request.POST,
                                              request=request,
                                              forum=self.forum,
                                              thread=self.thread)
                # Handle specific submit
                if 'preview' in request.POST:
                    form.empty_errors()
                    if form['post'].value():
                        md, post_preview = post_markdown(form['post'].value())
                    else:
                        md, post_preview = None, None
                else:
                    if form.is_valid():
                        self.post_form(form)
                        self.watch_thread()
                        self.after_form(form)
                        self.notify_users()
                        return self.response()
                    else:
                        self.message = Message(form.non_field_errors()[0],
                                               'error')
            else:
                form = self.form_type(request=request,
                                      forum=self.forum,
                                      thread=self.thread,
                                      initial=self.form_initial_data())
        except (Forum.DoesNotExist, Thread.DoesNotExist, Post.DoesNotExist):
            return error404(request)
        except ACLError403 as e:
            return error403(request, unicode(e))
        except ACLError404 as e:
            return error404(request, unicode(e))

        return request.theme.render_to_response(
            ('%ss/posting.html' % self.type_prefix),
            self.template_vars({
                'type_prefix': self.type_prefix,
                'action': self.action,
                'message': self.message,
                'forum': self.forum,
                'thread': self.thread,
                'quote': self.quote,
                'post': self.post,
                'parents': self.parents,
                'preview': post_preview,
                'form': FormLayout(form),
                'emojis': emojis(),
            }),
            context_instance=RequestContext(request))
Exemple #46
0
def list(request, slug=None, page=0):
    ranks = Rank.objects.filter(as_tab=1).order_by('order')

    # Find active rank
    default_rank = False
    active_rank = None
    if slug:
        for rank in ranks:
            if rank.slug == slug:
                active_rank = rank
        if not active_rank:
            return error404(request)
        if ranks and active_rank.slug == ranks[0].slug:
            return redirect(reverse('users'))
    elif ranks:
        default_rank = True
        active_rank = ranks[0]

    # Empty Defaults
    message = None
    users = []
    items_total = 0
    pagination = None
    in_search = False

    # Users search?
    if request.method == 'POST':
        if not request.acl.users.can_search_users():
            return error403(request)
        in_search = True
        active_rank = None
        search_form = QuickFindUserForm(request.POST, request=request)
        if search_form.is_valid():
            # Direct hit?
            username = search_form.cleaned_data['username']
            try:
                user = User.objects
                if settings.PROFILE_EXTENSIONS_PRELOAD:
                    user = user.select_related(
                        *settings.PROFILE_EXTENSIONS_PRELOAD)
                user = user.get(username__iexact=username)
                return redirect(
                    reverse('user', args=(user.username_slug, user.pk)))
            except User.DoesNotExist:
                pass

            # Looks like well have to find near match
            if len(username) > 6:
                username = username[0:-3]
            elif len(username) > 5:
                username = username[0:-2]
            elif len(username) > 4:
                username = username[0:-1]
            username = slugify(username.strip())

            # Go for rought match
            if len(username) > 0:
                users = User.objects
                if settings.PROFILE_EXTENSIONS_PRELOAD:
                    users = users.select_related(
                        *settings.PROFILE_EXTENSIONS_PRELOAD)
                users = users.filter(username_slug__startswith=username
                                     ).order_by('username_slug')[:10]
        elif search_form.non_field_errors()[0] == 'form_contains_errors':
            message = Message(
                _("To search users you have to enter username in search field."
                  ), 'error')
        else:
            message = Message(search_form.non_field_errors()[0], 'error')
    else:
        search_form = QuickFindUserForm(request=request)
        if active_rank:
            users = User.objects.filter(rank=active_rank)
            items_total = users.count()
            try:
                pagination = make_pagination(
                    page, items_total, request.settings['profiles_per_list'])
            except Http404:
                if not default_rank and active_rank:
                    return redirect(
                        reverse('users', kwargs={'slug': active_rank.slug}))
                return redirect(reverse('users'))
            if settings.PROFILE_EXTENSIONS_PRELOAD:
                users = users.select_related(
                    *settings.PROFILE_EXTENSIONS_PRELOAD)
            users = users.order_by(
                'username_slug')[pagination['start']:pagination['stop']]

    return request.theme.render_to_response(
        'profiles/list.html', {
            'message': message,
            'search_form': FormFields(search_form).fields,
            'in_search': in_search,
            'active_rank': active_rank,
            'default_rank': default_rank,
            'items_total': items_total,
            'ranks': ranks,
            'users': users,
            'pagination': pagination,
        },
        context_instance=RequestContext(request))