def sync(self): # Counters self.replies = self.post_set.filter(moderated=False).count() - 1 if self.replies < 0: self.replies = 0 self.replies_reported = self.post_set.filter(reported=True).count() self.replies_moderated = self.post_set.filter(moderated=True).count() self.replies_deleted = self.post_set.filter(deleted=True).count() # First post start_post = self.post_set.order_by('id')[0:][0] self.start = start_post.date self.start_post = start_post self.start_poster = start_post.user self.start_poster_name = start_post.user_name self.start_poster_slug = slugify(start_post.user_name) self.start_poster_style = start_post.user.rank.style if start_post.user and start_post.user.rank else '' self.upvotes = start_post.upvotes self.downvotes = start_post.downvotes # Last visible post if self.replies > 0: last_post = self.post_set.order_by('-id').filter(moderated=False)[0:][0] else: last_post = start_post self.last = last_post.date self.last_post = last_post self.last_poster = last_post.user self.last_poster_name = last_post.user_name self.last_poster_slug = slugify(last_post.user_name) self.last_poster_style = last_post.user.rank.style if last_post.user and last_post.user.rank else '' # Flags self.moderated = start_post.moderated self.deleted = start_post.deleted
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'] if form.cleaned_data['parent'].pk != target.parent.pk: target.move_to(form.cleaned_data['parent'], 'last-child') self.request.monitor.increase('acl_version') target.save(force_update=True) Forum.objects.populate_tree(True) if form.cleaned_data['perms']: target.copy_permissions(form.cleaned_data['perms']) if form.cleaned_data['parent'].pk != target.parent.pk or form.cleaned_data['perms']: self.request.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}, 'success')
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()
def clean_invite_users(self): self.users_list = [] usernames = [] slugs = [self.request.user.username_slug] for username in self.cleaned_data["invite_users"].split(","): username = username.strip() slug = slugify(username) if len(slug) >= 3 and not slug in slugs: slugs.append(slug) usernames.append(username) try: user = User.objects.get(username_slug=slug) if not user.acl(self.request).private_threads.can_participate(): raise forms.ValidationError( _("%(user)s cannot participate in private threads.") % {"user": user.username} ) if not self.request.acl.private_threads.can_invite_ignoring() and not user.allow_pd_invite( self.request.user ): raise forms.ValidationError( _("%(user)s restricts who can invite him to private threads.") % {"user": user.username} ) self.users_list.append(user) except User.DoesNotExist: raise forms.ValidationError(_('User "%(username)s" could not be found.') % {"username": username}) if len(usernames) > 8: raise forms.ValidationError( _( "You cannot invite more than 8 members at single time. Post thread and then invite additional members." ) ) return ", ".join(usernames)
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']) self.request.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.'), 'success') if form.cleaned_data['role'] == 'forum': return new_forum, Message(_('New Forum has been created.'), 'success') if form.cleaned_data['role'] == 'redirect': return new_forum, Message(_('New Redirect has been created.'), 'success')
def clean_search_author(self): data = self.cleaned_data['search_author'] if data: slug = slugify(data) if len(slug) < 3: raise forms.ValidationError(_("Author name has to contain at least 3 alpha-numerical characters.")) return data
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)
def post_action_split(self, ids): for id in ids: if id == self.thread.start_post_id: raise forms.ValidationError(_("You cannot split first post from thread.")) message = None if self.request.POST.get('do') == 'split': form = SplitThreadForm(self.request.POST, request=self.request) if form.is_valid(): new_thread = Thread() new_thread.forum = form.cleaned_data['thread_forum'] new_thread.name = form.cleaned_data['thread_name'] new_thread.slug = slugify(form.cleaned_data['thread_name']) new_thread.start = timezone.now() new_thread.last = timezone.now() new_thread.start_poster_name = 'n' new_thread.start_poster_slug = 'n' new_thread.last_poster_name = 'n' new_thread.last_poster_slug = 'n' new_thread.save(force_insert=True) prev_merge = -1 merge = -1 for post in self.posts: if post.pk in ids: if prev_merge != post.merge: prev_merge = post.merge merge += 1 post.merge = merge post.move_to(new_thread) post.save(force_update=True) new_thread.sync() new_thread.save(force_update=True) self.thread.sync() self.thread.save(force_update=True) self.forum.sync() self.forum.save(force_update=True) if new_thread.forum != self.forum: new_thread.forum.sync() new_thread.forum.save(force_update=True) self.request.messages.set_flash(Message(_("Selected posts have been split to new thread.")), 'success', 'threads') return redirect(reverse(self.type_prefix, kwargs={'thread': new_thread.pk, 'slug': new_thread.slug})) message = Message(form.non_field_errors()[0], 'error') else: form = SplitThreadForm(request=self.request, initial={ 'thread_name': _('[Split] %s') % self.thread.name, 'thread_forum': self.forum, }) return self.request.theme.render_to_response('%ss/split.html' % self.type_prefix, { 'type_prefix': self.type_prefix, 'message': message, 'forum': self.forum, 'parents': self.parents, 'thread': self.thread, 'posts': ids, 'form': FormLayout(form), }, context_instance=RequestContext(self.request));
def submit_form(self, form, target): target.name = form.cleaned_data['name'] target.slug = slugify(form.cleaned_data['name']) target.style = form.cleaned_data['style'] target.save(force_update=True) target.update_forums(form.cleaned_data['forums']) return target, Message(_('Changes in prefix "%(name)s" have been saved.') % {'name': self.original_name}, messages.SUCCESS)
def make_jump(self): username = slugify(self.request.POST.get("username", "").strip()) if not username: self.request.messages.set_flash( Message(_("You have to enter name of user you want to invite to thread.")), "error", "threads" ) return self.retreat_redirect() try: user = User.objects.get(username_slug=username) acl = user.acl(self.request) if user in self.thread.participants.all(): if user.pk == self.request.user.pk: self.request.messages.set_flash( Message(_("You cannot add yourself to this thread.")), "error", "threads" ) else: self.request.messages.set_flash( Message(_("%(user)s is already participating in this thread.") % {"user": user.username}), "info", "threads", ) elif not acl.private_threads.can_participate(): self.request.messages.set_flash( Message(_("%(user)s cannot participate in private threads.") % {"user": user.username}), "info", "threads", ) elif not self.request.acl.private_threads.can_invite_ignoring() and not user.allow_pd_invite( self.request.user ): self.request.messages.set_flash( Message(_("%(user)s restricts who can invite him to private threads.") % {"user": user.username}), "info", "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) self.request.messages.set_flash( Message(_("%(user)s has been added to this thread.") % {"user": user.username}), "success", "threads", ) except User.DoesNotExist: self.request.messages.set_flash( Message(_("User with requested username could not be found.")), "error", "threads" ) return self.retreat_redirect()
def action_merge(self, ids): if len(ids) < 2: raise ValidationError(_("You have to pick two or more threads to merge.")) threads = [] for thread in self.threads: if thread.pk in ids: threads.append(thread) if self.request.POST.get('origin') == 'merge_form': form = MergeThreadsForm(self.request.POST, request=self.request, threads=threads) if form.is_valid(): new_thread = Thread.objects.create( forum=form.cleaned_data['new_forum'], name=form.cleaned_data['thread_name'], slug=slugify(form.cleaned_data['thread_name']), start=timezone.now(), last=timezone.now() ) merged = [] for thread in reversed(threads): merged.append(thread.pk) thread.merge_with(new_thread) Thread.objects.filter(id__in=merged).delete() new_thread.sync() new_thread.save(force_update=True) new_thread.update_current_dates() self.forum.sync() self.forum.save(force_update=True) if form.cleaned_data['new_forum'].pk != self.forum.pk: form.cleaned_data['new_forum'].sync() form.cleaned_data['new_forum'].save(force_update=True) self.request.messages.set_flash(Message(_('Selected threads have been merged into new one.')), 'success', 'threads') return None self.message = Message(form.non_field_errors()[0], 'error') else: form = MergeThreadsForm(request=self.request, threads=threads) warning = None lookback = threads[0].last_post_id for thread in threads[1:]: if thread.start_post_id < lookback: warning = Message(_("Warning: Posting times in one or more of threads that you are going to merge are overlapping. This may result in disturbed flow of merged thread."), 'warning') break else: lookback = thread.last_post_id return self.request.theme.render_to_response(('%ss/merge.html' % self.type_prefix), { 'type_prefix': self.type_prefix, 'message': self.message, 'warning': warning, 'forum': self.forum, 'parents': self.parents, 'threads': threads, 'form': FormLayout(form), }, context_instance=RequestContext(self.request));
def submit_form(self, form, target): new_prefix = ThreadPrefix( name=form.cleaned_data['name'], slug=slugify(form.cleaned_data['name']), style=form.cleaned_data['style'], ) new_prefix.save(force_insert=True) for forum in form.cleaned_data['forums']: new_prefix.forums.add(forum) return new_prefix, Message(_('New Prefix has been created.'), messages.SUCCESS)
def submit_form(self, form, target): target.name = form.cleaned_data['name'] target.slug = slugify(form.cleaned_data['name']) target.description = form.cleaned_data['description'] target.expires_after_minutes = form.cleaned_data['expires_after_minutes'] target.restrict_posting_replies = form.cleaned_data['restrict_posting_replies'] target.restrict_posting_threads = form.cleaned_data['restrict_posting_threads'] target.save(force_update=True) return target, Message(_('Changes in warning level "%(name)s" have been saved.') % {'name': self.original_name}, messages.SUCCESS)
def submit_form(self, form, target): target.name = form.cleaned_data['name'] target.slug = slugify(form.cleaned_data['name']) target.description = form.cleaned_data['description'] target.style = form.cleaned_data['style'] target.title = form.cleaned_data['title'] target.special = form.cleaned_data['special'] target.as_tab = form.cleaned_data['as_tab'] target.on_index = form.cleaned_data['on_index'] target.criteria = form.cleaned_data['criteria'] target.save(force_update=True) return target, Message(_('Changes in rank "%(name)s" have been saved.') % {'name': self.original_name}, 'success')
def post_action_split(self, ids): for id in ids: if id == self.thread.start_post_id: raise forms.ValidationError(_("You cannot split first post from thread.")) message = None if self.request.POST.get("do") == "split": form = SplitThreadForm(self.request.POST, request=self.request) if form.is_valid(): new_thread = Thread() new_thread.forum = form.cleaned_data["thread_forum"] new_thread.name = form.cleaned_data["thread_name"] new_thread.slug = slugify(form.cleaned_data["thread_name"]) new_thread.start = timezone.now() new_thread.last = timezone.now() new_thread.start_poster_name = "n" new_thread.start_poster_slug = "n" new_thread.last_poster_name = "n" new_thread.last_poster_slug = "n" new_thread.save(force_insert=True) for post in self.posts: if post.pk in ids: post.move_to(new_thread) post.save(force_update=True) new_thread.sync() new_thread.save(force_update=True) self.thread.sync() self.thread.save(force_update=True) self.forum.sync() self.forum.save(force_update=True) if new_thread.forum != self.forum: new_thread.forum.sync() new_thread.forum.save(force_update=True) messages.success(self.request, _("Selected posts have been split to new thread."), "threads") return redirect(reverse(self.type_prefix, kwargs={"thread": new_thread.pk, "slug": new_thread.slug})) message = Message(form.non_field_errors()[0], messages.ERROR) else: form = SplitThreadForm( request=self.request, initial={"thread_name": _("[Split] %s") % self.thread.name, "thread_forum": self.forum}, ) return render_to_response( "%ss/split.html" % self.type_prefix, { "type_prefix": self.type_prefix, "message": message, "forum": self.forum, "parents": self.parents, "thread": self.thread, "posts": ids, "form": form, }, context_instance=RequestContext(self.request), )
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)): request.messages.set_flash(Message(_("No changes to revert.")), 'error', '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(request, self.change.post_content) self.post.save(force_update=True) request.messages.set_flash(Message(_("Post has been reverted to state from %(date)s.") % {'date': reldate(self.change.date).lower()}), 'success', 'threads_%s' % self.post.pk) return self.redirect_to_post(self.post)
def load(): Forum(special='private_threads', name='private', slug='private', type='forum').insert_at(None, save=True) Forum(special='reports', name='reports', slug='reports', type='forum').insert_at(None, save=True) root = Forum(special='root', name='root', slug='root') root.insert_at(None, save=True) cat = Forum(type='category', name='First Category', slug='first-category') cat.insert_at(root, save=True) forum = Forum(type='forum', name='First Forum', slug='first-forum', threads=1, posts=1) forum.insert_at(cat, save=True) Forum(type='redirect', name='Project Homepage', slug='project-homepage', redirect='http://misago-project.org').insert_at(cat, position='last-child', save=True) Forum.objects.populate_tree(True) now = timezone.now() thread = Thread.objects.create( forum=forum, name='Welcome to Misago!', slug=slugify('Welcome to Misago!'), start=now, last=now, ) post = Post.objects.create( forum=forum, thread=thread, user_name='MisagoProject', ip='127.0.0.1', agent='', post='Welcome to Misago!', post_preparsed='Welcome to Misago!', date=now, ) thread.start_post = post thread.start_poster_name = 'MisagoProject' thread.start_poster_slug = 'misagoproject' thread.last_post = post thread.last_poster_name = 'MisagoProject' thread.last_poster_slug = 'misagoproject' thread.save(force_update=True) forum.last_thread = thread forum.last_thread_name = thread.name forum.last_thread_slug = thread.slug forum.last_thread_date = thread.last forum.last_poster = thread.last_poster forum.last_poster_name = thread.last_poster_name forum.last_poster_slug = thread.last_poster_slug forum.save(force_update=True) load_monitor_fixture(monitor_fixture)
def clean_thread_name(self): data = self.cleaned_data['thread_name'] slug = slugify(data) if len(slug) < self.request.settings['thread_name_min']: raise forms.ValidationError(ungettext( "Thread name must contain at least one alpha-numeric character.", "Thread name must contain at least %(count)d alpha-numeric characters.", self.request.settings['thread_name_min'] ) % {'count': self.request.settings['thread_name_min']}) if len(data) > self.request.settings['thread_name_max']: raise forms.ValidationError(ungettext( "Thread name cannot be longer than %(count)d character.", "Thread name cannot be longer than %(count)d characters.", self.request.settings['thread_name_max'] ) % {'count': self.request.settings['thread_name_max']}) return data
def submit_form(self, form, target): position = 0 last_rank = Rank.objects.latest('order') new_rank = Rank( name=form.cleaned_data['name'], slug=slugify(form.cleaned_data['name']), description=form.cleaned_data['description'], style=form.cleaned_data['style'], title=form.cleaned_data['title'], special=form.cleaned_data['special'], as_tab=form.cleaned_data['as_tab'], on_index=form.cleaned_data['on_index'], order=(last_rank.order + 1 if last_rank else 0), criteria=form.cleaned_data['criteria'] ) new_rank.save(force_insert=True) return new_rank, Message(_('New Rank has been created.'), 'success')
def submit_form(self, form, target): new_forum = Forum( name=form.cleaned_data['name'], slug=slugify(form.cleaned_data['name']), redirect=form.cleaned_data['redirect'], style=form.cleaned_data['style'], type='redirect', ) new_forum.set_description(form.cleaned_data['description']) 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']) self.request.monitor['acl_version'] = int(self.request.monitor['acl_version']) + 1 return new_forum, Message(_('New Redirect has been created.'), 'success')
def submit_form(self, form, target): top_level = WarnLevel.objects.order_by('-warning_level')[:1] if top_level: new_warning_level = top_level[0].warning_level + 1 else: new_warning_level = 1 new_level = WarnLevel( name=form.cleaned_data['name'], slug=slugify(form.cleaned_data['name']), description=form.cleaned_data['description'], warning_level=new_warning_level, expires_after_minutes=form.cleaned_data['expires_after_minutes'], restrict_posting_replies=form.cleaned_data['restrict_posting_replies'], restrict_posting_threads=form.cleaned_data['restrict_posting_threads'] ) new_level.save(force_insert=True) return new_level, Message(_('New warning level has been defined.'), messages.SUCCESS)
def submit_form(self, form, target): position = 0 last_rank = Rank.objects.latest('order') new_rank = Rank( name=form.cleaned_data['name'], slug=slugify(form.cleaned_data['name']), description=form.cleaned_data['description'], style=form.cleaned_data['style'], title=form.cleaned_data['title'], special=form.cleaned_data['special'], as_tab=form.cleaned_data['as_tab'], on_index=form.cleaned_data['on_index'], order=(last_rank.order + 1 if last_rank else 0), criteria=form.cleaned_data['criteria'] ) new_rank.save(force_insert=True) for role in form.cleaned_data['roles']: new_rank.roles.add(role) return new_rank, Message(_('New Rank has been created.'), 'success')
def post_form(self, form): now = timezone.now() old_name = self.thread.name old_post = self.post.post changed_thread = old_name != form.cleaned_data['thread_name'] changed_post = old_post != form.cleaned_data['post'] if self.thread.last_post_id == self.post.pk: self.thread.last_post == self.post if 'close_thread' in form.cleaned_data and form.cleaned_data['close_thread']: self.thread.closed = not self.thread.closed changed_thread = True if self.thread.closed: self.thread.last_post.set_checkpoint(self.request, 'closed') else: self.thread.last_post.set_checkpoint(self.request, 'opened') if self.thread.last_post_id != self.post.pk or not changed_post: self.thread.last_post.save(force_update=True) if ('thread_weight' in form.cleaned_data and form.cleaned_data['thread_weight'] != self.thread.weight): self.thread.weight = form.cleaned_data['thread_weight'] changed_thread = True if changed_thread: self.thread.name = form.cleaned_data['thread_name'] self.thread.slug = slugify(form.cleaned_data['thread_name']) self.thread.save(force_update=True) if changed_post: self.post.post = form.cleaned_data['post'] self.md, self.post.post_preparsed = post_markdown(self.request, form.cleaned_data['post']) self.post.edits += 1 self.post.edit_date = now 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.save(force_update=True) if changed_thread or changed_post: self.record_edit(form, old_name, old_post)
def submit_form(self, form, target): top_level = WarnLevel.objects.order_by('-warning_level')[:1] if top_level: new_warning_level = top_level[0].warning_level + 1 else: new_warning_level = 1 new_level = WarnLevel( name=form.cleaned_data['name'], slug=slugify(form.cleaned_data['name']), description=form.cleaned_data['description'], warning_level=new_warning_level, expires_after_minutes=form.cleaned_data['expires_after_minutes'], restrict_posting_replies=form.cleaned_data['restrict_posting_replies'], restrict_posting_threads=form.cleaned_data['restrict_posting_threads'] ) new_level.save(force_insert=True) WarnLevel.objects.flush_cache() return new_level, Message(_('New warning level has been defined.'), messages.SUCCESS)
def mention(match): slug = slugify(match.group(0)[1:]) if slug in self.md.mentions: user = self.md.mentions[slug] return '%s[@%s](%s)' % (match.group(1), user.username, reverse('user', kwargs={ 'user': user.pk, 'username': user.username_slug, })) elif len(self.md.mentions) < 32: try: user = User.objects.get(username_slug=slug) self.md.mentions[slug] = user return '%s[@%s](%s)' % (match.group(1), user.username, reverse('user', kwargs={ 'user': user.pk, 'username': user.username_slug, })) except User.DoesNotExist: pass return match.group(0)
def mention(match): slug = slugify(match.group(0)[1:]).replace('-', '') if slug in self.md.mentions: user = self.md.mentions[slug] return '%s[@%s](%s)' % (match.group(1), user.username, reverse('user', kwargs={ 'user': user.pk, 'username': user.username_slug, })) elif len(self.md.mentions) < 32: try: user = User.objects.get(username_slug=slug) self.md.mentions[slug] = user return '%s[@%s](%s)' % (match.group(1), user.username, reverse('user', kwargs={ 'user': user.pk, 'username': user.username_slug, })) except User.DoesNotExist: pass return match.group(0)
def post_form(self, form): old_name = self.thread.name old_post = self.post.post changed_thread = old_name != form.cleaned_data['thread_name'] changed_post = old_post != form.cleaned_data['post'] if self.thread.last_post_id == self.post.pk: self.thread.last_post == self.post if 'close_thread' in form.cleaned_data and form.cleaned_data['close_thread']: self.thread.closed = not self.thread.closed changed_thread = True if self.thread.closed: self.thread.set_checkpoint(self.request, 'closed') else: self.thread.set_checkpoint(self.request, 'opened') if ('thread_weight' in form.cleaned_data and form.cleaned_data['thread_weight'] != self.thread.weight): self.thread.weight = form.cleaned_data['thread_weight'] changed_thread = True if changed_thread: self.thread.name = form.cleaned_data['thread_name'] self.thread.slug = slugify(form.cleaned_data['thread_name']) self.thread.save(force_update=True) if self.forum.last_thread_id == self.thread.pk: self.forum.last_thread_name = self.thread.name self.forum.last_thread_slug = self.thread.slug self.forum.save(force_update=True) if changed_post: self.post.post = form.cleaned_data['post'] self.md, self.post.post_preparsed = post_markdown(form.cleaned_data['post']) self.post.save(force_update=True) if old_name != form.cleaned_data['thread_name']: self.thread.update_current_dates() if changed_thread or changed_post: self.record_edit(form, old_name, old_post)
def submit_form(self, form, target): new_forum = Forum( name=form.cleaned_data['name'], slug=slugify(form.cleaned_data['name']), type='forum', attrs=form.cleaned_data['attrs'], show_details=form.cleaned_data['show_details'], style=form.cleaned_data['style'], closed=form.cleaned_data['closed'], prune_start=form.cleaned_data['prune_start'], prune_last=form.cleaned_data['prune_last'], ) new_forum.set_description(form.cleaned_data['description']) 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']) self.request.monitor['acl_version'] = int(self.request.monitor['acl_version']) + 1 return new_forum, Message(_('New Forum has been created.'), 'success')
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 submit_form(self, form, target): target.name = form.cleaned_data['name'] target.slug = slugify(form.cleaned_data['name']) target.description = form.cleaned_data['description'] target.style = form.cleaned_data['style'] target.title = form.cleaned_data['title'] target.special = form.cleaned_data['special'] target.as_tab = form.cleaned_data['as_tab'] target.on_index = form.cleaned_data['on_index'] target.criteria = form.cleaned_data['criteria'] target.save(force_update=True) if self.request.user.is_god(): target.roles.clear() else: target.roles.remove(*target.roles.filter(protected=False)) for role in form.cleaned_data['roles']: target.roles.add(role) target.user_set.update(acl_key=None) return target, Message(_('Changes in rank "%(name)s" have been saved.') % {'name': self.original_name}, 'success')
def submit_form(self, form, target): target.name = form.cleaned_data['name'] target.slug = slugify(form.cleaned_data['name']) target.description = form.cleaned_data['description'] target.style = form.cleaned_data['style'] target.title = form.cleaned_data['title'] target.special = form.cleaned_data['special'] target.as_tab = form.cleaned_data['as_tab'] target.on_index = form.cleaned_data['on_index'] target.criteria = form.cleaned_data['criteria'] target.save(force_update=True) if self.request.user.is_god(): target.roles.clear() else: target.roles.remove(*target.roles.filter(protected=False)) for role in form.cleaned_data['roles']: target.roles.add(role) target.user_set.update(acl_key=None) return target, Message(_('Changes in rank "%(name)s" have been saved.') % {'name': self.original_name}, messages.SUCCESS)
def submit_form(self, form, target): position = 0 last_rank = Rank.objects.order_by('-order')[:1] if last_rank: new_last_order = last_rank[0].order + 1 else: new_last_order = 0 new_rank = Rank(name=form.cleaned_data['name'], slug=slugify(form.cleaned_data['name']), description=form.cleaned_data['description'], style=form.cleaned_data['style'], title=form.cleaned_data['title'], special=form.cleaned_data['special'], as_tab=form.cleaned_data['as_tab'], on_index=form.cleaned_data['on_index'], order=new_last_order, criteria=form.cleaned_data['criteria']) new_rank.save(force_insert=True) for role in form.cleaned_data['roles']: new_rank.roles.add(role) return new_rank, Message(_('New Rank has been created.'), messages.SUCCESS)
def submit_form(self, form, target): position = 0 last_rank = Rank.objects.order_by('-order')[:1] if last_rank: new_last_order = last_rank[0].order + 1 else: new_last_order = 0 new_rank = Rank( name=form.cleaned_data['name'], slug=slugify(form.cleaned_data['name']), description=form.cleaned_data['description'], style=form.cleaned_data['style'], title=form.cleaned_data['title'], special=form.cleaned_data['special'], as_tab=form.cleaned_data['as_tab'], on_index=form.cleaned_data['on_index'], order=new_last_order, criteria=form.cleaned_data['criteria'] ) new_rank.save(force_insert=True) for role in form.cleaned_data['roles']: new_rank.roles.add(role) return new_rank, Message(_('New Rank has been created.'), messages.SUCCESS)
def reverse(route, target=None): if target: return django_reverse(route, kwargs={'target': target.pk, 'slug': slugify(target.name)}) return django_reverse(route)
def slugify_function(format_string): return slugify(format_string)
def post_action_split(self, ids): for id in ids: if id == self.thread.start_post_id: raise forms.ValidationError( _("You cannot split first post from thread.")) message = None if self.request.POST.get('do') == 'split': form = SplitThreadForm(self.request.POST, request=self.request) if form.is_valid(): new_thread = Thread() new_thread.forum = form.cleaned_data['thread_forum'] new_thread.name = form.cleaned_data['thread_name'] new_thread.slug = slugify(form.cleaned_data['thread_name']) new_thread.start = timezone.now() new_thread.last = timezone.now() new_thread.start_poster_name = 'n' new_thread.start_poster_slug = 'n' new_thread.last_poster_name = 'n' new_thread.last_poster_slug = 'n' new_thread.save(force_insert=True) for post in self.posts: if post.pk in ids: post.move_to(new_thread) post.save(force_update=True) new_thread.sync() new_thread.save(force_update=True) self.thread.sync() self.thread.save(force_update=True) self.forum.sync() self.forum.save(force_update=True) if new_thread.forum != self.forum: new_thread.forum.sync() new_thread.forum.save(force_update=True) messages.success( self.request, _("Selected posts have been split to new thread."), 'threads') return redirect( reverse(self.type_prefix, kwargs={ 'thread': new_thread.pk, 'slug': new_thread.slug })) message = Message(form.non_field_errors()[0], messages.ERROR) else: form = SplitThreadForm(request=self.request, initial={ 'thread_name': _('[Split] %s') % self.thread.name, 'thread_forum': self.forum, }) return render_to_response('%ss/split.html' % self.type_prefix, { 'type_prefix': self.type_prefix, 'message': message, 'forum': self.forum, 'parents': self.parents, 'thread': self.thread, 'posts': ids, 'form': form, }, context_instance=RequestContext( self.request))
def set_username(self, username): self.username = username.strip() self.username_slug = slugify(username)
def list(request, slug=None, page=0): ranks = Rank.objects.filter(as_tab=1).order_by('order') # Find active rank default_rank = False active_rank = None if slug: for rank in ranks: if rank.slug == slug: active_rank = rank if not active_rank: return error404(request) if ranks and active_rank.slug == ranks[0].slug: return redirect(reverse('users')) elif ranks: default_rank = True active_rank = ranks[0] # Empty Defaults message = None users = [] items_total = 0 pagination = None in_search = False # Users search? if request.method == 'POST': if not request.acl.users.can_search_users(): return error403(request) in_search = True active_rank = None search_form = QuickFindUserForm(request.POST, request=request) if search_form.is_valid(): # Direct hit? username = search_form.cleaned_data['username'] try: user = User.objects if settings.PROFILE_EXTENSIONS_PRELOAD: user = user.select_related( *settings.PROFILE_EXTENSIONS_PRELOAD) user = user.get(username__iexact=username) return redirect( reverse('user', args=(user.username_slug, user.pk))) except User.DoesNotExist: pass # Looks like well have to find near match if len(username) > 6: username = username[0:-3] elif len(username) > 5: username = username[0:-2] elif len(username) > 4: username = username[0:-1] username = slugify(username.strip()) # Go for rought match if len(username) > 0: users = User.objects if settings.PROFILE_EXTENSIONS_PRELOAD: users = users.select_related( *settings.PROFILE_EXTENSIONS_PRELOAD) users = users.filter(username_slug__startswith=username ).order_by('username_slug')[:10] elif search_form.non_field_errors()[0] == 'form_contains_errors': message = Message( _("To search users you have to enter username in search field." ), 'error') else: message = Message(search_form.non_field_errors()[0], 'error') else: search_form = QuickFindUserForm(request=request) if active_rank: users = User.objects.filter(rank=active_rank) items_total = users.count() try: pagination = make_pagination( page, items_total, request.settings['profiles_per_list']) except Http404: if not default_rank and active_rank: return redirect( reverse('users', kwargs={'slug': active_rank.slug})) return redirect(reverse('users')) if settings.PROFILE_EXTENSIONS_PRELOAD: users = users.select_related( *settings.PROFILE_EXTENSIONS_PRELOAD) users = users.order_by( 'username_slug')[pagination['start']:pagination['stop']] return request.theme.render_to_response( 'profiles/list.html', { 'message': message, 'search_form': FormFields(search_form).fields, 'in_search': in_search, 'active_rank': active_rank, 'default_rank': default_rank, 'items_total': items_total, 'ranks': ranks, 'users': users, 'pagination': pagination, }, context_instance=RequestContext(request))
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(self.request, 'reported', user) 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.save(force_update=True) self.thread.replies_reported += 1 self.thread.save(force_update=True) request.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." )) self.request.messages.set_flash( Message( _("Selected post has been reported and will receive moderator attention. Thank you." )), 'info', '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." )) self.request.messages.set_flash( Message( _("You have already reported this post. One of moderators will handle it as soon as it is possible. Thank you for your patience." )), 'info', 'threads_%s' % self.post.pk) return self.redirect_to_post(self.post)
def set_username(self, username): self.username = username.strip() self.username_slug = slugify(username).replace('-', '')
def action_merge(self, ids): if len(ids) < 2: raise ValidationError( _("You have to pick two or more threads to merge.")) threads = [] for thread in self.threads: if thread.pk in ids: threads.append(thread) if self.request.POST.get('origin') == 'merge_form': form = MergeThreadsForm(self.request.POST, request=self.request, threads=threads) if form.is_valid(): new_thread = Thread.objects.create( forum=form.cleaned_data['new_forum'], name=form.cleaned_data['thread_name'], slug=slugify(form.cleaned_data['thread_name']), start=timezone.now(), last=timezone.now()) merged = [] for thread in reversed(threads): merged.append(thread.pk) thread.merge_with(new_thread) Thread.objects.filter(id__in=merged).delete() new_thread.sync() new_thread.save(force_update=True) new_thread.update_current_dates() self.forum.sync() self.forum.save(force_update=True) if form.cleaned_data['new_forum'].pk != self.forum.pk: form.cleaned_data['new_forum'].sync() form.cleaned_data['new_forum'].save(force_update=True) self.request.messages.set_flash( Message( _('Selected threads have been merged into new one.')), 'success', 'threads') return None self.message = Message(form.non_field_errors()[0], 'error') else: form = MergeThreadsForm(request=self.request, threads=threads) warning = None lookback = threads[0].last_post_id for thread in threads[1:]: if thread.start_post_id < lookback: warning = Message( _("Warning: Posting times in one or more of threads that you are going to merge are overlapping. This may result in disturbed flow of merged thread." ), 'warning') break else: lookback = thread.last_post_id return self.request.theme.render_to_response( ('%ss/merge.html' % self.type_prefix), { 'type_prefix': self.type_prefix, 'message': self.message, 'warning': warning, 'forum': self.forum, 'parents': self.parents, 'threads': threads, 'form': FormLayout(form), }, context_instance=RequestContext(self.request))
def action_merge(self, ids): if len(ids) < 2: raise ValidationError( _("You have to pick two or more threads to merge.")) threads = [] for thread in self.threads: if thread.pk in ids: threads.append(thread) if self.request.POST.get('origin') == 'merge_form': form = MergeThreadsForm(self.request.POST, request=self.request, threads=threads) if form.is_valid(): new_thread = Thread.objects.create( forum=form.cleaned_data['new_forum'], name=form.cleaned_data['thread_name'], slug=slugify(form.cleaned_data['thread_name']), start=timezone.now(), last=timezone.now()) merged = [] for thread in reversed(threads): merged.append(thread.pk) thread.merge_with(new_thread) new_thread.sync() new_thread.save(force_update=True) new_thread.update_current_dates() poll_action = form.cleaned_data.get('final_poll', 'no') if poll_action == 'no': for thread in threads: if thread.has_poll: thread.poll.move_to(forum=new_thread.forum, thread=new_thread) new_thread.has_poll = True new_thread.save(force_update=True) break else: if poll_action > 0: for thread in threads: if thread.pk == poll_action: thread.poll.move_to(forum=new_thread.forum, thread=new_thread) new_thread.has_poll = True new_thread.save(force_update=True) break for thread in Thread.objects.filter(id__in=merged): thread.delete() self.forum.sync() self.forum.save(force_update=True) if form.cleaned_data['new_forum'].pk != self.forum.pk: form.cleaned_data['new_forum'].sync() form.cleaned_data['new_forum'].save(force_update=True) messages.success( self.request, _('Selected threads have been merged into new one.'), 'threads') return None self.message = Message(form.non_field_errors()[0], messages.ERROR) else: form = MergeThreadsForm(request=self.request, threads=threads) warning = None lookback = threads[-1] for thread in reversed(threads[:-1]): if thread.start_post_id < lookback.last_post_id: warning = Message( _("Warning: Posting times in one or more of threads that you are going to merge are overlapping. This may result in disturbed flow of merged thread." ), 'warning') break else: lookback = thread return render_to_response('%ss/merge.html' % self.type_prefix, { 'type_prefix': self.type_prefix, 'search_in': self.search_in, 'message': self.message, 'warning': warning, 'forum': self.forum, 'parents': self.parents, 'threads': threads, 'form': form, }, context_instance=RequestContext( self.request))
def post_form(self, form): now = timezone.now() 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=self.request.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: self.request.monitor.increase('threads') self.request.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=self.request. settings['score_reward_new_post_cooldown'])): self.request.user.score += self.request.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 __call__(self, value): slug = slugify(value) if not slug: raise ValidationError(self.error_short) if len(slug) > 255: raise ValidationError(self.error_long)
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)