Пример #1
0
 def post_action_undelete(self, ids):
     undeleted = []
     for post in self.posts:
         if post.pk in ids and post.deleted:
             undeleted.append(post.pk)
     if undeleted:
         update_kwargs = {
             'deleted': False,
             'current_date': timezone.now(),
             'edit_user': self.request.user,
             'edit_user_name': self.request.user.username,
             'edit_user_slug': self.request.user.username_slug,
         }
         self.thread.post_set.filter(id__in=undeleted).update(
             **update_kwargs)
         self.thread.sync()
         self.thread.save(force_update=True)
         self.forum.sync()
         self.forum.save(force_update=True)
         messages.success(self.request,
                          _('Selected posts have been restored.'),
                          'threads')
     else:
         messages.info(self.request, _('No posts were restored.'),
                       'threads')
Пример #2
0
    def action_prefix(self, ids, prefix):
        prefixes = self.prefixes
        try:
            prefix = int(prefix)
        except TypeError:
            prefix = 0
        prefix = prefix or None

        if prefix:
            if self._action_set_prefix(ids, prefixes[prefix]):
                messages.success(
                    self.request,
                    _('Selected threads prefix has been changed to "%(name)s".'
                      ) % {'name': _(prefixes[prefix].name)}, 'threads')
            else:
                messages.info(self.request,
                              _('No threads prefix was changed.'), 'threads')
        else:
            if self._action_remove_prefix(ids):
                messages.success(
                    self.request,
                    _('Selected threads prefix has been removed.'), 'threads')
            else:
                messages.info(self.request,
                              _('No threads prefixes were removed.'),
                              'threads')
Пример #3
0
def unignore(request, user):
    if request.user.pk == user.pk:
        return error404(request)
    if request.user.is_ignoring(user):
        messages.info(request, _("You have stopped ignoring %(username)s") % {'username': user.username})
        request.user.ignores.remove(user)
    return fallback(request)
Пример #4
0
 def post_action_soft(self, ids):
     deleted = []
     for post in self.posts:
         if post.pk in ids and not post.deleted:
             if post.pk == self.thread.start_post_id:
                 raise forms.ValidationError(
                     _("You cannot delete first post of thread using this action. If you want to delete thread, use thread moderation instead."
                       ))
             deleted.append(post.pk)
     if deleted:
         update_kwargs = {
             'deleted': True,
             'current_date': timezone.now(),
             'delete_date': timezone.now(),
             'edit_user': self.request.user,
             'edit_user_name': self.request.user.username,
             'edit_user_slug': self.request.user.username_slug,
         }
         self.thread.post_set.filter(id__in=deleted).update(**update_kwargs)
         self.thread.sync()
         self.thread.save(force_update=True)
         self.forum.sync()
         self.forum.save(force_update=True)
         messages.success(self.request,
                          _('Selected posts have been hidden.'), 'threads')
     else:
         messages.info(self.request, _('No posts were hidden.'), 'threads')
Пример #5
0
 def action_soft(self, ids):
     if self._action_soft(ids):
         messages.success(self.request,
                          _('Selected threads have been hidden.'),
                          'threads')
     else:
         messages.info(self.request, _('No threads were hidden.'),
                       'threads')
Пример #6
0
 def action_hard(self, ids):
     if self._action_hard(ids):
         messages.success(self.request,
                          _('Selected threads have been deleted.'),
                          'threads')
     else:
         messages.info(self.request, _('No threads were deleted.'),
                       'threads')
Пример #7
0
 def action_close(self, ids):
     if self._action_close(ids):
         messages.success(self.request,
                          _('Selected threads have been closed.'),
                          'threads')
     else:
         messages.info(self.request, _('No threads were closed.'),
                       'threads')
Пример #8
0
    def __call__(self, request, target=None, slug=None):
        self.request = request

        # Fetch target
        model = None
        if target:
            model = self.get_and_validate_target(target)
            self.original_name = self.get_target_name(model)
            if not model:
                return redirect(self.get_fallback_link())
        original_model = model

        # Set filter
        users = model.make_queryset()
        total_users = users.count()

        if not total_users:
            messages.error(request, _('Policy "%(name)s" does not apply to any users.') % {'name': model.name}, self.admin.id)
            return redirect(reverse('admin_prune_users'))

        message = None
        if request.method == 'POST':
            deleted = 0
            if request.csrf.request_secure(request):
                for user in users.iterator():
                    if user.is_protected():
                        messages.info(request, _('User "%(name)s" is protected and was not deleted.') % {'name': user.username}, self.admin.id)
                    else:
                        user.delete()
                        deleted += 1
                if deleted:
                    messages.success(request, ungettext(
                                                        'One user has been deleted.',
                                                        '%(deleted)d users have been deleted.',
                                                        deleted
                                                        ) % {'deleted': deleted}, self.admin.id)
                    User.objects.resync_monitor()
                else:
                    messages.info(request, _("No users have been deleted."), self.admin.id)
                return redirect(reverse('admin_prune_users'))
            else:
                message = Message(_("Request authorization is invalid. Please resubmit your form."), messages.ERROR)

        return render_to_response(self.get_template(),
                                  {
                                  'admin': self.admin,
                                  'action': self,
                                  'request': request,
                                  'link': self.get_link(model),
                                  'fallback': self.get_fallback_link(),
                                  'messages': messages.get_messages(request, self.admin.id),
                                  'message': message,
                                  'tabbed': self.tabbed,
                                  'total_users': total_users,
                                  'target': self.get_target_name(original_model),
                                  'target_model': original_model,
                                  },
                                  context_instance=RequestContext(request));
