def action(self, target): target.delete() with UpdatingMonitor() as cm: monitor.increase('acl_version') return Message( _('Forum Role "%(name)s" has been deleted.') % {'name': _(target.name)}, messages.SUCCESS), False
def sync(self): if self._mode == 'snap': with UpdatingMonitor() as cm: if self._members != self._om: monitor['online_members'] = self._members if self._all != self._oa: monitor['online_all'] = self._all
def action_delete(self, items, checked): with UpdatingMonitor() as cm: monitor.increase('acl_version') Role.objects.filter(id__in=checked).delete() return Message( _('Selected forum roles have been deleted successfully.'), messages.SUCCESS), reverse('admin_roles_forums')
def _action_accept(self, ids): accepted = 0 users = [] for thread in self.threads: if thread.pk in ids and thread.moderated: accepted += 1 # Sync thread and post thread.moderated = False thread.replies_moderated -= 1 thread.save(force_update=True) thread.start_post.moderated = False thread.start_post.save(force_update=True) thread.set_checkpoint(self.request, 'accepted') thread.update_current_dates() # Sync user if thread.last_post.user: thread.start_post.user.threads += 1 thread.start_post.user.posts += 1 users.append(thread.start_post.user) if accepted: with UpdatingMonitor() as cm: monitor.increase('threads', accepted) monitor.increase('posts', accepted) self.forum.sync() self.forum.save(force_update=True) for user in users: user.save(force_update=True) return accepted
def after_thread_action_normal(self): self.thread.set_checkpoint(self.request, 'bogus') if self.thread.original_weight == 2: with UpdatingMonitor() as cm: monitor.decrease('reported_posts') messages.success(self.request, _('Report has been set as bogus.'), 'threads')
def submit_form(self, form, target): target.name = form.cleaned_data['name'] if self.request.user.is_god(): target.protected = form.cleaned_data['protected'] target.save(force_update=True) with UpdatingMonitor() as cm: monitor.increase('acl_version') return target, Message(_('Changes in role "%(name)s" have been saved.') % {'name': self.original_name}, messages.SUCCESS)
def resync_monitor(self): with UpdatingMonitor() as cm: monitor['users'] = self.filter(activation=0).count() monitor['users_inactive'] = self.filter(activation__gt=0).count() last_user = self.filter(activation=0).latest('id') monitor['last_user'] = last_user.pk monitor['last_user_name'] = last_user.username monitor['last_user_slug'] = last_user.username_slug
def create_user(self, username, email, password, timezone=False, ip='127.0.0.1', agent='', no_roles=False, activation=0, request=False): token = '' if activation > 0: token = random_string(12) timezone = timezone or settings.default_timezone # Get first rank try: from misago.models import Rank default_rank = Rank.objects.filter(special=0).order_by('-order')[0] except IndexError: default_rank = None # Store user in database new_user = User( last_sync=tz_util.now(), join_date=tz_util.now(), join_ip=ip, join_agent=agent, activation=activation, token=token, timezone=timezone, rank=default_rank, subscribe_start=settings.subscribe_start, subscribe_reply=settings.subscribe_reply, ) validate_username(username) validate_password(password) new_user.set_username(username) new_user.set_email(email) new_user.set_password(password) new_user.full_clean() new_user.default_avatar() new_user.save(force_insert=True) # Set user roles? if not no_roles: from misago.models import Role new_user.roles.add(Role.objects.get(_special='registered')) new_user.make_acl_key() new_user.save(force_update=True) # Update forum stats with UpdatingMonitor() as cm: if activation == 0: monitor.increase('users') monitor['last_user'] = new_user.pk monitor['last_user_name'] = new_user.username monitor['last_user_slug'] = new_user.username_slug else: monitor.increase('users_inactive') # Return new user return new_user
def submit_form(self, form, target): target.test = form.cleaned_data['test'] target.ban = form.cleaned_data['ban'] target.reason_user = form.cleaned_data['reason_user'] target.reason_admin = form.cleaned_data['reason_admin'] target.expires = form.cleaned_data['expires'] target.save(force_update=True) with UpdatingMonitor() as cm: monitor.increase('bans_version') return target, Message(_('Changes in ban have been saved.'), messages.SUCCESS)
def submit_form(self, form, target): raw_acl = target.permissions for perm in form.cleaned_data: raw_acl[perm] = form.cleaned_data[perm] target.permissions = raw_acl target.save(force_update=True) with UpdatingMonitor() as cm: monitor.increase('acl_version') return target, Message(_('Role "%(name)s" permissions have been changed.') % {'name': self.original_name}, messages.SUCCESS)
def post_form(self, form): self.thread.original_weight = self.thread.weight super(SetStateCheckpointMixin, self).post_form(form) if self.thread.original_weight != self.thread.weight: if self.thread.original_weight == 2: with UpdatingMonitor() as cm: monitor.decrease('reported_posts') if self.thread.weight == 1: self.thread.set_checkpoint(self.request, 'resolved') if self.thread.weight == 0: self.thread.set_checkpoint(self.request, 'bogus')
def action(self, target): target.delete() with UpdatingMonitor() as cm: monitor.increase('bans_version') if target.test == 0: return Message(_('E-mail and username Ban "%(ban)s" has been lifted.') % {'ban': target.ban}, messages.SUCCESS), False if target.test == 1: return Message(_('Username Ban "%(ban)s" has been lifted.') % {'ban': target.ban}, messages.SUCCESS), False if target.test == 2: return Message(_('E-mail Ban "%(ban)s" has been lifted.') % {'ban': target.ban}, messages.SUCCESS), False if target.test == 3: return Message(_('IP Ban "%(ban)s" has been lifted.') % {'ban': target.ban}, messages.SUCCESS), False
def thread_action_hard(self): # Delete thread self.thread.delete() # Update forum self.forum.sync() self.forum.save(force_update=True) # Update monitor with UpdatingMonitor() as cm: monitor.decrease('threads') monitor.decrease('posts', self.thread.replies + 1) self.after_thread_action_hard() return self.threads_list_redirect()
def submit_form(self, form, target): new_ban = Ban( test=form.cleaned_data['test'], ban=form.cleaned_data['ban'], reason_user=form.cleaned_data['reason_user'], reason_admin=form.cleaned_data['reason_admin'], expires=form.cleaned_data['expires'] ) new_ban.save(force_insert=True) with UpdatingMonitor() as cm: monitor.increase('bans_version') return new_ban, Message(_('New Ban has been set.'), messages.SUCCESS)
def action_activate(self, items, checked): for user in items: if user.pk in checked and user.activation > 0: with UpdatingMonitor() as cm: monitor.decrease('users_inactive') user.activation = user.ACTIVATION_NONE user.save(force_update=True) user.email_user( self.request, 'users/activation/admin_done', _("Your Account has been activated"), ) return Message(_('Selected users accounts have been activated.'), messages.SUCCESS), reverse('admin_users')
def submit_form(self, form, target): new_forum = Forum( name=form.cleaned_data['name'], slug=slugify(form.cleaned_data['name']), type=form.cleaned_data['role'], attrs=form.cleaned_data['attrs'], style=form.cleaned_data['style'], ) new_forum.set_description(form.cleaned_data['description']) if form.cleaned_data['role'] == 'redirect': new_forum.redirect = form.cleaned_data['redirect'] else: new_forum.closed = form.cleaned_data['closed'] new_forum.show_details = form.cleaned_data['show_details'] new_forum.insert_at(form.cleaned_data['parent'], position='last-child', save=True) Forum.objects.populate_tree(True) if form.cleaned_data['perms']: new_forum.copy_permissions(form.cleaned_data['perms']) with UpdatingMonitor() as cm: monitor.increase('acl_version') self.request.session['forums_admin_preffs'] = { 'parent': form.cleaned_data['parent'].pk, 'perms': form.cleaned_data['perms'].pk if form.cleaned_data['perms'] else None, 'role': form.cleaned_data['role'], } if form.cleaned_data['role'] == 'category': return new_forum, Message(_('New Category has been created.'), messages.SUCCESS) if form.cleaned_data['role'] == 'forum': return new_forum, Message(_('New Forum has been created.'), messages.SUCCESS) if form.cleaned_data['role'] == 'redirect': return new_forum, Message(_('New Redirect has been created.'), messages.SUCCESS)
def mass_resolve(self, ids): reported_posts = [] reported_threads = [] for thread in self.threads: if thread.pk in ids: if thread.original_weight != thread.weight: if thread.weight == 1: thread.set_checkpoint(self.request, 'resolved') if thread.weight == 0: thread.set_checkpoint(self.request, 'bogus') if thread.original_weight == 2 and thread.report_for_id: reported_posts.append(thread.report_for.pk) reported_threads.append(thread.report_for.thread_id) if reported_threads: Thread.objects.filter(id__in=reported_threads).update(replies_reported=F('replies_reported') - 1) Post.objects.filter(id__in=reported_posts).update(reported=False, reports=None) with UpdatingMonitor() as cm: monitor.decrease('reported_posts', len(reported_threads))
def thread_action_soft(self): # Update first post in thread self.thread.start_post.deleted = True self.thread.start_post.edit_user = self.request.user self.thread.start_post.edit_user_name = self.request.user.username self.thread.start_post.edit_user_slug = self.request.user.username_slug self.thread.start_post.save(force_update=True) # Update thread self.thread.sync() self.thread.save(force_update=True) # Set checkpoint self.thread.set_checkpoint(self.request, 'deleted') # Update forum self.forum.sync() self.forum.save(force_update=True) # Update monitor with UpdatingMonitor() as cm: monitor.decrease('threads') monitor.decrease('posts', self.thread.replies + 1) self.after_thread_action_soft()
def thread_action_accept(self): # Sync thread and post self.thread.moderated = False self.thread.replies_moderated -= 1 self.thread.save(force_update=True) self.thread.start_post.moderated = False self.thread.start_post.save(force_update=True) self.thread.set_checkpoint(self.request, 'accepted') # Sync user if self.thread.last_post.user: self.thread.start_post.user.threads += 1 self.thread.start_post.user.posts += 1 self.thread.start_post.user.save(force_update=True) # Sync forum self.forum.sync() self.forum.save(force_update=True) # Update monitor with UpdatingMonitor() as cm: monitor.increase('threads') monitor.increase('posts', self.thread.replies + 1) # After self.after_thread_action_accept()
def submit_form(self, form, target): target.name = form.cleaned_data['name'] target.slug = slugify(form.cleaned_data['name']) target.set_description(form.cleaned_data['description']) if target.type == 'redirect': target.redirect = form.cleaned_data['redirect'] else: target.attrs = form.cleaned_data['attrs'] target.show_details = form.cleaned_data['show_details'] target.style = form.cleaned_data['style'] target.closed = form.cleaned_data['closed'] if target.type == 'forum': target.prune_start = form.cleaned_data['prune_start'] target.prune_last = form.cleaned_data['prune_last'] target.pruned_archive = form.cleaned_data['pruned_archive'] target.save(force_update=True) Forum.objects.populate_tree(True) if form.cleaned_data['perms']: target.copy_permissions(form.cleaned_data['perms']) with UpdatingMonitor() as cm: if form.cleaned_data['parent'].pk != target.parent.pk: target.move_to(form.cleaned_data['parent'], 'last-child') monitor.increase('acl_version') if form.cleaned_data[ 'parent'].pk != target.parent.pk or form.cleaned_data[ 'perms']: monitor.increase('acl_version') if self.original_name != target.name: target.sync_name() return target, Message( _('Changes in forum "%(name)s" have been saved.') % {'name': self.original_name}, messages.SUCCESS)
def handle(self, *args, **options): sync_forums = [] for forum in Forum.objects.iterator(): archive = forum.pruned_archive deleted = 0 if forum.prune_start: for thread in forum.thread_set.filter(weight=0).filter( start__lte=timezone.now() - timedelta(days=forum.prune_start)).iterator(): if archive: thread.move_to(archive) thread.save(force_update=True) else: thread.delete() deleted += 1 if forum.prune_last: for thread in forum.thread_set.filter(weight=0).filter( last__lte=timezone.now() - timedelta(days=forum.prune_last)).iterator(): if archive: thread.move_to(archive) thread.save(force_update=True) else: thread.delete() deleted += 1 if deleted: if forum not in sync_forums: sync_forums.append(forum) if archive and archive not in sync_forums: sync_forums.append(archive) for forum in sync_forums: forum.sync() forum.save(force_update=True) with UpdatingMonitor() as cm: monitor['threads'] = Thread.objects.count() monitor['posts'] = Post.objects.count() self.stdout.write('Forums were pruned.\n')
def submit_form(self, form, target): if target.type == 'forum': new_forum = form.cleaned_data['contents'] if new_forum: target.move_content(new_forum) new_forum.sync() new_forum.save(force_update=True) new_parent = form.cleaned_data['subforums'] if new_parent: for child in target.get_descendants(): if child.parent_id == target.pk: child.move_to(new_parent, 'last-child') child.save(force_update=True) else: for child in target.get_descendants().order_by('-lft'): Forum.objects.get(id=child.pk).delete() Forum.objects.get(id=target.pk).delete() Forum.objects.populate_tree(True) with UpdatingMonitor() as cm: monitor.increase('acl_version') return target, Message( _('Forum "%(name)s" has been deleted.') % {'name': self.original_name}, messages.SUCCESS)
def fetch_threads(self): qs_announcements, qs_threads = self.threads_queryset() self.count = qs_threads.count() try: self.pagination = make_pagination(self.kwargs.get('page', 0), self.count, settings.threads_per_page) except Http404: return self.threads_list_redirect() tracker_forum = ThreadsTracker(self.request, self.forum) unresolved_count = 0 for thread in list(chain(qs_announcements, qs_threads[self.pagination['start']:self.pagination['stop']])): thread.original_weight = thread.weight if thread.weight == 2: unresolved_count += 1 thread.is_read = tracker_forum.is_read(thread) thread.report_forum = None if thread.report_for_id: thread.report_forum = Forum.objects.forums_tree.get(thread.report_for.forum_id) self.threads.append(thread) if monitor['reported_posts'] != unresolved_count: with UpdatingMonitor() as cm: monitor['reported_posts'] = unresolved_count
def action_delete(self, items, checked): Ban.objects.filter(id__in=checked).delete() with UpdatingMonitor() as cm: monitor.increase('bans_version') return Message(_('Selected bans have been lifted successfully.'), messages.SUCCESS), reverse('admin_bans')
def after_thread_action_undelete(self): if self.thread.original_weight == 2: with UpdatingMonitor() as cm: monitor.increase('reported_posts') messages.success(self.request, _('Report has been restored.'), 'threads')
def after_thread_action_soft(self): if self.thread.original_weight == 2: with UpdatingMonitor() as cm: monitor.decrease('reported_posts') messages.success(self.request, _('Report has been hidden.'), 'threads')
def post_form(self, form): now = timezone.now() if self.force_moderation(): moderation = True else: moderation = ( not self.request.acl.threads.acl[self.forum.pk]['can_approve'] and self.request.acl.threads.acl[ self.forum.pk]['can_start_threads'] == 1) # Create empty thread self.thread = Thread.objects.create( forum=self.forum, name=form.cleaned_data['thread_name'], slug=slugify(form.cleaned_data['thread_name']), start=now, last=now, moderated=moderation, score=settings.thread_ranking_initial_score, ) # Create our post self.md, post_preparsed = post_markdown(form.cleaned_data['post']) self.post = Post.objects.create( forum=self.forum, thread=self.thread, user=self.request.user, user_name=self.request.user.username, ip=self.request.session.get_ip(self.request), agent=self.request.META.get('HTTP_USER_AGENT'), post=form.cleaned_data['post'], post_preparsed=post_preparsed, date=now, moderated=moderation, ) # Update thread stats to contain this post self.thread.new_start_post(self.post) self.thread.new_last_post(self.post) # Set thread status if 'close_thread' in form.cleaned_data: self.thread.closed = form.cleaned_data['close_thread'] if 'thread_weight' in form.cleaned_data: self.thread.weight = form.cleaned_data['thread_weight'] # Finally save complete thread self.thread.save(force_update=True) # Update forum monitor if not moderation: with UpdatingMonitor() as cm: monitor.increase('threads') monitor.increase('posts') self.forum.threads += 1 self.forum.posts += 1 self.forum.new_last_thread(self.thread) self.forum.save(force_update=True) # Reward user for posting new thread? if not moderation and ( not self.request.user.last_post or self.request.user.last_post < timezone.now() - timedelta(seconds=settings.score_reward_new_post_cooldown)): self.request.user.score += settings.score_reward_new_thread # Update user if not moderation: self.request.user.threads += 1 self.request.user.posts += 1 self.request.user.last_post = now self.request.user.save(force_update=True)
def post_form(self, form): now = timezone.now() if self.force_moderation(): moderation = True else: moderation = ( not self.request.acl.threads.acl[self.forum.pk]['can_approve'] and self.request.acl.threads.acl[ self.forum.pk]['can_start_threads'] == 1) self.thread.previous_last = self.thread.last_post self.md, post_preparsed = post_markdown(form.cleaned_data['post']) # Count merge diff and see if we are merging merge_diff = (now - self.thread.last) merge_diff = (merge_diff.days * 86400) + merge_diff.seconds if (settings.post_merge_time and merge_diff < (settings.post_merge_time * 60) and self.thread.last_poster_id == self.request.user.id and self.thread.last_post.moderated == moderation and (not self.thread.last_post.deleted or self.thread.last_post_id == self.thread.start_post_id)): merged = True self.post = self.thread.last_post self.post.date = now self.post.post = '%s\n\n%s' % (self.post.post, form.cleaned_data['post']) self.md, self.post.post_preparsed = post_markdown(self.post.post) self.post.save(force_update=True) else: # Create new post merged = False self.post = Post.objects.create( forum=self.forum, thread=self.thread, user=self.request.user, user_name=self.request.user.username, ip=self.request.session.get_ip(self.request), agent=self.request.META.get('HTTP_USER_AGENT'), post=form.cleaned_data['post'], post_preparsed=post_preparsed, date=now, moderated=moderation, ) # Update thread data and score? if not moderation: self.thread.new_last_post(self.post) if not merged: if not moderation: self.thread.replies += 1 else: self.thread.replies_moderated += 1 # Increase thread score if self.thread.last_poster_id != self.request.user.pk: self.thread.score += settings.thread_ranking_reply_score # Update forum and monitor if not moderation and not merged: with UpdatingMonitor() as cm: monitor.increase('posts') self.forum.posts += 1 self.forum.new_last_thread(self.thread) self.forum.save(force_update=True) # Reward user for posting new reply? if not moderation and not merged and ( not self.request.user.last_post or self.request.user.last_post < timezone.now() - timedelta(seconds=settings.score_reward_new_post_cooldown)): self.request.user.score += settings.score_reward_new_post # Update user if not moderation and not merged: self.request.user.posts += 1 self.request.user.last_post = now self.request.user.save(force_update=True) # Set thread weight if 'thread_weight' in form.cleaned_data: self.thread.weight = form.cleaned_data['thread_weight'] # Set "closed" checkpoint, either due to thread limit or posters wish if (settings.thread_length > 0 and not merged and not moderation and not self.thread.closed and self.thread.replies >= settings.thread_length): self.thread.closed = True self.thread.set_checkpoint(self.request, 'limit') elif 'close_thread' in form.cleaned_data and form.cleaned_data[ 'close_thread']: self.thread.closed = not self.thread.closed if self.thread.closed: self.thread.set_checkpoint(self.request, 'closed') else: self.thread.set_checkpoint(self.request, 'opened') # Save updated thread self.thread.save(force_update=True) # Mute quoted user? if not (self.quote and self.quote.user_id and not merged and self.quote.user_id != self.request.user.pk and not self.quote.user.is_ignoring(self.request.user)): self.quote = None
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)
def test_create_user(self): """Test User.objects.create_user""" with UpdatingMonitor() as cm: user_a = User.objects.create_user('Lemmiwinks', '*****@*****.**', '123pass') try: user_from_db = User.objects.get(username=user_a.username) user_from_db = User.objects.get(email=user_a.email) except User.DoesNotExist: raise AssertionError("User A was not saved in database!") refresh_monitor() self.assertEqual(int(monitor['users']), 1) self.assertEqual(int(monitor['users_inactive']), 0) self.assertEqual(int(monitor['last_user']), user_a.pk) self.assertEqual(monitor['last_user_name'], user_a.username) self.assertEqual(monitor['last_user_slug'], user_a.username_slug) with UpdatingMonitor() as cm: user_b = User.objects.create_user('InactiveTest', '*****@*****.**', '123pass', activation=User.ACTIVATION_USER) try: user_from_db = User.objects.get(username=user_b.username) user_from_db = User.objects.get(email=user_b.email) self.assertEqual(user_from_db.activation, User.ACTIVATION_USER) except User.DoesNotExist: raise AssertionError("User B was not saved in database!") refresh_monitor() self.assertEqual(int(monitor['users']), 1) self.assertEqual(int(monitor['users_inactive']), 1) self.assertEqual(int(monitor['last_user']), user_a.pk) self.assertEqual(monitor['last_user_name'], user_a.username) self.assertEqual(monitor['last_user_slug'], user_a.username_slug) with UpdatingMonitor() as cm: try: user_c = User.objects.create_user('UsedMail', '*****@*****.**', '123pass') raise AssertionError( "Created user account with taken e-mail address!") except ValidationError: pass refresh_monitor() self.assertEqual(int(monitor['users']), 1) self.assertEqual(int(monitor['users_inactive']), 1) self.assertEqual(int(monitor['last_user']), user_a.pk) self.assertEqual(monitor['last_user_name'], user_a.username) self.assertEqual(monitor['last_user_slug'], user_a.username_slug) with UpdatingMonitor() as cm: try: user_d = User.objects.create_user('InactiveTest', '*****@*****.**', '123pass') raise AssertionError( "Created user account with taken username!") except ValidationError: pass refresh_monitor() self.assertEqual(int(monitor['users']), 1) self.assertEqual(int(monitor['users_inactive']), 1) self.assertEqual(int(monitor['last_user']), user_a.pk) self.assertEqual(monitor['last_user_name'], user_a.username) self.assertEqual(monitor['last_user_slug'], user_a.username_slug)