Example #1
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)):
            request.messages.set_flash(Message(_("No changes to revert.")), 'error', 'changelog')
            return redirect(reverse('changelog_diff', 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)

        from misago.template.templatetags.django2jinja import reldate
        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)
        pagination = make_pagination(0, request.acl.threads.filter_posts(self.request, self.thread, self.thread.post_set).filter(id__lte=self.post.pk).count(), self.request.settings.posts_per_page)
        if pagination['total'] > 1:
            return redirect(reverse('thread', kwargs={'thread': self.thread.pk, 'slug': self.thread.slug, 'page': pagination['total']}) + ('#post-%s' % self.post.pk))
        return redirect(reverse('thread', kwargs={'thread': self.thread.pk, 'slug': self.thread.slug}) + ('#post-%s' % self.post.pk))
Example #2
0
 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('merge', '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 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('-merge', '-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 else ''
     # Flags
     self.moderated = start_post.moderated
     self.deleted = start_post.deleted
     self.merges = last_post.merge
Example #3
0
    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']

        if form.cleaned_data['parent'].pk != target.parent.pk:
            target.move_to(form.cleaned_data['parent'], 'last-child')
            self.request.monitor['acl_version'] = int(self.request.monitor['acl_version']) + 1

        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['acl_version'] = int(self.request.monitor['acl_version']) + 1

        return target, Message(_('Changes in forum "%(name)s" have been saved.') % {'name': self.original_name}, 'success')
Example #4
0
def reverse(route, target=None):
    if target:
        return django_reverse(route,
                              kwargs={
                                  'target': target.pk,
                                  'slug': slugify(target.name)
                              })
    return django_reverse(route)
Example #5
0
 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('thread', 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('threads/split.html',
                                                  {
                                                   'message': message,
                                                   'forum': self.forum,
                                                   'parents': self.parents,
                                                   'thread': self.thread,
                                                   'posts': ids,
                                                   'form': FormLayout(form),
                                                   },
                                                  context_instance=RequestContext(self.request));
Example #6
0
 def submit_form(self, request, form, target):
     target.name = form.cleaned_data['name']
     target.name_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.criteria = form.cleaned_data['criteria']
     target.save(force_update=True)
     return target, BasicMessage(_('Changes in rank "%(name)s" have been saved.' % {'name': self.original_name}), 'success')
Example #7
0
def load_fixtures():
    Forum(token='annoucements', name='annoucements', slug='annoucements', type='forum').insert_at(None, save=True)
    Forum(token='private', name='private', slug='private', type='forum').insert_at(None, save=True)
    Forum(token='reports', name='reports', slug='reports', type='forum').insert_at(None, save=True)

    root = Forum(token='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({
                          'threads': 1,
                          'posts': 1,
                          })
Example #8
0
 def submit_form(self, request, form, target):
     target.name = form.cleaned_data['name']
     target.name_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.criteria = form.cleaned_data['criteria']
     target.save(force_update=True)
     return target, BasicMessage(
         _('Changes in rank "%(name)s" have been saved.' %
           {'name': self.original_name}), 'success')
Example #9
0
 def submit_form(self, request, form, target):
     position = 0
     last_rank = Rank.objects.latest('order')
     new_rank = Rank(name=form.cleaned_data['name'],
                     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'],
                     order=(last_rank.order + 1 if last_rank else 0),
                     criteria=form.cleaned_data['criteria'])
     new_rank.save(force_insert=True)
     return new_rank, BasicMessage(_('New Rank has been created.'),
                                   'success')
Example #10
0
 def submit_form(self, request, form, target):
     position = 0
     last_rank = Rank.objects.latest('order')
     new_rank = Rank(
                   name = form.cleaned_data['name'],
                   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'],
                   order = (last_rank.order + 1 if last_rank else 0),
                   criteria = form.cleaned_data['criteria']
                  )
     new_rank.save(force_insert=True)
     return new_rank, BasicMessage(_('New Rank has been created.'), 'success')
Example #11
0
    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')
Example #12
0
 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)
Example #13
0
    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')