Пример #9
0
 def action_accept(self, ids):
     if self._action_accept(ids):
         messages.success(
             self.request,
             _("Selected threads have been marked as reviewed and made visible to other members."),
             "threads",
         )
     else:
         messages.info(self.request, _("No threads were marked as reviewed."), "threads")
Пример #10
0
 def action_normal(self, ids):
     if self._action_normal(ids):
         messages.success(self.request,
                          _('Selected threads weight has been removed.'),
                          'threads')
     else:
         messages.info(self.request,
                       _('No threads have had their weight removed.'),
                       'threads')
Пример #11
0
 def action_accept(self, ids):
     if self._action_accept(ids):
         messages.success(
             self.request,
             _('Selected threads have been marked as reviewed and made visible to other members.'
               ), 'threads')
     else:
         messages.info(self.request,
                       _('No threads were marked as reviewed.'), 'threads')
Пример #12
0
 def post_action_unprotect(self, ids):
     unprotected = 0
     for post in self.posts:
         if post.pk in ids and post.protected:
             unprotected += 1
     if unprotected:
         self.thread.post_set.filter(id__in=ids).update(protected=False)
         messages.success(self.request, _('Protection from editions has been removed from selected posts.'), 'threads')
     else:
         messages.info(self.request, _('No posts were unprotected.'), 'threads')
Пример #13
0
 def action_sticky(self, ids):
     if self._action_sticky(ids):
         messages.success(
             self.request,
             _('Selected threads have been sticked to the top of list.'),
             'threads')
     else:
         messages.info(self.request,
                       _('No threads were turned into stickies.'),
                       'threads')
Пример #14
0
 def post_action_protect(self, ids):
     protected = 0
     for post in self.posts:
         if post.pk in ids and not post.protected:
             protected += 1
     if protected:
         self.thread.post_set.filter(id__in=ids).update(protected=True)
         messages.success(self.request, _("Selected posts have been protected from edition."), "threads")
     else:
         messages.info(self.request, _("No posts were protected."), "threads")
Пример #15
0
 def action_annouce(self, ids):
     if self._action_annouce(ids):
         messages.success(
             self.request,
             _('Selected threads have been turned into announcements.'),
             'threads')
     else:
         messages.info(self.request,
                       _('No threads were turned into announcements.'),
                       'threads')
Пример #16
0
def resync_forums(request, forum=0, progress=0):
    progress = int(progress)
    forums = request.session.get('sync_forums')
    if not forums:
        messages.info(request, _('No forums to resynchronize.'), 'forums')
        return redirect(reverse('admin_forums'))
    try:
        if not forum:
            forum = request.session['sync_forums'].pop()
        forum = Forum.objects.get(id=forum)
    except Forum.DoesNotExist:
        del request.session['sync_forums']
        messages.error(request,
                       _('Forum for resynchronization does not exist.'),
                       'forums')
        return redirect(reverse('admin_forums'))

    # Sync 50 threads
    threads_total = forum.thread_set.count()
    for thread in forum.thread_set.all()[progress:(progress + 1)]:
        thread.sync()
        thread.save(force_update=True)
        progress += 1

    if not threads_total:
        return redirect(django_reverse('admin_forums_resync'))

    # Render Progress
    response = render_to_response('processing.html', {
        'task_name': _('Resynchronizing Forums'),
        'target_name': forum.name,
        'message': _('Resynchronized %(progress)s from %(total)s threads') % {
            'progress': progress,
            'total': threads_total
        },
        'progress': progress * 100 / threads_total,
        'cancel_link': reverse('admin_forums'),
    },
                                  context_instance=RequestContext(request))

    # Redirect where to?
    if progress >= threads_total:
        forum.sync()
        forum.save(force_update=True)
        response['refresh'] = '2;url=%s' % django_reverse(
            'admin_forums_resync')
    else:
        response['refresh'] = '2;url=%s' % django_reverse(
            'admin_forums_resync',
            kwargs={
                'forum': forum.pk,
                'progress': progress
            })
    return response
Пример #17
0
def unfollow(request, user):
    if request.user.pk == user.pk:
        return error404(request)
    if request.user.is_following(user):
        messages.info(request, _("You have stopped following %(username)s") % {'username': user.username})
        request.user.follows.remove(user)
        request.user.following -= 1
        request.user.save(force_update=True)
        user.followers -= 1
        user.save(force_update=True)
    return fallback(request)
Пример #18
0
 def post_action_accept(self, ids):
     accepted = 0
     for post in self.posts:
         if post.pk in ids and post.moderated:
             accepted += 1
     if accepted:
         self.thread.post_set.filter(id__in=ids).update(moderated=False)
         self.thread.sync()
         self.thread.save(force_update=True)
         messages.success(self.request, _('Selected posts have been accepted and made visible to other members.'), 'threads')
     else:
         messages.info(self.request, _('No posts were accepted.'), 'threads')
