Exemplo n.º 1
0
def activate(request, token):
    new_credentials = request.session.get("new_credentials")
    if not new_credentials or new_credentials["token"] != token:
        return error404(request)

    if new_credentials["new_email"]:
        request.user.set_email(new_credentials["new_email"])
    if new_credentials["new_password"]:
        request.user.set_password(new_credentials["new_password"])

    try:
        request.user.full_clean()
        request.user.save(force_update=True)
        request.user.sessions.exclude(id=request.session.id).delete()
        request.user.signin_tokens.all().delete()
        messages.success(
            request,
            _("%(username)s, your Sign-In credentials have been changed.") % {"username": request.user.username},
            "security",
        )
        request.session.sign_out(request)
        del request.session["new_credentials"]
        return redirect(reverse("sign_in"))
    except ValidationError:
        messages.error(
            request, _("Your new credentials have been invalidated. Please try again."), "usercp_credentials"
        )
        return redirect(reverse("usercp_credentials"))
Exemplo n.º 2
0
        def view(request):
            self.fetch_poll()

            if 'show_results' in request.POST:
                if not self.poll.user_votes:
                    self.poll.make_empty_vote(request)
                    self.poll.save()
                return self.poll_redirect()

            if 'show_options' in request.POST:
                if self.poll.user_votes and not self.poll.user_votes[0].option_id:
                    self.poll.retract_votes(self.poll.user_votes)
                    self.poll.save()
                return self.poll_redirect()

            if 'change_vote' in request.POST:
                if self.poll.user_votes and self.poll.user_votes[0].option_id and self.poll.vote_changing:
                    self.poll.retract_votes(self.poll.user_votes)
                    self.poll.save()
                return self.poll_redirect()

            if self.poll.user_votes and self.poll.user_votes[0].option_id and not self.poll.vote_changing:
                messages.error(_("Changing vote in this poll is not allowed."), 'poll_%s' % self.poll.pk)
                return self.poll_redirect()

            form = PollVoteForm(self.request.POST, request=self.request, poll=self.poll)
            if form.is_valid():
                if self.poll.user_votes:
                    self.poll.retract_votes(self.poll.user_votes)
                self.poll.make_vote(self.request, form.cleaned_data['options'])
                self.poll.save()
                messages.success(self.request, _("Your vote has been cast."), 'poll_%s' % self.poll.pk)
            elif 'options' in form.errors:
                messages.error(self.request, form.errors['options'][0], 'poll_%s' % self.poll.pk)
            return self.poll_redirect()
Exemplo n.º 3
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()
Exemplo n.º 4
0
def activate(request, token):
    new_credentials = request.session.get('new_credentials')
    if not new_credentials or new_credentials['token'] != token:
        return error404(request)

    if new_credentials['new_email']:
        request.user.set_email(new_credentials['new_email'])
    if new_credentials['new_password']:
        request.user.set_password(new_credentials['new_password'])

    try:
        request.user.full_clean()
        request.user.save(force_update=True)
        request.user.sessions.exclude(id=request.session.id).delete()
        request.user.signin_tokens.all().delete()
        messages.success(
            request,
            _("%(username)s, your Sign-In credentials have been changed.") %
            {'username': request.user.username}, 'security')
        request.session.sign_out(request)
        del request.session['new_credentials']
        return redirect(reverse('sign_in'))
    except ValidationError:
        messages.error(
            request,
            _("Your new credentials have been invalidated. Please try again."),
            'usercp_credentials')
        return redirect(reverse('usercp_credentials'))
