2 from forum import settings
3 from django.core.exceptions import ObjectDoesNotExist
4 from django.utils import simplejson
5 from django.http import HttpResponse, HttpResponseRedirect, HttpResponseForbidden
6 from django.shortcuts import get_object_or_404, render_to_response
7 from django.utils.translation import ungettext, ugettext as _
8 from django.template import RequestContext
9 from forum.models import *
10 from forum.actions import *
11 from django.core.urlresolvers import reverse
12 from django.contrib.auth.decorators import login_required
13 from forum.utils.decorators import ajax_method, ajax_login_required
14 from forum.modules.decorators import decoratable
15 from decorators import command, CommandException
16 from forum import settings
19 class NotEnoughRepPointsException(CommandException):
20 def __init__(self, action):
21 super(NotEnoughRepPointsException, self).__init__(
23 Sorry, but you don't have enough reputation points to %(action)s.<br />
24 Please check the <a href'%(faq_url)s'>faq</a>
25 """ % {'action': action, 'faq_url': reverse('faq')})
28 class CannotDoOnOwnException(CommandException):
29 def __init__(self, action):
30 super(CannotDoOnOwnException, self).__init__(
32 Sorry but you cannot %(action)s your own post.<br />
33 Please check the <a href'%(faq_url)s'>faq</a>
34 """ % {'action': action, 'faq_url': reverse('faq')})
37 class AnonymousNotAllowedException(CommandException):
38 def __init__(self, action):
39 super(AnonymousNotAllowedException, self).__init__(
41 Sorry but anonymous users cannot %(action)s.<br />
42 Please login or create an account <a href'%(signin_url)s'>here</a>.
43 """ % {'action': action, 'signin_url': reverse('auth_signin')})
46 class NotEnoughLeftException(CommandException):
47 def __init__(self, action, limit):
48 super(NotEnoughLeftException, self).__init__(
50 Sorry, but you don't have enough %(action)s left for today..<br />
51 The limit is %(limit)s per day..<br />
52 Please check the <a href'%(faq_url)s'>faq</a>
53 """ % {'action': action, 'limit': limit, 'faq_url': reverse('faq')})
56 class CannotDoubleActionException(CommandException):
57 def __init__(self, action):
58 super(CannotDoubleActionException, self).__init__(
60 Sorry, but you cannot %(action)s twice the same post.<br />
61 Please check the <a href'%(faq_url)s'>faq</a>
62 """ % {'action': action, 'faq_url': reverse('faq')})
67 def vote_post(request, id, vote_type):
68 post = get_object_or_404(Node, id=id).leaf
71 if not user.is_authenticated():
72 raise AnonymousNotAllowedException(_('vote'))
74 if user == post.author:
75 raise CannotDoOnOwnException(_('vote'))
77 if not (vote_type == 'up' and user.can_vote_up() or user.can_vote_down()):
78 raise NotEnoughRepPointsException(vote_type == 'up' and _('upvote') or _('downvote'))
80 user_vote_count_today = user.get_vote_count_today()
82 if user_vote_count_today >= int(settings.MAX_VOTES_PER_DAY):
83 raise NotEnoughLeftException(_('votes'), str(settings.MAX_VOTES_PER_DAY))
85 new_vote_cls = (vote_type == 'up') and VoteUpAction or VoteDownAction
89 old_vote = Action.objects.get_for_types((VoteUpAction, VoteDownAction), node=post, user=user)
91 if old_vote.action_date < datetime.datetime.now() - datetime.timedelta(days=int(settings.DENY_UNVOTE_DAYS)):
92 raise CommandException(
93 _("Sorry but you cannot cancel a vote after %(ndays)d %(tdays)s from the original vote") %
94 {'ndays': int(settings.DENY_UNVOTE_DAYS), 'tdays': ungettext('day', 'days', int(settings.DENY_UNVOTE_DAYS))}
97 old_vote.cancel(ip=request.META['REMOTE_ADDR'])
98 score_inc += (old_vote.__class__ == VoteDownAction) and 1 or -1
99 except ObjectDoesNotExist:
102 if old_vote.__class__ != new_vote_cls:
103 new_vote_cls(user=user, node=post, ip=request.META['REMOTE_ADDR']).save()
104 score_inc += (new_vote_cls == VoteUpAction) and 1 or -1
110 'update_post_score': [id, score_inc],
111 'update_user_post_vote': [id, vote_type]
115 votes_left = (int(settings.MAX_VOTES_PER_DAY) - user_vote_count_today) + (vote_type == 'none' and -1 or 1)
117 if int(settings.START_WARN_VOTES_LEFT) >= votes_left:
118 response['message'] = _("You have %(nvotes)s %(tvotes)s left today.") % \
119 {'nvotes': votes_left, 'tvotes': ungettext('vote', 'votes', votes_left)}
124 def flag_post(request, id):
126 return render_to_response('node/report.html', {'types': settings.FLAG_TYPES})
128 post = get_object_or_404(Node, id=id)
131 if not user.is_authenticated():
132 raise AnonymousNotAllowedException(_('flag posts'))
134 if user == post.author:
135 raise CannotDoOnOwnException(_('flag'))
137 if not (user.can_flag_offensive(post)):
138 raise NotEnoughRepPointsException(_('flag posts'))
140 user_flag_count_today = user.get_flagged_items_count_today()
142 if user_flag_count_today >= int(settings.MAX_FLAGS_PER_DAY):
143 raise NotEnoughLeftException(_('flags'), str(settings.MAX_FLAGS_PER_DAY))
146 current = FlagAction.objects.get(user=user, node=post)
147 raise CommandException(_("You already flagged this post with the following reason: %(reason)s") % {'reason': current.extra})
148 except ObjectDoesNotExist:
149 reason = request.POST.get('prompt', '').strip()
152 raise CommandException(_("Reason is empty"))
154 FlagAction(user=user, node=post, extra=reason, ip=request.META['REMOTE_ADDR']).save()
156 return {'message': _("Thank you for your report. A moderator will review your submission shortly.")}
159 def like_comment(request, id):
160 comment = get_object_or_404(Comment, id=id)
163 if not user.is_authenticated():
164 raise AnonymousNotAllowedException(_('like comments'))
166 if user == comment.user:
167 raise CannotDoOnOwnException(_('like'))
169 if not user.can_like_comment(comment):
170 raise NotEnoughRepPointsException( _('like comments'))
173 like = VoteUpCommentAction.objects.get(node=comment, user=user)
174 like.cancel(ip=request.META['REMOTE_ADDR'])
176 except ObjectDoesNotExist:
177 VoteUpCommentAction(node=comment, user=user, ip=request.META['REMOTE_ADDR']).save()
182 'update_post_score': [comment.id, likes and 1 or -1],
183 'update_user_post_vote': [comment.id, likes and 'up' or 'none']
188 def delete_comment(request, id):
189 comment = get_object_or_404(Comment, id=id)
192 if not user.is_authenticated():
193 raise AnonymousNotAllowedException(_('delete comments'))
195 if not user.can_delete_comment(comment):
196 raise NotEnoughRepPointsException( _('delete comments'))
198 if not comment.deleted:
199 DeleteAction(node=comment, user=user, ip=request.META['REMOTE_ADDR']).save()
203 'remove_comment': [comment.id],
208 def mark_favorite(request, id):
209 question = get_object_or_404(Question, id=id)
211 if not request.user.is_authenticated():
212 raise AnonymousNotAllowedException(_('mark a question as favorite'))
215 favorite = FavoriteAction.objects.get(node=question, user=request.user)
216 favorite.cancel(ip=request.META['REMOTE_ADDR'])
218 except ObjectDoesNotExist:
219 FavoriteAction(node=question, user=request.user, ip=request.META['REMOTE_ADDR']).save()
224 'update_favorite_count': [added and 1 or -1],
225 'update_favorite_mark': [added and 'on' or 'off']
231 def comment(request, id):
232 post = get_object_or_404(Node, id=id)
235 if not user.is_authenticated():
236 raise AnonymousNotAllowedException(_('comment'))
238 if not request.method == 'POST':
239 raise CommandException(_("Invalid request"))
241 comment_text = request.POST.get('comment', '').strip()
243 if not len(comment_text):
244 raise CommandException(_("Comment is empty"))
246 if len(comment_text) < settings.FORM_MIN_COMMENT_BODY:
247 raise CommandException(_("At least %d characters required on comment body.") % settings.FORM_MIN_COMMENT_BODY)
249 if len(comment_text) > settings.FORM_MAX_COMMENT_BODY:
250 raise CommandException(_("No more than %d characters on comment body.") % settings.FORM_MAX_COMMENT_BODY)
252 if 'id' in request.POST:
253 comment = get_object_or_404(Comment, id=request.POST['id'])
255 if not user.can_edit_comment(comment):
256 raise NotEnoughRepPointsException( _('edit comments'))
258 comment = ReviseAction(user=user, node=comment, ip=request.META['REMOTE_ADDR']).save(data=dict(text=comment_text)).node
260 if not user.can_comment(post):
261 raise NotEnoughRepPointsException( _('comment'))
263 comment = CommentAction(user=user, ip=request.META['REMOTE_ADDR']).save(data=dict(text=comment_text, parent=post)).node
265 if comment.active_revision.revision == 1:
269 id, comment.id, comment.comment, user.username, user.get_profile_url(),
270 reverse('delete_comment', kwargs={'id': comment.id}), reverse('node_markdown', kwargs={'id': comment.id})
277 'update_comment': [comment.id, comment.comment]
282 def node_markdown(request, id):
285 if not user.is_authenticated():
286 raise AnonymousNotAllowedException(_('accept answers'))
288 node = get_object_or_404(Node, id=id)
289 return HttpResponse(node.body, mimetype="text/plain")
293 def accept_answer(request, id):
296 if not user.is_authenticated():
297 raise AnonymousNotAllowedException(_('accept answers'))
299 answer = get_object_or_404(Answer, id=id)
300 question = answer.question
302 if not user.can_accept_answer(answer):
303 raise CommandException(_("Sorry but only the question author can accept an answer"))
308 answer.accepted.cancel(user, ip=request.META['REMOTE_ADDR'])
309 commands['unmark_accepted'] = [answer.id]
311 if question.answer_accepted:
312 accepted = question.accepted_answer
313 accepted.accepted.cancel(user, ip=request.META['REMOTE_ADDR'])
314 commands['unmark_accepted'] = [accepted.id]
316 AcceptAnswerAction(node=answer, user=user, ip=request.META['REMOTE_ADDR']).save()
317 commands['mark_accepted'] = [answer.id]
319 return {'commands': commands}
322 def delete_post(request, id):
323 post = get_object_or_404(Node, id=id)
326 if not user.is_authenticated():
327 raise AnonymousNotAllowedException(_('delete posts'))
329 if not (user.can_delete_post(post)):
330 raise NotEnoughRepPointsException(_('delete posts'))
332 ret = {'commands': {}}
335 post.deleted.cancel(user, ip=request.META['REMOTE_ADDR'])
336 ret['commands']['unmark_deleted'] = [post.node_type, id]
338 DeleteAction(node=post, user=user, ip=request.META['REMOTE_ADDR']).save()
340 ret['commands']['mark_deleted'] = [post.node_type, id]
345 def close(request, id, close):
346 if close and not request.POST:
347 return render_to_response('node/report.html', {'types': settings.CLOSE_TYPES})
349 question = get_object_or_404(Question, id=id)
352 if not user.is_authenticated():
353 raise AnonymousNotAllowedException(_('close questions'))
355 if question.extra_action:
356 if not user.can_reopen_question(question):
357 raise NotEnoughRepPointsException(_('reopen questions'))
359 question.extra_action.cancel(user, ip=request.META['REMOTE_ADDR'])
361 if not request.user.can_close_question(question):
362 raise NotEnoughRepPointsException(_('close questions'))
364 reason = request.POST.get('prompt', '').strip()
367 raise CommandException(_("Reason is empty"))
369 CloseAction(node=question, user=user, extra=reason, ip=request.META['REMOTE_ADDR']).save()
378 def subscribe(request, id):
379 question = get_object_or_404(Question, id=id)
382 subscription = QuestionSubscription.objects.get(question=question, user=request.user)
383 subscription.delete()
386 subscription = QuestionSubscription(question=question, user=request.user, auto_subscription=False)
392 'set_subscription_button': [subscribed and _('unsubscribe me') or _('subscribe me')],
393 'set_subscription_status': ['']
397 #internally grouped views - used by the tagging system
399 def mark_tag(request, tag=None, **kwargs):#tagging system
400 action = kwargs['action']
401 ts = MarkedTag.objects.filter(user=request.user, tag__name=tag)
402 if action == 'remove':
403 logging.debug('deleting tag %s' % tag)
406 reason = kwargs['reason']
409 t = Tag.objects.get(name=tag)
410 mt = MarkedTag(user=request.user, reason=reason, tag=t)
415 ts.update(reason=reason)
416 return HttpResponse(simplejson.dumps(''), mimetype="application/json")
418 def matching_tags(request):
419 if len(request.GET['q']) == 0:
420 raise CommandException(_("Invalid request"))
422 possible_tags = Tag.objects.filter(name__istartswith = request.GET['q'])
424 for tag in possible_tags:
425 tag_output += (tag.name + "|" + tag.name + "." + tag.used_count.__str__() + "\n")
427 return HttpResponse(tag_output, mimetype="text/plain")