Пример #19
0
def gallery(request):
    if not 'gallery' in settings.avatars_types:
        return error404(request)

    allowed_avatars = []
    galleries = []
    for directory in path(
            settings.STATICFILES_DIRS[0]).joinpath('avatars').dirs():
        if directory[-7:] != '_locked' and directory[-8:] != '_default':
            gallery = {'name': directory[-7:], 'avatars': []}
            avatars = directory.files('*.gif')
            avatars += directory.files('*.jpg')
            avatars += directory.files('*.jpeg')
            avatars += directory.files('*.png')
            for item in avatars:
                gallery['avatars'].append('/'.join(path(item).splitall()[-2:]))
            galleries.append(gallery)
            allowed_avatars += gallery['avatars']

    if not allowed_avatars:
        messages.info(request,
                      _("No avatar galleries are available at the moment."),
                      'usercp_avatar')
        return redirect(reverse('usercp_avatar'))

    message = request.messages.get_message('usercp_avatar')
    if request.method == 'POST':
        if request.csrf.request_secure(request):
            new_avatar = request.POST.get('avatar_image')
            if new_avatar in allowed_avatars:
                request.user.delete_avatar()
                request.user.avatar_type = 'gallery'
                request.user.avatar_image = new_avatar
                request.user.save(force_update=True)
                messages.success(
                    request,
                    _("Your avatar has been changed to one from gallery."),
                    'usercp_avatar')
                return redirect(reverse('usercp_avatar'))
            message = Message(_("Selected Avatar is incorrect."),
                              messages.ERROR)
        else:
            message = Message(_("Request authorisation is invalid."),
                              messages.ERROR)

    return render_to_response('usercp/avatar_gallery.html',
                              context_instance=RequestContext(
                                  request, {
                                      'message': message,
                                      'galleries': galleries,
                                      'tab': 'avatar'
                                  }))
Пример #20
0
 def post_action_undelete(self, ids):
     undeleted = []
     for post in self.posts:
         if post.pk in ids and post.deleted:
             undeleted.append(post.pk)
     if undeleted:
         self.thread.post_set.filter(id__in=undeleted).update(deleted=False, current_date=timezone.now())
         self.thread.sync()
         self.thread.save(force_update=True)
         self.forum.sync()
         self.forum.save(force_update=True)
         messages.success(self.request, _("Selected posts have been restored."), "threads")
     else:
         messages.info(self.request, _("No posts were restored."), "threads")
Пример #21
0
def signout(request):
    user = request.user
    request.session.sign_out(request)
    messages.info(request, _("You have been signed out."), 'security')
    if request.firewall.admin:
        return redirect(reverse(site.get_admin_index()))
    else:
        ranks_online = cache.get('ranks_online', 'nada')
        if ranks_online != 'nada':
            for rank in ranks_online:
                if rank['id'] == user.rank_id:
                    cache.delete('ranks_online')
                    break
    return redirect(reverse('index'))
Пример #22
0
 def post_action_unprotect(self, ids):
     unprotected = 0
     for post in self.posts:
         if post.pk in ids and post.protected:
             unprotected += 1
     if unprotected:
         self.thread.post_set.filter(id__in=ids).update(protected=False)
         messages.success(
             self.request,
             _('Protection from editions has been removed from selected posts.'
               ), 'threads')
     else:
         messages.info(self.request, _('No posts were unprotected.'),
                       'threads')
Пример #23
0
 def post_action_protect(self, ids):
     protected = 0
     for post in self.posts:
         if post.pk in ids and not post.protected:
             protected += 1
     if protected:
         self.thread.post_set.filter(id__in=ids).update(protected=True)
         messages.success(
             self.request,
             _('Selected posts have been protected from edition.'),
             'threads')
     else:
         messages.info(self.request, _('No posts were protected.'),
                       'threads')
Пример #24
0
    def __call__(self, request, target=None, slug=None):
        self.request = request

        # Fetch target
        model = None
        if target:
            model = self.get_and_validate_target(target)
            self.original_name = self.get_target_name(model)
            if not model:
                return redirect(self.get_fallback_link())
        original_model = model

        message = None
        if request.method == 'POST':
            if request.csrf.request_secure(request):
                if model.attachment_set.count():
                    deleted = 0
                    for attachment in model.attachment_set.iterator():
                        attachment.delete()
                        deleted += 1
                    messages.success(request, ungettext(
                                                        'Attachment type and one attachment has been deleted.',
                                                        'Attachment type and %(deleted)d attachments have been deleted.',
                                                        deleted
                                                        ) % {'deleted': deleted}, self.admin.id)
                else:
                    messages.info(request, _("Attachment type has been deleted."), self.admin.id)
                model.delete()
                AttachmentType.objects.flush_cache()
                return redirect(reverse('admin_attachments_types'))
            else:
                message = Message(_("Request authorization is invalid. Please resubmit your form."), messages.ERROR)

        return render_to_response(self.get_template(),
                                  {
                                  'admin': self.admin,
                                  'action': self,
                                  'request': request,
                                  'link': self.get_link(model),
                                  'fallback': self.get_fallback_link(),
                                  'messages': messages.get_messages(request, self.admin.id),
                                  'message': message,
                                  'tabbed': self.tabbed,
                                  'attachments_count': model.attachment_set.count(),
                                  'target': self.get_target_name(original_model),
                                  'target_model': original_model,
                                  },
                                  context_instance=RequestContext(request));
Пример #25
0
 def post_action_accept(self, ids):
     accepted = 0
     for post in self.posts:
         if post.pk in ids and post.moderated:
             accepted += 1
     if accepted:
         self.thread.post_set.filter(id__in=ids).update(moderated=False)
         self.thread.sync()
         self.thread.save(force_update=True)
         messages.success(
             self.request,
             _('Selected posts have been accepted and made visible to other members.'
               ), 'threads')
     else:
         messages.info(self.request, _('No posts were accepted.'),
                       'threads')
Пример #26
0
    def action_prefix(self, ids, prefix):
        prefixes = self.prefixes
        try:
            prefix = int(prefix)
        except TypeError:
            prefix = 0
        prefix = prefix or None

        if prefix:
            if self._action_set_prefix(ids, prefixes[prefix]):
                messages.success(self.request, _('Selected threads prefix has been changed to "%(name)s".') % {'name': _(prefixes[prefix].name)}, 'threads')
            else:
                messages.info(self.request, _('No threads prefix was changed.'), 'threads')
        else:
            if self._action_remove_prefix(ids):
                messages.success(self.request, _('Selected threads prefix has been removed.'), 'threads')
            else:
                messages.info(self.request, _('No threads prefixes were removed.'), 'threads')