Exemplo n.º 5
0
def crop(request, upload=False):
    if upload and (not request.user.avatar_temp or not 'upload' in settings.avatars_types):
        return error404(request)

    if not upload and request.user.avatar_type != 'upload':
        messages.error(request, _("Crop Avatar option is avaiable only when you use uploaded image as your avatar."), 'usercp_avatar')
        return redirect(reverse('usercp_avatar'))

    message = request.messages.get_message('usercp_avatar')
    if request.method == 'POST':
        if request.csrf.request_secure(request):
            try:
                image_path = settings.MEDIA_ROOT + 'avatars/'
                if upload:
                    source = Image.open(image_path + request.user.avatar_temp)
                else:
                    source = Image.open(image_path + request.user.avatar_original)
                width, height = source.size

                aspect = float(width) / float(request.POST['crop_b'])
                crop_x = int(aspect * float(request.POST['crop_x']))
                crop_y = int(aspect * float(request.POST['crop_y']))
                crop_w = int(aspect * float(request.POST['crop_w']))
                crop = source.crop((crop_x, crop_y, crop_x + crop_w, crop_y + crop_w))

                if upload:
                    image_name, image_extension = path(request.user.avatar_temp).splitext()
                else:
                    image_name, image_extension = path(request.user.avatar_original).splitext()
                image_name = '%s_%s%s' % (request.user.pk, random_string(8), image_extension)
                resizeimage(crop, settings.AVATAR_SIZES[0], image_path + image_name, info=source.info, format=source.format)
                for size in settings.AVATAR_SIZES[1:]:
                    resizeimage(crop, size, image_path + str(size) + '_' + image_name, info=source.info, format=source.format)

                request.user.delete_avatar_image()
                if upload:
                    request.user.delete_avatar_original()
                    request.user.avatar_type = 'upload'
                    request.user.avatar_original = '%s_org_%s%s' % (request.user.pk, random_string(8), image_extension)
                    source.save(image_path + request.user.avatar_original)
                request.user.delete_avatar_temp()
                request.user.avatar_image = image_name
                request.user.avatar_crop = [str(float(request.POST[x])) for x in ('crop_x', 'crop_y', 'crop_w')]
                request.user.save(force_update=True)
                messages.success(request, _("Your avatar has been cropped."), 'usercp_avatar')
                return redirect(reverse('usercp_avatar'))
            except Exception:
                message = Message(_("Form contains errors."), messages.ERROR)
        else:
            message = Message(_("Request authorisation is invalid."), messages.ERROR)


    return render_to_response('usercp/avatar_crop.html',
                              context_instance=RequestContext(request, {
                                  'message': message,
                                  'after_upload': upload,
                                  'avatar_size': settings.AVATAR_SIZES[0],
                                  'avatar_crop': request.user.avatar_crop if not upload else None,
                                  'source': 'avatars/%s' % (request.user.avatar_temp if upload else request.user.avatar_original),
                                  'tab': 'avatar'}));
Exemplo n.º 6
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));
Exemplo n.º 7
0
 def get_and_validate_target(self, target):
     try:
         model = self.admin.model.objects.select_related().get(pk=target)
         self.get_target(model)
         return model
     except self.admin.model.DoesNotExist:
         messages.error(self.request, self.notfound_message, self.admin.id)
     except ValueError as e:
         messages.error(self.request, e.args[0], self.admin.id)
     return None
Exemplo n.º 8
0
 def get_and_validate_target(self, target):
     try:
         model = self.admin.model.objects.select_related().get(pk=target)
         self.get_target(model)
         return model
     except self.admin.model.DoesNotExist:
         messages.error(self.request, self.notfound_message, self.admin.id)
     except ValueError as e:
         messages.error(self.request, e.args[0], self.admin.id)
     return None
Exemplo n.º 9
0
def send(request, target, token):
    try:
        newsletter = Newsletter.objects.get(pk=target, token=token)

        # Build recipients queryset
        recipients = User.objects
        if newsletter.ranks.all():
            recipients = recipients.filter(rank__in=[x.pk for x in newsletter.ranks.all()])
        if not newsletter.ignore_subscriptions:
            recipients = recipients.filter(receive_newsletters=1)

        recipients_total = recipients.count()
        if recipients_total < 1:
            messages.error(request, _('No recipients for newsletter "%(newsletter)s" could be found.') % {'newsletter': newsletter.name}, 'newsletters')
            return redirect(reverse('admin_newsletters'))

        for user in recipients.all()[newsletter.progress:(newsletter.progress + newsletter.step_size)]:
            tokens = {
              '{{ board_name }}': settings.board_name,
              '{{ username }}': user.username,
              '{{ user_link }}': django_reverse('user', kwargs={'username': user.username_slug, 'user': user.pk}),
              '{{ board_link }}': settings.BOARD_ADDRESS,
            }
            subject = newsletter.parse_name(tokens)
            user.email_user(request, 'users/newsletter', subject, {
                                                                'newsletter': newsletter,
                                                                'subject': subject,
                                                                'content_html': newsletter.parse_html(tokens),
                                                                'content_plain': newsletter.parse_plain(tokens),
                                                                })
            newsletter.progress += 1
        newsletter.generate_token()
        newsletter.save(force_update=True)

        if newsletter.progress >= recipients_total:
            newsletter.progress = 0
            newsletter.save(force_update=True)
            messages.success(request, _('Newsletter "%(newsletter)s" has been sent.') % {'newsletter': newsletter.name}, 'newsletters')
            return redirect(reverse('admin_newsletters'))

        # Render Progress
        response = render_to_response('processing.html',
                                      {
                                      'task_name': _('Sending Newsletter'),
                                      'target_name': newsletter.name,
                                      'message': _('Sent to %(progress)s from %(total)s users') % {'progress': newsletter.progress, 'total': recipients_total},
                                      'progress': newsletter.progress * 100 / recipients_total,
                                      'cancel_link': reverse('admin_newsletters'),
                                      },
                                      context_instance=RequestContext(request));
        response['refresh'] = '2;url=%s' % reverse('admin_newsletters_send', newsletter)
        return response
    except Newsletter.DoesNotExist:
        messages.error(request, _('Requested Newsletter could not be found.'), 'newsletters')
        return redirect(reverse('admin_newsletters'))