Example #14
0
def reverse(route, target=None):
    if target:
        return django_reverse(route, kwargs={'target': target.pk, 'slug': slugify(target.theme)})
    return django_reverse(route)
Example #15
0
 def __call__(self, value):
     slug = slugify(value)
     if not slug:
         raise ValidationError(self.error_short)
     if len(slug) > 255:
         raise ValidationError(self.error_long)
Example #16
0
def list(request, rank_slug=None):
    ranks = Rank.objects.filter(as_tab=1).order_by('order')

    # Find active rank
    active_rank = None
    if rank_slug:
        for rank in ranks:
            if rank.name_slug == rank_slug:
                active_rank = rank
        if not active_rank:
            return error404(request)
    elif ranks:
        active_rank = ranks[0]

    # Empty Defaults
    message = None
    users = []
    in_search = False

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

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

            # Go for rought match
            if len(username) > 0:
                print username
                users = User.objects.filter(username_slug__startswith=username
                                            ).order_by('username_slug')[:10]
        elif search_form.non_field_errors()[0] == 'form_contains_errors':
            message = Message(request, 'users/search_empty', 'error')
        else:
            message = Message(request,
                              search_form.non_field_errors()[0], 'error')
    else:
        search_form = QuickFindUserForm(request=request)
        if active_rank:
            users = User.objects.filter(
                rank=active_rank).order_by('username_slug')

    return request.theme.render_to_response(
        'users/list.html', {
            'message': message,
            'search_form': FormFields(search_form).fields,
            'in_search': in_search,
            'active_rank': active_rank,
            'ranks': ranks,
            'users': users,
        },
        context_instance=RequestContext(request))
Example #17
0
 def set_username(self, username):
     self.username = username.strip()
     self.username_slug = slugify(username)