Пример #27
0
 def post_action_hard(self, ids):
     deleted = []
     for post in self.posts:
         if post.pk in ids:
             if post.pk == self.thread.start_post_id:
                 raise forms.ValidationError(_("You cannot delete first post of thread using this action. If you want to delete thread, use thread moderation instead."))
             deleted.append(post.pk)
     if deleted:
         for post in self.posts:
             if post.pk in deleted:
                 post.delete()
         self.thread.sync()
         self.thread.save(force_update=True)
         self.forum.sync()
         self.forum.save(force_update=True)
         messages.success(self.request, _('Selected posts have been deleted.'), 'threads')
     else:
         messages.info(self.request, _('No posts were deleted.'), 'threads')
Пример #28
0
def resync_forums(request, forum=0, progress=0):
    progress = int(progress)
    forums = request.session.get('sync_forums')
    if not forums:
        messages.info(request, _('No forums to resynchronize.'), 'forums')
        return redirect(reverse('admin_forums'))
    try:
        if not forum:
            forum = request.session['sync_forums'].pop()
        forum = Forum.objects.get(id=forum)
    except Forum.DoesNotExist:
        del request.session['sync_forums']
        messages.error(request, _('Forum for resynchronization does not exist.'), 'forums')
        return redirect(reverse('admin_forums'))

    # Sync 50 threads
    threads_total = forum.thread_set.count()
    for thread in forum.thread_set.all()[progress:(progress+1)]:
        thread.sync()
        thread.save(force_update=True)
        progress += 1

    if not threads_total:
        return redirect(django_reverse('admin_forums_resync'))

    # Render Progress
    response = render_to_response('processing.html',
                                  {
                                   'task_name': _('Resynchronizing Forums'),
                                   'target_name': forum.name,
                                   'message': _('Resynchronized %(progress)s from %(total)s threads') % {'progress': progress, 'total': threads_total},
                                   'progress': progress * 100 / threads_total,
                                   'cancel_link': reverse('admin_forums'),
                                   },
                                  context_instance=RequestContext(request));

    # Redirect where to?
    if progress >= threads_total:
        forum.sync()
        forum.save(force_update=True)
        response['refresh'] = '2;url=%s' % django_reverse('admin_forums_resync')
    else:
        response['refresh'] = '2;url=%s' % django_reverse('admin_forums_resync', kwargs={'forum': forum.pk, 'progress': progress})
    return response
Пример #29
0
def gallery(request):
    if not 'gallery' in settings.avatars_types:
        return error404(request)

    allowed_avatars = []
    galleries = []
    for directory in path(settings.STATICFILES_DIRS[0]).joinpath('avatars').dirs():
        if directory[-7:] != '_locked' and directory[-8:] != '_default':
            gallery = {'name': directory[-7:], 'avatars': []}
            avatars = directory.files('*.gif')
            avatars += directory.files('*.jpg')
            avatars += directory.files('*.jpeg')
            avatars += directory.files('*.png')
            for item in avatars:
                gallery['avatars'].append('/'.join(path(item).splitall()[-2:]))
            galleries.append(gallery)
            allowed_avatars += gallery['avatars']

    if not allowed_avatars:
        messages.info(request, _("No avatar galleries are available at the moment."), 'usercp_avatar')
        return redirect(reverse('usercp_avatar'))

    message = request.messages.get_message('usercp_avatar')
    if request.method == 'POST':
        if request.csrf.request_secure(request):
            new_avatar = request.POST.get('avatar_image')
            if new_avatar in allowed_avatars:
                request.user.delete_avatar()
                request.user.avatar_type = 'gallery'
                request.user.avatar_image = new_avatar
                request.user.save(force_update=True)
                messages.success(request, _("Your avatar has been changed to one from gallery."), 'usercp_avatar')
                return redirect(reverse('usercp_avatar'))
            message = Message(_("Selected Avatar is incorrect."), messages.ERROR)
        else:
            message = Message(_("Request authorisation is invalid."), messages.ERROR)

    return render_to_response('usercp/avatar_gallery.html',
                              context_instance=RequestContext(request, {
                                  'message': message,
                                  'galleries': galleries,
                                  'tab': 'avatar'}));
Пример #30
0
 def post_action_hard(self, ids):
     deleted = []
     for post in self.posts:
         if post.pk in ids:
             if post.pk == self.thread.start_post_id:
                 raise forms.ValidationError(
                     _("You cannot delete first post of thread using this action. If you want to delete thread, use thread moderation instead."
                       ))
             deleted.append(post.pk)
     if deleted:
         for post in self.posts:
             if post.pk in deleted:
                 post.delete()
         self.thread.sync()
         self.thread.save(force_update=True)
         self.forum.sync()
         self.forum.save(force_update=True)
         messages.success(self.request,
                          _('Selected posts have been deleted.'), 'threads')
     else:
         messages.info(self.request, _('No posts were deleted.'), 'threads')