Exemplo n.º 10
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
Exemplo n.º 11
0
def gravatar(request):
    if not 'gravatar' in settings.avatars_types:
        return error404(request)
    if request.user.avatar_type != 'gravatar':
        if request.csrf.request_secure(request):
            request.user.delete_avatar()
            request.user.avatar_type = 'gravatar'
            request.user.save(force_update=True)
            messages.success(request, _("Your avatar has been changed to Gravatar."), 'usercp_avatar')
        else:
            messages.error(request, _("Request authorisation is invalid."), 'usercp_avatar')
    return redirect(reverse('usercp_avatar'))
Exemplo n.º 12
0
    def dispatch(self, request, **kwargs):
        if ((not self.change.thread_name_old or self.thread.name == self.change.thread_name_old)
            and (self.change.post_content == self.post.post)):
            messages.error(request, _("No changes to revert."), 'changelog')
            return redirect(reverse('%s_changelog_diff' % self.type_prefix, kwargs={'thread': self.thread.pk, 'slug': self.thread.slug, 'post': self.post.pk, 'change': self.change.pk}))
        
        self.post.edits += 1
        self.post.edit_user = self.request.user
        self.post.edit_user_name = self.request.user.username
        self.post.edit_user_slug = self.request.user.username_slug
        
        self.post.change_set.create(
                                    forum=self.forum,
                                    thread=self.thread,
                                    post=self.post,
                                    user=request.user,
                                    user_name=request.user.username,
                                    user_slug=request.user.username_slug,
                                    date=timezone.now(),
                                    ip=request.session.get_ip(self.request),
                                    agent=request.META.get('HTTP_USER_AGENT'),
                                    reason=_("Reverted to the state before %(date)s.") % {'date': reldate(self.change.date).lower()},
                                    size=len(self.change.post_content),
                                    change=len(self.change.post_content) - len(self.post.post),
                                    thread_name_old=self.thread.name if self.change.thread_name_old != self.thread.name and self.change.thread_name_old != None else None,
                                    thread_name_new=self.change.thread_name_old if self.change.thread_name_old != self.thread.name else None,
                                    post_content=self.post.post,
                                    )

        if self.change.thread_name_old and self.change.thread_name_old != self.thread.name:
            self.thread.name = self.change.thread_name_old
            self.thread.slug = slugify(self.change.thread_name_old)
            self.thread.save(force_update=True)

            if self.forum.last_thread_id == self.thread.pk:
                self.forum.last_thread_name = self.change.thread_name_old
                self.forum.last_thread_slug = slugify(self.change.thread_name_old)
                self.forum.save(force_update=True)

        if self.change.post_content != self.post.post:
            self.post.post = self.change.post_content
            md, self.post.post_preparsed = post_markdown(self.change.post_content)

        self.post.save(force_update=True)
        
        messages.success(request, _("Post has been reverted to the state before %(date)s.") % {'date': reldate(self.change.date).lower()}, 'threads_%s' % self.post.pk)
        return self.redirect_to_post(self.post)
