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__(
22 _("""Sorry, but you don't have enough reputation points to %(action)s.<br />Please check the <a href='%(faq_url)s'>faq</a>""") % {'action': action, 'faq_url': reverse('faq')}
25 class CannotDoOnOwnException(CommandException):
26 def __init__(self, action):
27 super(CannotDoOnOwnException, self).__init__(
28 _("""Sorry but you cannot %(action)s your own post.<br />Please check the <a href='%(faq_url)s'>faq</a>""") % {'action': action, 'faq_url': reverse('faq')}
31 class AnonymousNotAllowedException(CommandException):
32 def __init__(self, action):
33 super(AnonymousNotAllowedException, self).__init__(
34 _("""Sorry but anonymous users cannot %(action)s.<br />Please login or create an account <a href='%(signin_url)s'>here</a>.""") % {'action': action, 'signin_url': reverse('auth_signin')}
37 class NotEnoughLeftException(CommandException):
38 def __init__(self, action, limit):
39 super(NotEnoughLeftException, self).__init__(
40 _("""Sorry, but you don't have enough %(action)s left for today..<br />The limit is %(limit)s per day..<br />Please check the <a href='%(faq_url)s'>faq</a>""") % {'action': action, 'limit': limit, 'faq_url': reverse('faq')}
43 class CannotDoubleActionException(CommandException):
44 def __init__(self, action):
45 super(CannotDoubleActionException, self).__init__(
46 _("""Sorry, but you cannot %(action)s twice the same post.<br />Please check the <a href='%(faq_url)s'>faq</a>""") % {'action': action, 'faq_url': reverse('faq')}
51 def vote_post(request, id, vote_type):
52 post = get_object_or_404(Node, id=id).leaf
55 if not user.is_authenticated():
56 raise AnonymousNotAllowedException(_('vote'))
58 if user == post.author:
59 raise CannotDoOnOwnException(_('vote'))
61 if not (vote_type == 'up' and user.can_vote_up() or user.can_vote_down()):
62 raise NotEnoughRepPointsException(vote_type == 'up' and _('upvote') or _('downvote'))
64 user_vote_count_today = user.get_vote_count_today()
66 if user_vote_count_today >= int(settings.MAX_VOTES_PER_DAY):
67 raise NotEnoughLeftException(_('votes'), str(settings.MAX_VOTES_PER_DAY))
69 new_vote_cls = (vote_type == 'up') and VoteUpAction or VoteDownAction
73 old_vote = Action.objects.get_for_types((VoteUpAction, VoteDownAction), node=post, user=user)
75 if old_vote.action_date < datetime.datetime.now() - datetime.timedelta(days=int(settings.DENY_UNVOTE_DAYS)):
76 raise CommandException(
77 _("Sorry but you cannot cancel a vote after %(ndays)d %(tdays)s from the original vote") %
78 {'ndays': int(settings.DENY_UNVOTE_DAYS), 'tdays': ungettext('day', 'days', int(settings.DENY_UNVOTE_DAYS))}
81 old_vote.cancel(ip=request.META['REMOTE_ADDR'])
82 score_inc += (old_vote.__class__ == VoteDownAction) and 1 or -1
83 except ObjectDoesNotExist:
86 if old_vote.__class__ != new_vote_cls:
87 new_vote_cls(user=user, node=post, ip=request.META['REMOTE_ADDR']).save()
88 score_inc += (new_vote_cls == VoteUpAction) and 1 or -1
94 'update_post_score': [id, score_inc],
95 'update_user_post_vote': [id, vote_type]
99 votes_left = (int(settings.MAX_VOTES_PER_DAY) - user_vote_count_today) + (vote_type == 'none' and -1 or 1)
101 if int(settings.START_WARN_VOTES_LEFT) >= votes_left:
102 response['message'] = _("You have %(nvotes)s %(tvotes)s left today.") % \
103 {'nvotes': votes_left, 'tvotes': ungettext('vote', 'votes', votes_left)}
108 def flag_post(request, id):
110 return render_to_response('node/report.html', {'types': settings.FLAG_TYPES})
112 post = get_object_or_404(Node, id=id)
115 if not user.is_authenticated():
116 raise AnonymousNotAllowedException(_('flag posts'))
118 if user == post.author:
119 raise CannotDoOnOwnException(_('flag'))
121 if not (user.can_flag_offensive(post)):
122 raise NotEnoughRepPointsException(_('flag posts'))
124 user_flag_count_today = user.get_flagged_items_count_today()
126 if user_flag_count_today >= int(settings.MAX_FLAGS_PER_DAY):
127 raise NotEnoughLeftException(_('flags'), str(settings.MAX_FLAGS_PER_DAY))
130 current = FlagAction.objects.get(user=user, node=post)
131 raise CommandException(_("You already flagged this post with the following reason: %(reason)s") % {'reason': current.extra})
132 except ObjectDoesNotExist:
133 reason = request.POST.get('prompt', '').strip()
136 raise CommandException(_("Reason is empty"))
138 FlagAction(user=user, node=post, extra=reason, ip=request.META['REMOTE_ADDR']).save()
140 return {'message': _("Thank you for your report. A moderator will review your submission shortly.")}
143 def like_comment(request, id):
144 comment = get_object_or_404(Comment, id=id)
147 if not user.is_authenticated():
148 raise AnonymousNotAllowedException(_('like comments'))
150 if user == comment.user:
151 raise CannotDoOnOwnException(_('like'))
153 if not user.can_like_comment(comment):
154 raise NotEnoughRepPointsException( _('like comments'))
157 like = VoteUpCommentAction.objects.get(node=comment, user=user)
158 like.cancel(ip=request.META['REMOTE_ADDR'])
160 except ObjectDoesNotExist:
161 VoteUpCommentAction(node=comment, user=user, ip=request.META['REMOTE_ADDR']).save()
166 'update_post_score': [comment.id, likes and 1 or -1],
167 'update_user_post_vote': [comment.id, likes and 'up' or 'none']
172 def delete_comment(request, id):
173 comment = get_object_or_404(Comment, id=id)
176 if not user.is_authenticated():
177 raise AnonymousNotAllowedException(_('delete comments'))
179 if not user.can_delete_comment(comment):
180 raise NotEnoughRepPointsException( _('delete comments'))
182 if not comment.deleted:
183 DeleteAction(node=comment, user=user, ip=request.META['REMOTE_ADDR']).save()
187 'remove_comment': [comment.id],
192 def mark_favorite(request, id):
193 question = get_object_or_404(Question, id=id)
195 if not request.user.is_authenticated():
196 raise AnonymousNotAllowedException(_('mark a question as favorite'))
199 favorite = FavoriteAction.objects.get(node=question, user=request.user)
200 favorite.cancel(ip=request.META['REMOTE_ADDR'])
202 except ObjectDoesNotExist:
203 FavoriteAction(node=question, user=request.user, ip=request.META['REMOTE_ADDR']).save()
208 'update_favorite_count': [added and 1 or -1],
209 'update_favorite_mark': [added and 'on' or 'off']
215 def comment(request, id):
216 post = get_object_or_404(Node, id=id)
219 if not user.is_authenticated():
220 raise AnonymousNotAllowedException(_('comment'))
222 if not request.method == 'POST':
223 raise CommandException(_("Invalid request"))
225 comment_text = request.POST.get('comment', '').strip()
227 if not len(comment_text):
228 raise CommandException(_("Comment is empty"))
230 if len(comment_text) < settings.FORM_MIN_COMMENT_BODY:
231 raise CommandException(_("At least %d characters required on comment body.") % settings.FORM_MIN_COMMENT_BODY)
233 if len(comment_text) > settings.FORM_MAX_COMMENT_BODY:
234 raise CommandException(_("No more than %d characters on comment body.") % settings.FORM_MAX_COMMENT_BODY)
236 if 'id' in request.POST:
237 comment = get_object_or_404(Comment, id=request.POST['id'])
239 if not user.can_edit_comment(comment):
240 raise NotEnoughRepPointsException( _('edit comments'))
242 comment = ReviseAction(user=user, node=comment, ip=request.META['REMOTE_ADDR']).save(data=dict(text=comment_text)).node
244 if not user.can_comment(post):
245 raise NotEnoughRepPointsException( _('comment'))
247 comment = CommentAction(user=user, ip=request.META['REMOTE_ADDR']).save(data=dict(text=comment_text, parent=post)).node
249 if comment.active_revision.revision == 1:
253 id, comment.id, comment.comment, user.username, user.get_profile_url(),
254 reverse('delete_comment', kwargs={'id': comment.id}), reverse('node_markdown', kwargs={'id': comment.id})
261 'update_comment': [comment.id, comment.comment]
266 def node_markdown(request, id):
269 if not user.is_authenticated():
270 raise AnonymousNotAllowedException(_('accept answers'))
272 node = get_object_or_404(Node, id=id)
273 return HttpResponse(node.body, mimetype="text/plain")
277 def accept_answer(request, id):
280 if not user.is_authenticated():
281 raise AnonymousNotAllowedException(_('accept answers'))
283 answer = get_object_or_404(Answer, id=id)
284 question = answer.question
286 if not user.can_accept_answer(answer):
287 raise CommandException(_("Sorry but only the question author can accept an answer"))
292 answer.accepted.cancel(user, ip=request.META['REMOTE_ADDR'])
293 commands['unmark_accepted'] = [answer.id]
295 if question.answer_accepted:
296 accepted = question.accepted_answer
297 accepted.accepted.cancel(user, ip=request.META['REMOTE_ADDR'])
298 commands['unmark_accepted'] = [accepted.id]
300 AcceptAnswerAction(node=answer, user=user, ip=request.META['REMOTE_ADDR']).save()
301 commands['mark_accepted'] = [answer.id]
303 return {'commands': commands}
306 def delete_post(request, id):
307 post = get_object_or_404(Node, id=id)
310 if not user.is_authenticated():
311 raise AnonymousNotAllowedException(_('delete posts'))
313 if not (user.can_delete_post(post)):
314 raise NotEnoughRepPointsException(_('delete posts'))
316 ret = {'commands': {}}
319 post.deleted.cancel(user, ip=request.META['REMOTE_ADDR'])
320 ret['commands']['unmark_deleted'] = [post.node_type, id]
322 DeleteAction(node=post, user=user, ip=request.META['REMOTE_ADDR']).save()
324 ret['commands']['mark_deleted'] = [post.node_type, id]
329 def close(request, id, close):
330 if close and not request.POST:
331 return render_to_response('node/report.html', {'types': settings.CLOSE_TYPES})
333 question = get_object_or_404(Question, id=id)
336 if not user.is_authenticated():
337 raise AnonymousNotAllowedException(_('close questions'))
339 if question.extra_action:
340 if not user.can_reopen_question(question):
341 raise NotEnoughRepPointsException(_('reopen questions'))
343 question.extra_action.cancel(user, ip=request.META['REMOTE_ADDR'])
345 if not request.user.can_close_question(question):
346 raise NotEnoughRepPointsException(_('close questions'))
348 reason = request.POST.get('prompt', '').strip()
351 raise CommandException(_("Reason is empty"))
353 CloseAction(node=question, user=user, extra=reason, ip=request.META['REMOTE_ADDR']).save()
362 def subscribe(request, id):
363 question = get_object_or_404(Question, id=id)
366 subscription = QuestionSubscription.objects.get(question=question, user=request.user)
367 subscription.delete()
370 subscription = QuestionSubscription(question=question, user=request.user, auto_subscription=False)
376 'set_subscription_button': [subscribed and _('unsubscribe me') or _('subscribe me')],
377 'set_subscription_status': ['']
381 #internally grouped views - used by the tagging system
383 def mark_tag(request, tag=None, **kwargs):#tagging system
384 action = kwargs['action']
385 ts = MarkedTag.objects.filter(user=request.user, tag__name=tag)
386 if action == 'remove':
387 logging.debug('deleting tag %s' % tag)
390 reason = kwargs['reason']
393 t = Tag.objects.get(name=tag)
394 mt = MarkedTag(user=request.user, reason=reason, tag=t)
399 ts.update(reason=reason)
400 return HttpResponse(simplejson.dumps(''), mimetype="application/json")
402 def matching_tags(request):
403 if len(request.GET['q']) == 0:
404 raise CommandException(_("Invalid request"))
406 possible_tags = Tag.objects.filter(name__istartswith = request.GET['q'])
408 for tag in possible_tags:
409 tag_output += (tag.name + "|" + tag.name + "." + tag.used_count.__str__() + "\n")
411 return HttpResponse(tag_output, mimetype="text/plain")