Пример #31
0
 def post_action_undelete(self, ids):
     undeleted = []
     for post in self.posts:
         if post.pk in ids and post.deleted:
             undeleted.append(post.pk)
     if undeleted:
         update_kwargs = {
             'deleted': False,
             'current_date': timezone.now(),
             'edit_user': self.request.user,
             'edit_user_name': self.request.user.username,
             'edit_user_slug': self.request.user.username_slug,
         }
         self.thread.post_set.filter(id__in=undeleted).update(**update_kwargs)
         self.thread.sync()
         self.thread.save(force_update=True)
         self.forum.sync()
         self.forum.save(force_update=True)
         messages.success(self.request, _('Selected posts have been restored.'), 'threads')
     else:
         messages.info(self.request, _('No posts were restored.'), 'threads')
Пример #32
0
 def make_jump(self):
     target_user = int(self.request.POST.get('user', 0))
     if (not (self.request.user.pk == self.thread.start_poster_id or
             self.request.acl.private_threads.is_mod()) and
             target_user != self.request.user.pk):
         raise ACLError403(_("You don't have permission to remove discussion participants."))
     try:
         user = self.thread.participants.get(id=target_user)
         self.thread.participants.remove(user)
         self.thread.threadread_set.filter(id=user.pk).delete()
         self.thread.watchedthread_set.filter(id=user.pk).delete()
         user.sync_pds = True
         user.save(force_update=True)
         # If there are no more participants in thread, remove it
         if self.thread.participants.count() == 0:
             self.thread.delete()
             messages.info(self.request, _('Thread has been deleted because last participant left it.'), 'threads')
             return self.threads_list_redirect()
         # Nope, see if we removed ourselves
         if user.pk == self.request.user.pk:
             self.thread.set_checkpoint(self.request, 'left')
             messages.info(self.request, _('You have left the "%(thread)s" thread.') % {'thread': self.thread.name}, 'threads')
             return self.threads_list_redirect()
         # Nope, somebody else removed user
         user.sync_pds = True
         user.save(force_update=True)
         self.thread.set_checkpoint(self.request, 'removed', user)
         messages.info(self.request, _('Selected participant was removed from thread.'), 'threads')
         return self.retreat_redirect()
     except User.DoesNotExist:
         messages.error(self.request, _('Requested thread participant does not exist.'), 'threads')
         return self.retreat_redirect()
Пример #33
0
 def make_jump(self):
     username = slugify(self.request.POST.get('username', '').strip())
     if not username:
         messages.error(self.request, _('You have to enter name of user you want to invite to thread.'), 'threads')
         return self.retreat_redirect()
     try:
         user = User.objects.get(username_slug=username)
         acl = user.acl()
         if user in self.thread.participants.all():
             if user.pk == self.request.user.pk:
                 messages.error(self.request, _('You cannot add yourself to this thread.'), 'threads')
             else:
                 messages.info(self.request, _('%(user)s is already participating in this thread.') % {'user': user.username}, 'threads')
         elif not acl.private_threads.can_participate():
             messages.info(self.request, _('%(user)s cannot participate in private threads.') % {'user': user.username}, 'threads')
         elif (not self.request.acl.private_threads.can_invite_ignoring() and
                 not user.allow_pd_invite(self.request.user)):
             messages.info(self.request, _('%(user)s restricts who can invite him to private threads.') % {'user': user.username}, 'threads')
         else:
             self.thread.participants.add(user)
             user.sync_pds = True
             user.save(force_update=True)
             user.email_user(self.request, 'private_thread_invite', _("You've been invited to private thread \"%(thread)s\" by %(user)s") % {'thread': self.thread.name, 'user': self.request.user.username}, {'author': self.request.user, 'thread': self.thread})
             self.thread.set_checkpoint(self.request, 'invited', user)
             messages.success(self.request, _('%(user)s has been added to this thread.') % {'user': user.username}, 'threads')
     except User.DoesNotExist:
         messages.error(self.request, _('User with requested username could not be found.'), 'threads')
     return self.retreat_redirect()
Пример #34
0
 def post_action_soft(self, ids):
     deleted = []
     for post in self.posts:
         if post.pk in ids and not post.deleted:
             if post.pk == self.thread.start_post_id:
                 raise forms.ValidationError(
                     _(
                         "You cannot delete first post of thread using this action. If you want to delete thread, use thread moderation instead."
                     )
                 )
             deleted.append(post.pk)
     if deleted:
         self.thread.post_set.filter(id__in=deleted).update(
             deleted=True, current_date=timezone.now(), delete_date=timezone.now()
         )
         self.thread.sync()
         self.thread.save(force_update=True)
         self.forum.sync()
         self.forum.save(force_update=True)
         messages.success(self.request, _("Selected posts have been hidden."), "threads")
     else:
         messages.info(self.request, _("No posts were hidden."), "threads")
Пример #35
0
 def action_leave(self, ids):
     left = 0
     for thread in self.threads:
         if thread.pk in ids:
             try:
                 user = thread.participants.get(id=self.request.user.pk)
                 thread.participants.remove(user)
                 thread.threadread_set.filter(id=user.pk).delete()
                 thread.watchedthread_set.filter(id=user.pk).delete()
                 user.sync_pds = True
                 user.save(force_update=True)
                 left +=1
                 # If there are no more participants in thread, remove it
                 if thread.participants.count() == 0:
                     thread.delete()
                 # Nope, see if we removed ourselves
                 else:
                     thread.set_checkpoint(self.request, 'left')
             except User.DoesNotExist:
                 pass
     if left:
         messages.success(self.request, _('You have left selected private threads.'), 'threads')
     else:
         messages.info(self.request, _('You have left no private threads.'), 'threads')