Exemplo n.º 13
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
Exemplo n.º 14
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()
Exemplo n.º 15
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)
            if not model:
                return redirect(self.get_fallback_link())
        original_model = model

        # Crash if this is invalid request
        if not request.csrf.request_secure(request):
            messages.error(request, _("Action authorization is invalid."), self.admin.id)
            return redirect(self.get_fallback_link())

        # Do something
        message, url = self.action(model)
        messages.add_message(request, message.level, message, self.admin.id)
        if url:
            return redirect(url)
        return redirect(self.get_fallback_link())
Exemplo n.º 16
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)
            if not model:
                return redirect(self.get_fallback_link())
        original_model = model

        # Crash if this is invalid request
        if not request.csrf.request_secure(request):
            messages.error(request, _("Action authorization is invalid."),
                           self.admin.id)
            return redirect(self.get_fallback_link())

        # Do something
        message, url = self.action(model)
        messages.add_message(request, message.level, message, self.admin.id)
        if url:
            return redirect(url)
        return redirect(self.get_fallback_link())
Exemplo n.º 17
0
    def dispatch(self, request, **kwargs):
        if ((not self.change.thread_name_old or self.thread.name == self.change.thread_name_old)
            and (self.change.post_content == self.post.post)):
            messages.error(request, _("No changes to revert."), 'changelog')
            return redirect(reverse('%s_changelog_diff' % self.type_prefix, kwargs={'thread': self.thread.pk, 'slug': self.thread.slug, 'post': self.post.pk, 'change': self.change.pk}))

        if self.change.thread_name_old and self.change.thread_name_old != self.thread.name:
            self.thread.name = self.change.thread_name_old
            self.thread.slug = slugify(self.change.thread_name_old)
            self.thread.save(force_update=True)

            if self.forum.last_thread_id == self.thread.pk:
                self.forum.last_thread_name = self.change.thread_name_old
                self.forum.last_thread_slug = slugify(self.change.thread_name_old)
                self.forum.save(force_update=True)

        if self.change.post_content != self.post.post:
            self.post.post = self.change.post_content
            md, self.post.post_preparsed = post_markdown(self.change.post_content)
            self.post.save(force_update=True)

        messages.success(request, _("Post has been reverted to state from %(date)s.") % {'date': reldate(self.change.date).lower()}, 'threads_%s' % self.post.pk)
        return self.redirect_to_post(self.post)
Exemplo n.º 18
0
 def __call__(self, request, slug, target):
     self.request = request
     try:
         self.role = Role.objects.get(id=target)
         if self.role and self.role.protected and not request.user.is_god():
             messages.error(request, _('Role "%(name)s" is protected, you cannot edit it.') % {'name': _(self.role.name)}, self.admin.id)
             return redirect(reverse('admin_roles'))
     except Role.DoesNotExist:
         messages.error(request, _('Requested Role could not be found.'), self.admin.id)
         return redirect(reverse('admin_roles'))
     self.roles = ForumRole.objects.order_by('name').all()
     if not self.roles:
         messages.error(request, _('No forum roles are currently set.'), self.admin.id)
         return redirect(reverse('admin_roles'))
     return super(Forums, self).__call__(request)
Exemplo n.º 19
0
 def get_and_validate_target(self, target):
     result = super(ACL, self).get_and_validate_target(target)
     if result and result.protected and not self.request.user.is_god():
         messages.error(self.request, _('Role "%(name)s" is protected, you cannot edit it.') % {'name': _(result.name)}, self.admin.id)
         return None
     return result
Exemplo n.º 20
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))
Exemplo n.º 21
0
    def __call__(self, request, *args, **kwargs):
        if not request.user.is_god():
            messages.error(request, _('Only system administrators can set new pruning policies.'), self.admin.id)
            return redirect(reverse('admin_prune_users'))

        return super(New, self).__call__(request, *args, **kwargs)