Example #18
0
    def __call__(self, request, **kwargs):
        self.request = request
        self.forum = None
        self.thread = None
        self.quote = None
        self.post = None
        self.parents = None
        self.mode = kwargs.get('mode')
        if self.request.POST.get('quick_reply') and self.mode == 'new_post':
            self.mode = 'new_post_quick'
        try:
            self.fetch_target(kwargs)
            if not request.user.is_authenticated():
                raise ACLError403(_("Guest, you have to sign-in in order to post replies."))
        except (Forum.DoesNotExist, Thread.DoesNotExist, Post.DoesNotExist):
            return error404(self.request)
        except ACLError403 as e:
            return error403(request, e.message)
        except ACLError404 as e:
            return error404(request, e.message)

        message = request.messages.get_message('threads')
        if request.method == 'POST':
            form = self.get_form(True)
            # Show message preview
            if 'preview' in request.POST:
                if form['post'].value():
                    md, preparsed = post_markdown(request, form['post'].value())
                else:
                    md, preparsed = None, None
                form.empty_errors()
                return request.theme.render_to_response('threads/posting.html',
                                                        {
                                                         'mode': self.mode,
                                                         'forum': self.forum,
                                                         'thread': self.thread,
                                                         'post': self.post,
                                                         'quote': self.quote,
                                                         'parents': self.parents,
                                                         'message': message,
                                                         'preview': preparsed,
                                                         'form': FormLayout(form),
                                                         },
                                                        context_instance=RequestContext(request));
            # Commit form to database
            if form.is_valid():                
                # Record original vars if user is editing 
                if self.mode in ['edit_thread', 'edit_post']:
                    old_name = self.thread.name
                    old_post = self.post.post
                    # If there is no change, throw user back
                    changed_name = (old_name != form.cleaned_data['thread_name']) if self.mode == 'edit_thread' else False
                    changed_post = old_post != form.cleaned_data['post']
                    changed_anything = changed_name or changed_post

                # Some extra initialisation
                now = timezone.now()
                md = None
                moderation = False
                if not request.acl.threads.acl[self.forum.pk]['can_approve']:
                    if self.mode == 'new_thread' and request.acl.threads.acl[self.forum.pk]['can_start_threads'] == 1:
                        moderation = True
                    if self.mode in ['new_post', 'new_post_quick'] and request.acl.threads.acl[self.forum.pk]['can_write_posts'] == 1:
                        moderation = True

                # Get or create new thread
                if self.mode == 'new_thread':
                    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=request.settings['thread_ranking_initial_score'],
                                                   )
                    if moderation:
                        thread.replies_moderated += 1
                else:
                    thread = self.thread
                    if self.mode == 'edit_thread':
                        thread.name = form.cleaned_data['thread_name']
                        thread.slug = slugify(form.cleaned_data['thread_name'])
                thread.previous_last = thread.last 

                # Create new message
                if self.mode in ['new_thread', 'new_post', 'new_post_quick']:
                    # Use last post instead?
                    if self.mode in ['new_post', 'new_post_quick']:
                        merge_diff = (now - self.thread.last)
                        merge_diff = (merge_diff.days * 86400) + merge_diff.seconds
                    if (self.mode in ['new_post', 'new_post_quick']
                        and request.settings.post_merge_time
                        and merge_diff < (request.settings.post_merge_time * 60)
                        and self.thread.last_poster_id == request.user.id):
                        # Overtake posting
                        post = self.thread.last_post
                        post.appended = True
                        post.moderated = moderation
                        post.date = now
                        post.post = '%s\n\n- - -\n**%s**\n%s' % (post.post, _("Added on %(date)s:") % {'date': date(now, 'SHORT_DATETIME_FORMAT')}, form.cleaned_data['post'])
                        md, post.post_preparsed = post_markdown(request, post.post)
                        post.save(force_update=True)
                        thread.last = now
                        thread.save(force_update=True)
                        self.forum.last = now
                        self.forum.save(force_update=True)
                        # Ignore rest of posting action
                        request.messages.set_flash(Message(_("Your reply has been added to previous one.")), 'success', 'threads_%s' % post.pk)
                        return self.redirect_to_post(post)
                    else:
                        md, post_preparsed = post_markdown(request, form.cleaned_data['post'])
                        post = Post.objects.create(
                                                   forum=self.forum,
                                                   thread=thread,
                                                   merge=thread.merges,
                                                   user=request.user,
                                                   user_name=request.user.username,
                                                   ip=request.session.get_ip(request),
                                                   agent=request.META.get('HTTP_USER_AGENT'),
                                                   post=form.cleaned_data['post'],
                                                   post_preparsed=post_preparsed,
                                                   date=now,
                                                   moderated=moderation,
                                                   )
                        post.appended = False
                elif changed_post:
                    # Change message
                    post = self.post
                    post.post = form.cleaned_data['post']
                    md, post.post_preparsed = post_markdown(request, form.cleaned_data['post'])
                    post.edits += 1
                    post.edit_date = now
                    post.edit_user = request.user
                    post.edit_user_name = request.user.username
                    post.edit_user_slug = request.user.username_slug
                    post.save(force_update=True)

                # Record this edit in changelog?
                if self.mode in ['edit_thread', 'edit_post'] and changed_anything:
                    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=now,
                                                ip=request.session.get_ip(request),
                                                agent=request.META.get('HTTP_USER_AGENT'),
                                                reason=form.cleaned_data['edit_reason'],
                                                size=len(self.post.post),
                                                change=len(self.post.post) - len(old_post),
                                                thread_name_old=old_name if self.mode == 'edit_thread' and form.cleaned_data['thread_name'] != old_name else None,
                                                thread_name_new=self.thread.name if self.mode == 'edit_thread' and form.cleaned_data['thread_name'] != old_name else None,
                                                post_content=old_post,
                                                )

                # Set thread start post and author data
                if self.mode == 'new_thread':
                    thread.start_post = post
                    thread.start_poster = request.user
                    thread.start_poster_name = request.user.username
                    thread.start_poster_slug = request.user.username_slug
                    if request.user.rank and request.user.rank.style:
                        thread.start_poster_style = request.user.rank.style
                    # Reward user for posting new thread?
                    if not request.user.last_post or request.user.last_post < timezone.now() - timedelta(seconds=request.settings['score_reward_new_post_cooldown']):
                        request.user.score += request.settings['score_reward_new_thread']

                # New post - increase post counters, thread score
                # Notify quoted post author and close thread if it has hit limit
                if self.mode in ['new_post', 'new_post_quick']:
                    if moderation:
                        thread.replies_moderated += 1
                    else:
                        thread.replies += 1
                        if thread.last_poster_id != request.user.pk:
                            thread.score += request.settings['thread_ranking_reply_score']
                        # Notify quoted poster of reply?
                        if self.quote and self.quote.user_id and self.quote.user_id != request.user.pk and not self.quote.user.is_ignoring(request.user):
                            alert = self.quote.user.alert(ugettext_lazy("%(username)s has replied to your post in thread %(thread)s").message)
                            alert.profile('username', request.user)
                            alert.post('thread', self.thread, post)
                            alert.save_all()
                        if (self.request.settings.thread_length > 0
                            and not thread.closed
                            and thread.replies >= self.request.settings.thread_length):
                            thread.closed = True
                            post.set_checkpoint(self.request, 'limit')
                    # Reward user for posting new post?
                    if not post.appended and (not request.user.last_post or request.user.last_post < timezone.now() - timedelta(seconds=request.settings['score_reward_new_post_cooldown'])):
                        request.user.score += request.settings['score_reward_new_post']

                # Update last poster data
                if not moderation and self.mode not in ['edit_thread', 'edit_post']:
                    thread.last = now
                    thread.last_post = post
                    thread.last_poster = request.user
                    thread.last_poster_name = request.user.username
                    thread.last_poster_slug = request.user.username_slug
                    thread.last_poster_style = request.user.rank.style

                # Final update of thread entry
                if self.mode != 'edit_post':
                    thread.save(force_update=True)

                # Update forum and monitor
                if not moderation:
                    if self.mode == 'new_thread':
                        self.request.monitor['threads'] = int(self.request.monitor['threads']) + 1
                        self.forum.threads += 1

                    if self.mode in ['new_thread', 'new_post', 'new_post_quick']:
                        self.request.monitor['posts'] = int(self.request.monitor['posts']) + 1
                        self.forum.posts += 1

                    if self.mode in ['new_thread', 'new_post', 'new_post_quick'] or (
                        self.mode == 'edit_thread'
                        and self.forum.last_thread_id == thread.pk
                        and self.forum.last_thread_name != thread.name):
                        self.forum.last_thread = thread
                        self.forum.last_thread_name = thread.name
                        self.forum.last_thread_slug = thread.slug
                        self.forum.last_thread_date = thread.last

                    if self.mode in ['new_thread', 'new_post', 'new_post_quick']:
                        self.forum.last_poster = thread.last_poster
                        self.forum.last_poster_name = thread.last_poster_name
                        self.forum.last_poster_slug = thread.last_poster_slug
                        self.forum.last_poster_style = thread.last_poster_style

                    if self.mode != 'edit_post':
                        self.forum.save(force_update=True)

                # Update user
                if not moderation:
                    if self.mode == 'new_thread':
                        request.user.threads += 1
                    request.user.posts += 1
                if self.mode in ['new_thread', 'new_post', 'new_post_quick']:
                    request.user.last_post = thread.last
                    request.user.save(force_update=True)
                    
                # Notify users about post
                if md:
                    try:
                        if self.quote and self.quote.user_id:
                            del md.mentions[self.quote.user.username_slug]
                    except KeyError:
                        pass
                    if md.mentions:
                        post.notify_mentioned(request, md.mentions)
                        post.save(force_update=True)

                # Set thread watch status
                if self.mode == 'new_thread' and request.user.subscribe_start:
                    ThreadWatch.objects.create(
                                               user=request.user,
                                               forum=self.forum,
                                               thread=thread,
                                               last_read=now,
                                               email=(request.user.subscribe_start == 2),
                                               )
                    
                if self.mode in ['new_post', 'new_post_quick'] and request.user.subscribe_reply:
                    try:
                        watcher = ThreadWatch.objects.get(user=request.user, thread=self.thread)
                    except ThreadWatch.DoesNotExist:
                        ThreadWatch.objects.create(
                                                   user=request.user,
                                                   forum=self.forum,
                                                   thread=thread,
                                                   last_read=now,
                                                   email=(request.user.subscribe_reply == 2),
                                                   )

                # Set flash and redirect user to his post
                if self.mode == 'new_thread':
                    if moderation:
                        request.messages.set_flash(Message(_("New thread has been posted. It will be hidden from other members until moderator reviews it.")), 'success', 'threads')
                    else:
                        request.messages.set_flash(Message(_("New thread has been posted.")), 'success', 'threads')
                    return redirect(reverse('thread', kwargs={'thread': thread.pk, 'slug': thread.slug}) + ('#post-%s' % post.pk))

                if self.mode in ['new_post', 'new_post_quick']:
                    thread.email_watchers(request, post)
                    if moderation:
                        request.messages.set_flash(Message(_("Your reply has been posted. It will be hidden from other members until moderator reviews it.")), 'success', 'threads_%s' % post.pk)
                    else:
                        request.messages.set_flash(Message(_("Your reply has been posted.")), 'success', 'threads_%s' % post.pk)
                    return self.redirect_to_post(post)

                if self.mode == 'edit_thread':
                    request.messages.set_flash(Message(_("Your thread has been edited.")), 'success', 'threads_%s' % self.post.pk)
                if self.mode == 'edit_post':
                    request.messages.set_flash(Message(_("Your reply has been edited.")), 'success', 'threads_%s' % self.post.pk)
                    return self.redirect_to_post(self.post)
                return redirect(reverse('thread', kwargs={'thread': self.thread.pk, 'slug': self.thread.slug}) + ('#post-%s' % self.post.pk))
            message = Message(form.non_field_errors()[0], 'error')
        else:
            form = self.get_form()

        # Merge proxy into forum
        self.forum.closed = self.proxy.closed
        return request.theme.render_to_response('threads/posting.html',
                                                {
                                                 'mode': self.mode,
                                                 'forum': self.forum,
                                                 'thread': self.thread,
                                                 'post': self.post,
                                                 'quote': self.quote,
                                                 'parents': self.parents,
                                                 'message': message,
                                                 'form': FormLayout(form),
                                                 },
                                                context_instance=RequestContext(request));