Пример #36
0
 def post_action_soft(self, ids):
     deleted = []
     for post in self.posts:
         if post.pk in ids and not post.deleted:
             if post.pk == self.thread.start_post_id:
                 raise forms.ValidationError(_("You cannot delete first post of thread using this action. If you want to delete thread, use thread moderation instead."))
             deleted.append(post.pk)
     if deleted:
         update_kwargs = {
             'deleted': True,
             'current_date': timezone.now(),
             'delete_date': timezone.now(),
             'edit_user': self.request.user,
             'edit_user_name': self.request.user.username,
             'edit_user_slug': self.request.user.username_slug,
         }
         self.thread.post_set.filter(id__in=deleted).update(**update_kwargs)
         self.thread.sync()
         self.thread.save(force_update=True)
         self.forum.sync()
         self.forum.save(force_update=True)
         messages.success(self.request, _('Selected posts have been hidden.'), 'threads')
     else:
         messages.info(self.request, _('No posts were hidden.'), 'threads')
Пример #37
0
 def action_normal(self, ids):
     if self._action_normal(ids):
         messages.success(self.request, _("Selected threads weight has been removed."), "threads")
     else:
         messages.info(self.request, _("No threads have had their weight removed."), "threads")
Пример #38
0
 def action_close(self, ids):
     if self._action_close(ids):
         messages.success(self.request, _("Selected threads have been closed."), "threads")
     else:
         messages.info(self.request, _("No threads were closed."), "threads")
Пример #39
0
    def __call__(self, request, page=0):
        """
        Use widget as view
        """
        self.request = request

        # Get basic list items
        items_total = self.get_items()

        # Set extra filters?
        try:
            items_total = self.select_items(items_total).count()
        except AttributeError:
            items_total = items_total.count()

        # Set sorting and paginating
        sorting_method = self.get_sorting()
        try:
            paginating_method = self.get_pagination(items_total, page)
        except Http404:
            return redirect(self.get_link())

        # List items
        items = self.get_items()
        if not request.session.get(self.get_token('filter')):
            items = items.all()

        # Set extra filters?
        try:
            items = self.select_items(items)
        except AttributeError:
            pass

        # Sort them
        items = self.sort_items(items, sorting_method)

        # Set pagination
        if self.pagination:
            items = items[paginating_method['start']:paginating_method['stop']]

        # Prefetch related?
        try:
            items = self.prefetch_related(items)
        except AttributeError:
            pass

        # Default message
        message = None

        # See if we should make and handle search form
        search_form = None
        SearchForm = self.get_search_form()
        if SearchForm:
            if request.method == 'POST':
                # New search
                if request.POST.get('origin') == 'search':
                    search_form = SearchForm(request.POST, request=request)
                    if search_form.is_valid():
                        search_criteria = {}
                        for field, criteria in search_form.cleaned_data.items(
                        ):
                            if len(criteria) > 0:
                                search_criteria[field] = criteria
                        if not search_criteria:
                            message = Message(
                                _("No search criteria have been defined."))
                        else:
                            request.session[self.get_token(
                                'filter')] = search_criteria
                            return redirect(self.get_link())
                    else:
                        message = Message(_("Search form contains errors."))
                    message.level = messages.ERROR
                else:
                    search_form = SearchForm(request=request)

                # Kill search
                if request.POST.get(
                        'origin'
                ) == 'clear' and self.is_filtering and request.csrf.request_secure(
                        request):
                    request.session[self.get_token('filter')] = None
                    messages.info(request,
                                  _("Search criteria have been cleared."),
                                  self.admin.id)
                    return redirect(self.get_link())
            else:
                if self.is_filtering:
                    search_form = SearchForm(request=request,
                                             initial=request.session.get(
                                                 self.get_token('filter')))
                else:
                    search_form = SearchForm(request=request)

        # See if we sould make and handle tab form
        table_form = None
        TableForm = self.get_table_form(items)
        if TableForm:
            if request.method == 'POST' and request.POST.get(
                    'origin') == 'table':
                table_form = TableForm(request.POST, request=request)
                if table_form.is_valid():
                    message, redirect_link = self.table_action(
                        items, table_form.cleaned_data)
                    if redirect_link:
                        messages.add_message(request, message.level, message,
                                             self.admin.id)
                        return redirect(redirect_link)
                else:
                    message = Message(table_form.non_field_errors()[0],
                                      messages.ERROR)
            else:
                table_form = TableForm(request=request)

        # See if we should make and handle list form
        list_form = None
        ListForm = self.get_actions_form(items)
        if ListForm:
            if request.method == 'POST' and request.POST.get(
                    'origin') == 'list':
                list_form = ListForm(request.POST, request=request)
                if list_form.is_valid():
                    try:
                        form_action = getattr(
                            self,
                            'action_' + list_form.cleaned_data['list_action'])
                        message, redirect_link = form_action(
                            items, [
                                int(x)
                                for x in list_form.cleaned_data['list_items']
                            ])
                        if redirect_link:
                            messages.add_message(request, message.level,
                                                 message, self.admin.id)
                            return redirect(redirect_link)
                    except AttributeError:
                        message = Message(_("Requested action is incorrect."))
                else:
                    if 'list_items' in list_form.errors:
                        message = Message(self.nothing_checked_message)
                    elif 'list_action' in list_form.errors:
                        message = Message(_("Requested action is incorrect."))
                    else:
                        message = Message(list_form.non_field_errors()[0])
                message.level = messages.ERROR
            else:
                list_form = ListForm(request=request)

        # Little hax to keep counters correct
        items_shown = len(items)
        if items_total < items_shown:
            items_total = items_shown

        # Render list
        return render_to_response(self.get_template(),
                                  self.add_template_variables({
                                      'admin':
                                      self.admin,
                                      'action':
                                      self,
                                      'request':
                                      request,
                                      'link':
                                      self.get_link(),
                                      'messages_log':
                                      messages.get_messages(
                                          request, self.admin.id),
                                      'message':
                                      message,
                                      'sorting':
                                      self.sortables,
                                      'sorting_method':
                                      sorting_method,
                                      'pagination':
                                      paginating_method,
                                      'list_form':
                                      list_form or None,
                                      'search_form':
                                      search_form or None,
                                      'table_form':
                                      table_form or None,
                                      'items':
                                      items,
                                      'items_total':
                                      items_total,
                                      'items_shown':
                                      items_shown,
                                  }),
                                  context_instance=RequestContext(request))