Exemplo n.º 22
0
def send(request, target, token):
    try:
        newsletter = Newsletter.objects.get(pk=target, token=token)

        # Build recipients queryset
        recipients = User.objects
        if newsletter.ranks.all():
            recipients = recipients.filter(
                rank__in=[x.pk for x in newsletter.ranks.all()])
        if not newsletter.ignore_subscriptions:
            recipients = recipients.filter(receive_newsletters=1)

        recipients_total = recipients.count()
        if recipients_total < 1:
            messages.error(
                request,
                _('No recipients for newsletter "%(newsletter)s" could be found.'
                  ) % {'newsletter': newsletter.name}, 'newsletters')
            return redirect(reverse('admin_newsletters'))

        for user in recipients.all()[newsletter.progress:(
                newsletter.progress + newsletter.step_size)]:
            tokens = {
                '{{ board_name }}':
                settings.board_name,
                '{{ username }}':
                user.username,
                '{{ user_link }}':
                django_reverse('user',
                               kwargs={
                                   'username': user.username_slug,
                                   'user': user.pk
                               }),
                '{{ board_link }}':
                settings.BOARD_ADDRESS,
            }
            subject = newsletter.parse_name(tokens)
            user.email_user(
                request, 'users/newsletter', subject, {
                    'newsletter': newsletter,
                    'subject': subject,
                    'content_html': newsletter.parse_html(tokens),
                    'content_plain': newsletter.parse_plain(tokens),
                })
            newsletter.progress += 1
        newsletter.generate_token()
        newsletter.save(force_update=True)

        if newsletter.progress >= recipients_total:
            newsletter.progress = 0
            newsletter.save(force_update=True)
            messages.success(
                request,
                _('Newsletter "%(newsletter)s" has been sent.') %
                {'newsletter': newsletter.name}, 'newsletters')
            return redirect(reverse('admin_newsletters'))

        # Render Progress
        response = render_to_response(
            'processing.html', {
                'task_name': _('Sending Newsletter'),
                'target_name': newsletter.name,
                'message': _('Sent to %(progress)s from %(total)s users') % {
                    'progress': newsletter.progress,
                    'total': recipients_total
                },
                'progress': newsletter.progress * 100 / recipients_total,
                'cancel_link': reverse('admin_newsletters'),
            },
            context_instance=RequestContext(request))
        response['refresh'] = '2;url=%s' % reverse('admin_newsletters_send',
                                                   newsletter)
        return response
    except Newsletter.DoesNotExist:
        messages.error(request, _('Requested Newsletter could not be found.'),
                       'newsletters')
        return redirect(reverse('admin_newsletters'))
Exemplo n.º 23
0
    def dispatch(self, request, **kwargs):
        if ((not self.change.thread_name_old
             or self.thread.name == self.change.thread_name_old)
                and (self.change.post_content == self.post.post)):
            messages.error(request, _("No changes to revert."), 'changelog')
            return redirect(
                reverse('%s_changelog_diff' % self.type_prefix,
                        kwargs={
                            'thread': self.thread.pk,
                            'slug': self.thread.slug,
                            'post': self.post.pk,
                            'change': self.change.pk
                        }))

        self.post.edits += 1
        self.post.edit_user = self.request.user
        self.post.edit_user_name = self.request.user.username
        self.post.edit_user_slug = self.request.user.username_slug

        self.post.change_set.create(
            forum=self.forum,
            thread=self.thread,
            post=self.post,
            user=request.user,
            user_name=request.user.username,
            user_slug=request.user.username_slug,
            date=timezone.now(),
            ip=request.session.get_ip(self.request),
            agent=request.META.get('HTTP_USER_AGENT'),
            reason=_("Reverted to the state before %(date)s.") %
            {'date': reldate(self.change.date).lower()},
            size=len(self.change.post_content),
            change=len(self.change.post_content) - len(self.post.post),
            thread_name_old=self.thread.name
            if self.change.thread_name_old != self.thread.name
            and self.change.thread_name_old != None else None,
            thread_name_new=self.change.thread_name_old
            if self.change.thread_name_old != self.thread.name else None,
            post_content=self.post.post,
        )

        if self.change.thread_name_old and self.change.thread_name_old != self.thread.name:
            self.thread.name = self.change.thread_name_old
            self.thread.slug = slugify(self.change.thread_name_old)
            self.thread.save(force_update=True)

            if self.forum.last_thread_id == self.thread.pk:
                self.forum.last_thread_name = self.change.thread_name_old
                self.forum.last_thread_slug = slugify(
                    self.change.thread_name_old)
                self.forum.save(force_update=True)

        if self.change.post_content != self.post.post:
            self.post.post = self.change.post_content
            md, self.post.post_preparsed = post_markdown(
                self.change.post_content)

        self.post.save(force_update=True)

        messages.success(
            request,
            _("Post has been reverted to the state before %(date)s.") %
            {'date': reldate(self.change.date).lower()},
            'threads_%s' % self.post.pk)
        return self.redirect_to_post(self.post)