source: djangobb/djangobb_forum/views.py @ 222:4d85334d2acd

Last change on this file since 222:4d85334d2acd was 222:4d85334d2acd, checked in by slav0nic <slav0nic0@…>, 3 years ago

refactored some code in ban command

File size: 30.2 KB
Line 
1import math
2from datetime import datetime, timedelta
3
4from django.shortcuts import get_object_or_404
5from django.http import Http404, HttpResponse, HttpResponseRedirect, HttpResponseForbidden
6from django.contrib.auth.models import User
7from django.contrib.auth.decorators import login_required
8from django.conf import settings
9from django.core.urlresolvers import reverse
10from django.db import connection
11from django.core.cache import cache
12from django.utils import translation
13from django.db.models import Q, F, Sum
14from django.utils.encoding import smart_str
15
16from djangobb_forum.util import render_to, paged, build_form, paginate, set_language
17from djangobb_forum.models import Category, Forum, Topic, Post, Profile, Reputation,\
18    Report, PrivateMessage, Attachment, PostTracking
19from djangobb_forum.forms import AddPostForm, EditPostForm, UserSearchForm,\
20    PostSearchForm, ReputationForm, MailToForm, EssentialsProfileForm,\
21    PersonalProfileForm, MessagingProfileForm, PersonalityProfileForm,\
22    DisplayProfileForm, PrivacyProfileForm, ReportForm, UploadAvatarForm, CreatePMForm
23from djangobb_forum.markups import mypostmarkup
24from djangobb_forum.templatetags import forum_extras
25from djangobb_forum import settings as forum_settings
26from djangobb_forum.util import urlize, smiles
27from djangobb_forum.index import post_indexer
28from djangobb_forum.templatetags.forum_extras import forum_moderated_by
29
30
31@render_to('forum/index.html')
32def index(request, full=True):
33    users_cached = cache.get('users_online', {})
34    users_online = users_cached and User.objects.filter(id__in = users_cached.keys()) or []
35    guests_cached = cache.get('guests_online', {})
36    guest_count = len(guests_cached)
37    users_count = len(users_online)
38
39    cats = {}
40    forums = {}
41    user_groups = request.user.groups.all()
42    if request.user.is_anonymous():  # in django 1.1 EmptyQuerySet raise exception
43        user_groups = []
44    _forums = Forum.objects.filter(
45            Q(category__groups__in=user_groups) | \
46            Q(category__groups__isnull=True)).select_related('last_post__topic',
47                                                            'last_post__user',
48                                                            'category')
49    for forum in _forums:
50        cat = cats.setdefault(forum.category.id,
51            {'cat': forum.category, 'forums': []})
52        cat['forums'].append(forum)
53        forums[forum.id] = forum
54
55    cmpdef = lambda a, b: cmp(a['cat'].position, b['cat'].position)
56    cats = sorted(cats.values(), cmpdef)
57
58    to_return = {'cats': cats,
59                'posts': Post.objects.count(),
60                'topics': Topic.objects.count(),
61                'users': User.objects.count(),
62                'users_online': users_online,
63                'online_count': users_count,
64                'guest_count': guest_count,
65                'last_user': User.objects.latest('date_joined'),
66                }
67    if full:
68        return to_return
69    else:
70        to_return['TEMPLATE'] = 'forum/lofi/index.html'
71        return to_return
72
73
74@render_to('forum/moderate.html')
75@paged('topics', forum_settings.FORUM_PAGE_SIZE)
76def moderate(request, forum_id):
77    forum = get_object_or_404(Forum, pk=forum_id)
78    topics = forum.topics.order_by('-sticky', '-updated').select_related()
79    if request.user.is_superuser or request.user in forum.moderators.all():
80        if 'move_topics' in request.POST:
81            topic_ids = request.POST.getlist('topic_id')
82            return {
83                'categories': Category.objects.all(),
84                'topic_ids': topic_ids,
85                'exclude_forum': forum,
86                'TEMPLATE': 'forum/move_topic.html'
87            }
88        elif 'delete_topics' in request.POST:
89            for topic_id in topic_list:
90                topic = get_object_or_404(Topic, pk=topic_id)
91                topic.delete()
92            return HttpResponseRedirect(reverse('djangobb:index'))
93        elif 'open_topics' in request.POST:
94            for topic_id in topic_list:
95                open_close_topic(request, topic_id)
96            return HttpResponseRedirect(reverse('djangobb:index'))
97        elif 'close_topics' in request.POST:
98            for topic_id in topic_list:
99                open_close_topic(request, topic_id)
100            return HttpResponseRedirect(reverse('djangobb:index'))
101
102        return {'forum': forum,
103                'topics': topics,
104                #'sticky_topics': forum.topics.filter(sticky=True),
105                'paged_qs': topics,
106                'posts': forum.posts.count(), 
107                }
108    else:
109        raise Http404
110
111
112@render_to('forum/search_topics.html')
113@paged('results', forum_settings.SEARCH_PAGE_SIZE)
114def search(request):
115    # TODO: move to form
116    if 'action' in request.GET:
117        action = request.GET['action']
118        if action == 'show_24h':
119            date = datetime.today() - timedelta(1)
120            topics = Topic.objects.filter(created__gte=date).order_by('created')
121        elif action == 'show_new':
122            #TODO: FIXME
123            #must be filter topic.last_post > tracking.last_read and exclude tracking.topics
124            topics = Topic.objects.all().order_by('created')
125            topics = [topic for topic in topics if forum_extras.has_unreads(topic, request.user)] 
126        elif action == 'show_unanswered':
127            topics = Topic.objects.filter(post_count=1)
128        elif action == 'show_subscriptions':
129            topics = Topic.objects.filter(subscribers=request.user)
130        elif action == 'show_user':
131            user_id = request.GET['user_id']
132            posts = Post.objects.filter(user__id=user_id)
133            topics = [post.topic for post in posts]
134        elif action == 'search':
135            keywords = request.GET.get('keywords')
136            author = request.GET.get('author')
137            forum = request.GET.get('forum')
138            search_in = request.GET.get('search_in')
139            sort_by = request.GET.get('sort_by')
140            sort_dir = request.GET.get('sort_dir')
141
142            if keywords and author:
143                if search_in == 'all':
144                    if forum == '0':
145                        query = 'user:%s AND (topic:%s OR body:%s)' % (author, keywords, keywords)
146                    else:
147                        query = 'user:%s AND forum:%s AND (topic:%s OR body:%s)' % (author, forum, keywords, keywords)
148                elif search_in == 'message':
149                    if forum == '0':
150                        query = 'user:%s AND body:%s' % (author, keywords)
151                    else:
152                        query = 'user:%s AND forum:%s AND body:%s' % (author, forum, keywords)
153                elif search_in == 'topic':
154                    if forum == '0':
155                        query = 'user:%s AND topic:%s' % (author, keywords)
156                    else:
157                        query = 'user:%s AND forum:%s AND topic:%s' % (author, forum, keywords)
158            elif keywords:
159                if search_in == 'all':
160                    if forum == '0':
161                        query = 'topic:%s OR body:%s' % (keywords, keywords)
162                    else:
163                        query = 'forum:%s AND (topic:%s OR body:%s)' % (forum, keywords, keywords)
164                elif search_in == 'message':
165                    if forum == '0':
166                        query = 'body:%s' % (keywords)
167                    else:
168                        query = 'forum:%s AND body:%s' % (forum, keywords)
169                elif search_in == 'topic':
170                    if forum == '0':
171                        query = 'topic:%s' % (keywords)
172                    else:
173                        query = 'forum:%s AND topic:%s' % (forum, keywords)
174            elif author:
175                if forum == '0':
176                    query = 'user:%s' % (author)
177                else:
178                    query = 'forum:%s AND user:%s' % (forum, author)
179            else:
180                return HttpResponseRedirect(reverse('djangobb:search'))
181
182            order = {'0': 'created',
183                     '1': 'user',
184                     '2': 'topic',
185                     '3': 'forum'}.get(sort_by, 'created')
186
187            if sort_dir == 'DESC':
188                order = '-' + order
189            posts = post_indexer.search(query).order_by(order)
190
191            if 'topics' in request.GET['show_as']:
192                topics = []
193                for post in posts:
194                    if post.instance.topic not in topics:
195                        topics.append(post.instance.topic)
196                return {'paged_qs': topics}
197            elif 'posts' in request.GET['show_as']:
198                return {'paged_qs': posts,
199                        'TEMPLATE': 'forum/search_posts.html'
200                        }
201        return {'paged_qs': topics}
202    else:
203        form = PostSearchForm()
204        return {'categories': Category.objects.all(),
205                'form': form,
206                'TEMPLATE': 'forum/search_form.html'
207                }
208
209
210@login_required
211@render_to('forum/report.html')
212def misc(request):
213    if 'action' in request.GET:
214        action = request.GET['action']
215        if action =='markread':
216            user = request.user
217            PostTracking.objects.filter(user=user).update(last_read=datetime.now(), topics=None)
218            return HttpResponseRedirect(reverse('djangobb:index'))
219
220        elif action == 'report':
221            if request.GET.get('post_id', ''):
222                post_id = request.GET['post_id']
223                post = get_object_or_404(Post, id=post_id)
224                form = build_form(ReportForm, request, reported_by=request.user, post=post_id)
225                if request.method == 'POST' and form.is_valid():
226                    form.save()
227                    return HttpResponseRedirect(post.get_absolute_url())
228                return {'form':form}
229
230    elif 'submit' in request.POST and 'mail_to' in request.GET:
231        form = MailToForm(request.POST)
232        if form.is_valid():
233            user = get_object_or_404(User, username=request.GET['mail_to'])
234            subject = form.cleaned_data['subject']
235            body = form.cleaned_data['body']
236            user.email_user(subject, body, request.user.email)
237            return HttpResponseRedirect(reverse('djangobb:index'))
238
239    elif 'mail_to' in request.GET:
240        user = get_object_or_404(User, username=request.GET['mail_to'])
241        form = MailToForm()
242        return {'form':form,
243                'user': user,
244               'TEMPLATE': 'forum/mail_to.html'
245               }
246
247
248@render_to('forum/forum.html')
249@paged('topics', forum_settings.FORUM_PAGE_SIZE)
250def show_forum(request, forum_id, full=True):
251    forum = get_object_or_404(Forum, pk=forum_id)
252    if not forum.category.has_access(request.user):
253        return HttpResponseForbidden()
254    topics = forum.topics.order_by('-sticky', '-updated').select_related()
255    moderator = request.user.is_superuser or\
256        request.user in forum.moderators.all()
257    to_return = {'categories': Category.objects.all(),
258                'forum': forum,
259                'paged_qs': topics,
260                'posts': forum.post_count,
261                'topics': forum.topic_count,
262                'moderator': moderator,
263                }
264    if full:
265        return to_return
266    else:
267        pages, paginator, paged_list_name = paginate(topics, request, forum_settings.FORUM_PAGE_SIZE)
268        to_return.update({'pages': pages,
269                        'paginator': paginator, 
270                        'topics': paged_list_name,
271                        'TEMPLATE': 'forum/lofi/forum.html'
272                        })
273        del to_return['paged_qs']
274        return to_return
275
276
277@render_to('forum/topic.html')
278@paged('posts', forum_settings.TOPIC_PAGE_SIZE)
279def show_topic(request, topic_id, full=True):
280    topic = get_object_or_404(Topic.objects.select_related(), pk=topic_id)
281    if not topic.forum.category.has_access(request.user):
282        return HttpResponseForbidden()
283    Topic.objects.filter(pk=topic.id).update(views=F('views') + 1)
284
285    last_post = topic.last_post
286
287    if request.user.is_authenticated():
288        topic.update_read(request.user)
289
290    posts = topic.posts.all().select_related()
291
292    users = set(post.user.id for post in posts)
293    profiles = Profile.objects.filter(user__pk__in=users)
294    profiles = dict((profile.user_id, profile) for profile in profiles)
295
296    for post in posts:
297        post.user.forum_profile = profiles[post.user.id]
298
299    if forum_settings.REPUTATION_SUPPORT:
300        replies_list = Reputation.objects.filter(to_user__pk__in=users).values('to_user_id').annotate(sign=Sum('sign')) #values_list buggy?
301
302        replies = {}
303        for r in replies_list:
304            replies[r['to_user_id']] = r['sign']
305
306        for post in posts:
307            post.user.forum_profile.reply_total = replies.get(post.user.id, 0)
308
309    initial = {}
310    if request.user.is_authenticated():
311        initial = {'markup': request.user.forum_profile.markup}
312    form = AddPostForm(topic=topic, initial=initial)
313
314    moderator = request.user.is_superuser or\
315        request.user in topic.forum.moderators.all()
316    if request.user.is_authenticated() and request.user in topic.subscribers.all():
317        subscribed = True
318    else:
319        subscribed = False
320
321    highlight_word = request.GET.get('hl', '')
322    if full:
323        return {'categories': Category.objects.all(),
324                'topic': topic,
325                'last_post': last_post,
326                'form': form,
327                'moderator': moderator,
328                'subscribed': subscribed,
329                'paged_qs': posts,
330                'highlight_word': highlight_word,
331                }
332    else:
333        pages, paginator, paged_list_name = paginate(posts, request, forum_settings.TOPIC_PAGE_SIZE)
334        return {'categories': Category.objects.all(),
335                'topic': topic,
336                'pages': pages,
337                'paginator': paginator, 
338                'posts': paged_list_name,
339                'TEMPLATE': 'forum/lofi/topic.html'
340                }
341
342
343@login_required
344@render_to('forum/add_post.html')
345def add_post(request, forum_id, topic_id):
346    forum = None
347    topic = None
348    posts = None
349
350    if forum_id:
351        forum = get_object_or_404(Forum, pk=forum_id)
352        if not forum.category.has_access(request.user):
353            return HttpResponseForbidden()
354    elif topic_id:
355        topic = get_object_or_404(Topic, pk=topic_id)
356        posts = topic.posts.all().select_related()
357        if not topic.forum.category.has_access(request.user):
358            return HttpResponseForbidden()
359    if topic and topic.closed:
360        return HttpResponseRedirect(topic.get_absolute_url())
361   
362    ip = request.META.get('REMOTE_ADDR', None)
363    form = build_form(AddPostForm, request, topic=topic, forum=forum,
364                      user=request.user, ip=ip,
365                      initial={'markup': request.user.forum_profile.markup})
366
367    if 'post_id' in request.GET:
368        post_id = request.GET['post_id']
369        post = get_object_or_404(Post, pk=post_id)
370        form.fields['body'].initial = "[quote=%s]%s[/quote]" % (post.user, post.body)
371
372    if form.is_valid():
373        post = form.save();
374        return HttpResponseRedirect(post.get_absolute_url())
375
376    return {'form': form,
377            'posts': posts,
378            'topic': topic,
379            'forum': forum,
380            }
381
382
383@render_to('forum/user.html')
384def user(request, username):
385    user = get_object_or_404(User, username=username)
386    if request.user.is_authenticated() and user == request.user or request.user.is_superuser:
387        if 'section' in request.GET:
388            section = request.GET['section']
389            if section == 'privacy':
390                form = build_form(PrivacyProfileForm, request, instance=user.forum_profile)
391                if request.method == 'POST' and form.is_valid():
392                    form.save()
393                return {'active_menu':'privacy',
394                        'profile': user,
395                        'form': form,
396                        'TEMPLATE': 'forum/profile/profile_privacy.html'
397                       }
398            elif section == 'display':
399                form = build_form(DisplayProfileForm, request, instance=user.forum_profile)
400                if request.method == 'POST' and form.is_valid():
401                    form.save()
402                return {'active_menu':'display',
403                        'profile': user,
404                        'form': form,
405                        'TEMPLATE': 'forum/profile/profile_display.html'
406                       }
407            elif section == 'personality':
408                form = build_form(PersonalityProfileForm, request, instance=user.forum_profile)
409                if request.method == 'POST' and form.is_valid():
410                    form.save()
411                return {'active_menu':'personality',
412                        'profile': user,
413                        'form': form,
414                        'TEMPLATE': 'forum/profile/profile_personality.html'
415                        }
416            elif section == 'messaging':
417                form = build_form(MessagingProfileForm, request, instance=user.forum_profile)
418                if request.method == 'POST' and form.is_valid():
419                    form.save()
420                return {'active_menu':'messaging',
421                        'profile': user,
422                        'form': form,
423                        'TEMPLATE': 'forum/profile/profile_messaging.html'
424                       }
425            elif section == 'personal':
426                form = build_form(PersonalProfileForm, request, instance=user.forum_profile, user=user)
427                if request.method == 'POST' and form.is_valid():
428                    form.save()
429                return {'active_menu':'personal',
430                        'profile': user,
431                        'form': form,
432                        'TEMPLATE': 'forum/profile/profile_personal.html'
433                       }
434            elif section == 'essentials':
435                form = build_form(EssentialsProfileForm, request, instance=user.forum_profile, 
436                                  user_view=user, user_request=request.user)
437                if request.method == 'POST' and form.is_valid():
438                    profile = form.save()
439                    set_language(request, profile.language)
440                    return HttpResponseRedirect(reverse('djangobb:forum_profile', args=[user.username]))
441                   
442                return {'active_menu':'essentials',
443                        'profile': user,
444                        'form': form,
445                        'TEMPLATE': 'forum/profile/profile_essentials.html'
446                        }
447               
448        elif 'action' in request.GET:
449            action = request.GET['action']
450            if action == 'upload_avatar':
451                form = build_form(UploadAvatarForm, request, instance=user.forum_profile)
452                if request.method == 'POST' and form.is_valid():
453                    form.save()
454                    return HttpResponseRedirect(reverse('djangobb:forum_profile', args=[user.username]))
455                return {'form': form,
456                        'avatar_width': forum_settings.AVATAR_WIDTH,
457                        'avatar_height': forum_settings.AVATAR_HEIGHT,
458                        'TEMPLATE': 'forum/upload_avatar.html'
459                       }
460            elif action == 'delete_avatar':
461                profile = get_object_or_404(Profile, user=request.user)
462                profile.avatar = None
463                profile.save()
464                return HttpResponseRedirect(reverse('djangobb:forum_profile', args=[user.username]))
465         
466        else:
467            form = build_form(EssentialsProfileForm, request, instance=user.forum_profile, 
468                                  user_view=user, user_request=request.user)
469            if request.method == 'POST' and form.is_valid():
470                profile = form.save()
471                set_language(request, profile.language)
472                return HttpResponseRedirect(reverse('djangobb:forum_profile', args=[user.username]))
473            return {'active_menu':'essentials',
474                    'profile': user,
475                    'form': form,
476                    'TEMPLATE': 'forum/profile/profile_essentials.html'
477                   }
478           
479    else:
480        topic_count = Topic.objects.filter(user=user).count()
481        if user.forum_profile.post_count < forum_settings.POST_USER_SEARCH and not request.user.is_authenticated():
482            return HttpResponseRedirect(reverse('user_signin') + '?next=%s' % request.path)
483        return {'profile': user,
484                'topic_count': topic_count,
485               }
486
487
488@login_required
489@render_to('forum/reputation.html')
490def reputation(request, username):
491    user = get_object_or_404(User, username=username)
492    form = build_form(ReputationForm, request, from_user=request.user, to_user=user)
493
494    if 'action' in request.GET:
495        if 'topic_id' in request.GET:
496            sign = 0
497            topic_id = request.GET['topic_id']
498            form.fields['topic'].initial = topic_id
499            if request.GET['action'] == 'plus':
500                form.fields['sign'].initial = 1
501            elif request.GET['action'] == 'minus':
502                form.fields['sign'].initial = -1
503            return {'form': form,
504                    'TEMPLATE': 'forum/reputation_form.html'
505                    }
506        else:
507            raise Http404
508
509    elif request.method == 'POST':
510        if 'del_reputation' in request.POST:
511            reputation_list = request.POST.getlist('reputation_id')
512            for reputation_id in reputation_list:
513                    reputation = get_object_or_404(Reputation, pk=reputation_id)
514                    reputation.delete()
515            return HttpResponseRedirect(reverse('djangobb:index'))
516        elif form.is_valid():
517            form.save()
518            topic_id = request.POST['topic']
519            topic = get_object_or_404(Topic, id=topic_id)
520            return HttpResponseRedirect(topic.get_absolute_url())
521        else:
522            raise Http404
523    else:
524        reputations = Reputation.objects.filter(to_user=user).order_by('-time').select_related()
525        return {'reputations': reputations,
526                'profile': user.forum_profile,
527               }
528
529
530def show_post(request, post_id):
531    post = get_object_or_404(Post, pk=post_id)
532    count = post.topic.posts.filter(created__lt=post.created).count() + 1
533    page = math.ceil(count / float(forum_settings.TOPIC_PAGE_SIZE))
534    url = '%s?page=%d#post-%d' % (reverse('djangobb:topic', args=[post.topic.id]), page, post.id)
535    return HttpResponseRedirect(url)
536
537
538@login_required
539@render_to('forum/edit_post.html')
540def edit_post(request, post_id):
541    from djangobb_forum.templatetags.forum_extras import forum_editable_by
542
543    post = get_object_or_404(Post, pk=post_id)
544    topic = post.topic
545    if not forum_editable_by(post, request.user):
546        return HttpResponseRedirect(post.get_absolute_url())
547    form = build_form(EditPostForm, request, topic=topic, instance=post)
548    if form.is_valid():
549        post = form.save()
550        return HttpResponseRedirect(post.get_absolute_url())
551
552    return {'form': form,
553            'post': post,
554            }
555
556
557@login_required
558@render_to('forum/delete_posts.html')
559@paged('posts', forum_settings.TOPIC_PAGE_SIZE)
560def delete_posts(request, topic_id):
561
562    topic = Topic.objects.select_related().get(pk=topic_id)
563
564    if forum_moderated_by(topic, request.user):
565        deleted = False
566        post_list = request.POST.getlist('post')
567        for post_id in post_list:
568            if not deleted:
569                deleted = True
570            delete_post(request, post_id)
571        if deleted:
572            return HttpResponseRedirect(topic.get_absolute_url())
573
574    last_post = topic.posts.latest()
575
576    if request.user.is_authenticated():
577        topic.update_read(request.user)
578
579    posts = topic.posts.all().select_related()
580
581    profiles = Profile.objects.filter(user__pk__in=set(x.user.id for x in posts))
582    profiles = dict((x.user_id, x) for x in profiles)
583   
584    for post in posts:
585        post.user.forum_profile = profiles[post.user.id]
586
587    initial = {}
588    if request.user.is_authenticated():
589        initial = {'markup': request.user.forum_profile.markup}
590    form = AddPostForm(topic=topic, initial=initial)
591
592    moderator = request.user.is_superuser or\
593        request.user in topic.forum.moderators.all()
594    if request.user.is_authenticated() and request.user in topic.subscribers.all():
595        subscribed = True
596    else:
597        subscribed = False
598    return {
599            'topic': topic,
600            'last_post': last_post,
601            'form': form,
602            'moderator': moderator,
603            'subscribed': subscribed,
604            'paged_qs': posts,
605            }
606
607
608@login_required
609@render_to('forum/move_topic.html')
610def move_topic(request):
611    if 'topic_id' in request.GET:
612        #if move only 1 topic
613        topic_ids = [request.GET['topic_id']]
614    else:
615        topic_ids = request.POST.getlist('topic_id')
616    first_topic = topic_ids[0]
617    topic = get_object_or_404(Topic, pk=first_topic)
618    from_forum = topic.forum
619    if 'to_forum' in request.POST:
620        to_forum_id = int(request.POST['to_forum'])
621        to_forum = get_object_or_404(Forum, pk=to_forum_id)
622        for topic_id in topic_ids:
623            topic = get_object_or_404(Topic, pk=topic_id)
624            if topic.forum != to_forum:
625                if forum_moderated_by(topic, request.user):
626                    topic.forum = to_forum
627                    topic.save()
628
629        #TODO: not DRY
630        try:
631            last_post = Post.objects.filter(topic__forum=from_forum).latest()
632        except Post.DoesNotExist:
633            last_post = None
634        from_forum.last_post = last_post
635        from_forum.topic_count = from_forum.topics.count()
636        from_forum.post_count = from_forum.posts.count()
637        from_forum.save()
638        return HttpResponseRedirect(to_forum.get_absolute_url())
639
640    return {'categories': Category.objects.all(),
641            'topic_ids': topic_ids,
642            'exclude_forum': from_forum,
643            }
644
645
646@login_required
647def stick_unstick_topic(request, topic_id):
648
649    topic = get_object_or_404(Topic, pk=topic_id)
650    if forum_moderated_by(topic, request.user):
651        topic.sticky = not topic.sticky
652        topic.save()
653    return HttpResponseRedirect(topic.get_absolute_url())
654
655
656@login_required
657@render_to('forum/delete_post.html')
658def delete_post(request, post_id):
659    post = get_object_or_404(Post, pk=post_id)
660    last_post = post.topic.last_post
661    topic = post.topic
662    forum = post.topic.forum
663
664    allowed = False
665    if request.user.is_superuser or\
666        request.user in post.topic.forum.moderators.all() or \
667        (post.user == request.user and post == last_post):
668        allowed = True
669
670    if not allowed:
671        return HttpResponseRedirect(post.get_absolute_url())
672
673    post.delete()
674    profile = post.user.forum_profile
675    profile.post_count = Post.objects.filter(user=post.user).count()
676    profile.save()
677
678    try:
679        Topic.objects.get(pk=topic.id)
680    except Topic.DoesNotExist:
681        #removed latest post in topic
682        return HttpResponseRedirect(forum.get_absolute_url())
683    else:
684        return HttpResponseRedirect(topic.get_absolute_url())
685
686
687@login_required
688def open_close_topic(request, topic_id):
689
690    topic = get_object_or_404(Topic, pk=topic_id)
691    if forum_moderated_by(topic, request.user):
692        topic.closed = not topic.closed
693        topic.save()
694    return HttpResponseRedirect(topic.get_absolute_url())
695
696
697@render_to('forum/users.html')
698@paged('users', forum_settings.USERS_PAGE_SIZE)
699def users(request):
700    users = User.objects.filter(forum_profile__post_count__gte=forum_settings.POST_USER_SEARCH).order_by('username')
701    form = UserSearchForm(request.GET)
702    users = form.filter(users)
703    return {'paged_qs': users,
704            'form': form,
705            }
706
707
708@login_required
709@render_to('forum/pm/create_pm.html')
710def create_pm(request):
711    recipient = request.GET.get('recipient', '')
712    form = build_form(CreatePMForm, request, user=request.user,
713                      initial={'markup': request.user.forum_profile.markup,
714                               'recipient': recipient})
715
716    if form.is_valid():
717        post = form.save();
718        return HttpResponseRedirect(reverse('djangobb:forum_pm_outbox'))
719
720    return {'active_menu':'create',
721            'form': form,
722            }
723
724
725@login_required
726@render_to('forum/pm/outbox.html')
727def pm_outbox(request):
728    messages = PrivateMessage.objects.filter(src_user=request.user)
729    return {'active_menu':'outbox',
730            'messages': messages,
731            }
732
733
734@login_required
735@render_to('forum/pm/inbox.html')
736def pm_inbox(request):
737    messages = PrivateMessage.objects.filter(dst_user=request.user)
738    return {'active_menu':'inbox',
739            'messages': messages,
740            }
741
742
743@login_required
744@render_to('forum/pm/message.html')
745def show_pm(request, pm_id):
746    msg = get_object_or_404(PrivateMessage, pk=pm_id)
747    if not request.user in [msg.dst_user, msg.src_user]:
748        return HttpRedirectException('/')
749    if request.user == msg.dst_user:
750        inbox = True
751        post_user = msg.src_user
752    else:
753        inbox = False
754        post_user = msg.dst_user
755    if not msg.read:
756        msg.read = True
757        msg.save()
758    return {'msg': msg,
759            'inbox': inbox,
760            'post_user': post_user,
761            }
762
763
764@login_required
765def delete_subscription(request, topic_id):
766    topic = get_object_or_404(Topic, pk=topic_id)
767    topic.subscribers.remove(request.user)
768    if 'from_topic' in request.GET:
769        return HttpResponseRedirect(reverse('djangobb:topic', args=[topic.id]))
770    else:
771        return HttpResponseRedirect(reverse('djangobb:edit_profile'))
772
773
774@login_required
775def add_subscription(request, topic_id):
776    topic = get_object_or_404(Topic, pk=topic_id)
777    topic.subscribers.add(request.user)
778    return HttpResponseRedirect(reverse('djangobb:topic', args=[topic.id]))
779
780
781@login_required
782def show_attachment(request, hash):
783    attachment = get_object_or_404(Attachment, hash=hash)
784    file_data = file(attachment.get_absolute_path()).read()
785    response = HttpResponse(file_data, mimetype=attachment.content_type)
786    response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(attachment.name)
787    return response
788
789#TODO: check markup
790@render_to('forum/post_preview.html')
791def post_preview(request):
792    '''Preview for markitup'''
793    data = mypostmarkup.markup(request.POST.get('data', ''), auto_urls=False)
794    data = urlize(data)
795    data = smiles(data)
796    return {'data': data}
Note: See TracBrowser for help on using the repository browser.