Пример #40
0
def form(request):
    #if settings.account_activation == 'block':
    return redirect_message(
        request, messages.INFO,
        _("We are sorry but we don't allow new members registrations at this time."
          ))

    message = None
    if request.method == 'POST':
        form = UserRegisterForm(request.POST, request=request)
        if form.is_valid():
            need_activation = 0
            if settings.account_activation == 'user':
                need_activation = User.ACTIVATION_USER
            if settings.account_activation == 'admin':
                need_activation = User.ACTIVATION_ADMIN

            new_user = User.objects.create_user(
                form.cleaned_data['username'],
                form.cleaned_data['email'],
                form.cleaned_data['password'],
                ip=request.session.get_ip(request),
                agent=request.META.get('HTTP_USER_AGENT'),
                activation=need_activation,
                request=request)

            if need_activation == User.ACTIVATION_NONE:
                # Sign in user
                sign_user_in(request, new_user)
                messages.success(
                    request,
                    _("Welcome aboard, %(username)s! Your account has been registered successfully."
                      ) % {'username': new_user.username})

            if need_activation == User.ACTIVATION_USER:
                # Mail user activation e-mail
                messages.info(
                    request,
                    _("%(username)s, your account has been registered, but you will have to activate it before you will be able to sign-in. We have sent you an e-mail with activation link."
                      ) % {'username': new_user.username})
                new_user.email_user(
                    request,
                    'users/activation/user',
                    _("Welcome aboard, %(username)s!") %
                    {'username': new_user.username},
                )

            if need_activation == User.ACTIVATION_ADMIN:
                # Require admin activation
                messages.info(
                    request,
                    _("%(username)s, Your account has been registered, but you won't be able to sign in until board administrator accepts it. We'll notify when this happens. Thank you for your patience!"
                      ) % {'username': new_user.username})
                new_user.email_user(
                    request, 'users/activation/admin',
                    _("Welcome aboard, %(username)s!") %
                    {'username': new_user.username},
                    {'password': form.cleaned_data['password']})

            User.objects.resync_monitor()
            return redirect(reverse('index'))
        else:
            message = Message(form.non_field_errors()[0], messages.ERROR)
            if settings.registrations_jams:
                SignInAttempt.objects.register_attempt(
                    request.session.get_ip(request))
            # Have we jammed our account?
            if SignInAttempt.objects.is_jammed(
                    request.session.get_ip(request)):
                request.jam.expires = timezone.now()
                return redirect(reverse('register'))
    else:
        form = UserRegisterForm(request=request)
    return render_to_response('register.html', {
        'message': message,
        'form': form,
        'hide_signin': True,
    },
                              context_instance=RequestContext(request))
Пример #41
0
 def action_undelete(self, ids):
     if self._action_undelete(ids):
         messages.success(self.request, _('Selected reports have been restored.'), 'threads')
     else:
         messages.info(self.request, _('No reports were restored.'), 'threads')
Пример #42
0
        def view(request):
            report = None
            made_report = False
            if self.post.reported:
                report = self.post.live_report()

                if report and report.start_poster_id != request.user.pk:
                    # Append our q.q to existing report?
                    try:
                        report.checkpoint_set.get(user=request.user,
                                                  action="reported")
                    except Checkpoint.DoesNotExist:
                        report.set_checkpoint(request, 'reported',
                                              request.useruser)
                        self.post.add_reporter(request.user)
                        self.post.save(force_update=True)
                    made_report = True

            if not report:
                # File up new report
                now = timezone.now()

                reason_post = _('''
Member @%(reporter)s has reported following post by @%(reported)s:

%(quote)s
**Post link:** <%(post)s>
''')

                reason_post = reason_post.strip() % {
                    'reporter':
                    request.user.username,
                    'reported':
                    self.post.user_name,
                    'post':
                    settings.BOARD_ADDRESS +
                    self.redirect_to_post(self.post)['Location'],
                    'quote':
                    self.post.quote(),
                }

                md, reason_post_preparsed = post_markdown(reason_post)

                reports = Forum.objects.special_model('reports')
                report = Thread.objects.create(
                    forum=reports,
                    weight=2,
                    name=self.thread.name,
                    slug=slugify(self.thread.slug),
                    start=now,
                    start_poster=request.user,
                    start_poster_name=request.user.username,
                    start_poster_slug=request.user.username_slug,
                    start_poster_style=request.user.rank.style,
                    last=now,
                    last_poster=request.user,
                    last_poster_name=request.user.username,
                    last_poster_slug=request.user.username_slug,
                    last_poster_style=request.user.rank.style,
                    report_for=self.post,
                )

                reason = Post.objects.create(
                    forum=reports,
                    thread=report,
                    user=request.user,
                    user_name=request.user.username,
                    ip=request.session.get_ip(self.request),
                    agent=request.META.get('HTTP_USER_AGENT'),
                    post=reason_post,
                    post_preparsed=reason_post_preparsed,
                    date=now,
                )

                report.start_post = reason
                report.last_post = reason
                report.save(force_update=True)

                for m in self.post.mentions.all():
                    reason.mentions.add(m)

                self.post.reported = True
                self.post.add_reporter(self.request.user)
                self.post.save(force_update=True)
                self.thread.replies_reported += 1
                self.thread.save(force_update=True)
                with UpdatingMonitor() as cm:
                    monitor.increase('reported_posts')
                made_report = True

            if made_report:
                if request.is_ajax():
                    return json_response(
                        request,
                        message=
                        _("Selected post has been reported and will receive moderator attention. Thank you."
                          ))
                messages.info(
                    request,
                    _("Selected post has been reported and will receive moderator attention. Thank you."
                      ), 'threads_%s' % self.post.pk)
            else:
                if request.is_ajax():
                    return json_response(
                        request,
                        message=
                        _("You have already reported this post. One of moderators will handle it as soon as it is possible. Thank you for your patience."
                          ))
                messages.info(
                    request,
                    _("You have already reported this post. One of moderators will handle it as soon as it is possible. Thank you for your patience."
                      ), 'threads_%s' % self.post.pk)

            return self.redirect_to_post(self.post)