Example #19
0
def slugify_tag(format_string):
    return slugify(format_string)
Example #20
0
def list(request, rank_slug=None):
    ranks = Rank.objects.filter(as_tab=1).order_by('order')
    
    # Find active rank
    active_rank = None
    if rank_slug:
        for rank in ranks:
            if rank.name_slug == rank_slug:
                active_rank = rank
        if not active_rank:
            return error404(request)
    elif ranks:
        active_rank = ranks[0]
    
    # Empty Defaults
    message = None
    users = []
    in_search = False
    
    # Users search?
    if request.method == 'POST':
        in_search = True
        active_rank = None
        search_form = QuickFindUserForm(request.POST, request=request)
        if search_form.is_valid():
            # Direct hit?
            username = search_form.cleaned_data['username']
            try:
                user = User.objects.get(username__iexact=username)
                return redirect(reverse('user', args=(user.username_slug, user.pk)))
            except User.DoesNotExist:
                pass
            
            # Looks like well have to find near match
            if len(username) > 6:
                username = username[0:-3]
            elif len(username) > 5:
                username = username[0:-2]
            elif len(username) > 4:
                username = username[0:-1]
            username = slugify(username.strip())
            
            # Go for rought match
            if len(username) > 0:
                print username
                users = User.objects.filter(username_slug__startswith=username).order_by('username_slug')[:10]
        elif search_form.non_field_errors()[0] == 'form_contains_errors':
            message = Message(request, 'users/search_empty', 'error')
        else:
            message = Message(request, search_form.non_field_errors()[0], 'error')
    else:
        search_form = QuickFindUserForm(request=request)
        if active_rank:
            users = User.objects.filter(rank=active_rank).order_by('username_slug')
    
    return request.theme.render_to_response('users/list.html',
                                        {
                                         'message': message,
                                         'search_form': FormFields(search_form).fields,
                                         'in_search': in_search,
                                         'active_rank': active_rank,
                                         'ranks': ranks,
                                         'users': users,
                                        },
                                        context_instance=RequestContext(request));
Example #21
0
 def set_username(self, username):
     self.username = username.strip()
     self.username_slug = slugify(username)