Пример #43
0
 def action_soft(self, ids):
     if self._action_soft(ids):
         messages.success(self.request, _("Selected threads have been hidden."), "threads")
     else:
         messages.info(self.request, _("No threads were hidden."), "threads")
Пример #44
0
 def action_soft(self, ids):
     if self._action_soft(ids):
         self.mass_resolve(ids)
         messages.success(self.request, _('Selected reports have been hidden.'), 'threads')
     else:
         messages.info(self.request, _('No reports were hidden.'), 'threads')
Пример #45
0
 def action_hard(self, ids):
     if self._action_hard(ids):
         messages.success(self.request, _('Selected reports have been deleted.'), 'threads')
     else:
         messages.info(self.request, _('No reports were deleted.'), 'threads')
Пример #46
0
 def action_hard(self, ids):
     if self._action_hard(ids):
         messages.success(self.request, _("Selected threads have been deleted."), "threads")
     else:
         messages.info(self.request, _("No threads were deleted."), "threads")
Пример #47
0
 def action_sticky(self, ids):
     if self._action_sticky(ids):
         messages.success(self.request, _("Selected threads have been sticked to the top of list."), "threads")
     else:
         messages.info(self.request, _("No threads were turned into stickies."), "threads")
Пример #48
0
 def action_annouce(self, ids):
     if self._action_annouce(ids):
         messages.success(self.request, _("Selected threads have been turned into announcements."), "threads")
     else:
         messages.info(self.request, _("No threads were turned into announcements."), "threads")
Пример #49
0
def form(request):
    if settings.account_activation == "block":
        return redirect_message(
            request, messages.INFO, _("We are sorry but we don't allow new members registrations at this time.")
        )

    message = None
    if request.method == "POST":
        form = UserRegisterForm(request.POST, request=request)
        if form.is_valid():
            need_activation = 0
            if settings.account_activation == "user":
                need_activation = User.ACTIVATION_USER
            if settings.account_activation == "admin":
                need_activation = User.ACTIVATION_ADMIN

            new_user = User.objects.create_user(
                form.cleaned_data["username"],
                form.cleaned_data["email"],
                form.cleaned_data["password"],
                ip=request.session.get_ip(request),
                agent=request.META.get("HTTP_USER_AGENT"),
                activation=need_activation,
                request=request,
            )

            if need_activation == User.ACTIVATION_NONE:
                # Sign in user
                sign_user_in(request, new_user)
                messages.success(
                    request,
                    _("Welcome aboard, %(username)s! Your account has been registered successfully.")
                    % {"username": new_user.username},
                )

            if need_activation == User.ACTIVATION_USER:
                # Mail user activation e-mail
                messages.info(
                    request,
                    _(
                        "%(username)s, your account has been registered, but you will have to activate it before you will be able to sign-in. We have sent you an e-mail with activation link."
                    )
                    % {"username": new_user.username},
                )
                new_user.email_user(
                    request,
                    "users/activation/user",
                    _("Welcome aboard, %(username)s!") % {"username": new_user.username},
                )

            if need_activation == User.ACTIVATION_ADMIN:
                # Require admin activation
                messages.info(
                    request,
                    _(
                        "%(username)s, Your account has been registered, but you won't be able to sign in until board administrator accepts it. We'll notify when this happens. Thank you for your patience!"
                    )
                    % {"username": new_user.username},
                )
                new_user.email_user(
                    request,
                    "users/activation/admin",
                    _("Welcome aboard, %(username)s!") % {"username": new_user.username},
                    {"password": form.cleaned_data["password"]},
                )

            User.objects.resync_monitor()
            return redirect(reverse("index"))
        else:
            message = Message(form.non_field_errors()[0], messages.ERROR)
            if settings.registrations_jams:
                SignInAttempt.objects.register_attempt(request.session.get_ip(request))
            # Have we jammed our account?
            if SignInAttempt.objects.is_jammed(request.session.get_ip(request)):
                request.jam.expires = timezone.now()
                return redirect(reverse("register"))
    else:
        form = UserRegisterForm(request=request)
    return render_to_response(
        "register.html",
        {"message": message, "form": form, "hide_signin": True},
        context_instance=RequestContext(request),
    )
Пример #50
0
 def action_normal(self, ids):
     if self._action_normal(ids):
         self.mass_resolve(ids)
         messages.success(self.request, _('Selected reports were set as bogus.'), 'threads')
     else:
         messages.info(self.request, _('No reports were set as bogus.'), 'threads')