2 from django.conf 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 decorators import command, CommandException
15 from forum import settings
18 class NotEnoughRepPointsException(CommandException):
19 def __init__(self, action):
20 super(NotEnoughRepPointsException, self).__init__(
22 Sorry, but you don't have enough reputation points to %(action)s.<br />
23 Please check the <a href'%(faq_url)s'>faq</a>
24 """ % {'action': action, 'faq_url': reverse('faq')})
27 class CannotDoOnOwnException(CommandException):
28 def __init__(self, action):
29 super(CannotDoOnOwnException, self).__init__(
31 Sorry but you cannot %(action)s your own post.<br />
32 Please check the <a href'%(faq_url)s'>faq</a>
33 """ % {'action': action, 'faq_url': reverse('faq')})
36 class AnonymousNotAllowedException(CommandException):
37 def __init__(self, action):
38 super(AnonymousNotAllowedException, self).__init__(
40 Sorry but anonymous users cannot %(action)s.<br />
41 Please login or create an account <a href'%(signin_url)s'>here</a>.
42 """ % {'action': action, 'signin_url': reverse('auth_signin')})
45 class SpamNotAllowedException(CommandException):
46 def __init__(self, action = "comment"):
47 super(SpamNotAllowedException, self).__init__(
48 _("""Your %s has been marked as spam.""" % action)
51 class NotEnoughLeftException(CommandException):
52 def __init__(self, action, limit):
53 super(NotEnoughLeftException, self).__init__(
55 Sorry, but you don't have enough %(action)s left for today..<br />
56 The limit is %(limit)s per day..<br />
57 Please check the <a href'%(faq_url)s'>faq</a>
58 """ % {'action': action, 'limit': limit, 'faq_url': reverse('faq')})
61 class CannotDoubleActionException(CommandException):
62 def __init__(self, action):
63 super(CannotDoubleActionException, self).__init__(
65 Sorry, but you cannot %(action)s twice the same post.<br />
66 Please check the <a href'%(faq_url)s'>faq</a>
67 """ % {'action': action, 'faq_url': reverse('faq')})
72 def vote_post(request, id, vote_type):
73 post = get_object_or_404(Node, id=id).leaf
76 if not user.is_authenticated():
77 raise AnonymousNotAllowedException(_('vote'))
79 if user == post.author:
80 raise CannotDoOnOwnException(_('vote'))
82 if not (vote_type == 'up' and user.can_vote_up() or user.can_vote_down()):
83 raise NotEnoughRepPointsException(vote_type == 'up' and _('upvote') or _('downvote'))
85 user_vote_count_today = user.get_vote_count_today()
87 if user_vote_count_today >= int(settings.MAX_VOTES_PER_DAY):
88 raise NotEnoughLeftException(_('votes'), str(settings.MAX_VOTES_PER_DAY))
90 new_vote_cls = (vote_type == 'up') and VoteUpAction or VoteDownAction
94 old_vote = Action.objects.get_for_types((VoteUpAction, VoteDownAction), node=post, user=user)
96 if old_vote.action_date < datetime.datetime.now() - datetime.timedelta(days=int(settings.DENY_UNVOTE_DAYS)):
97 raise CommandException(
98 _("Sorry but you cannot cancel a vote after %(ndays)d %(tdays)s from the original vote") %
99 {'ndays': int(settings.DENY_UNVOTE_DAYS), 'tdays': ungettext('day', 'days', int(settings.DENY_UNVOTE_DAYS))}
102 old_vote.cancel(ip=request.META['REMOTE_ADDR'])
103 score_inc += (old_vote.__class__ == VoteDownAction) and 1 or -1
104 except ObjectDoesNotExist:
107 if old_vote.__class__ != new_vote_cls:
108 new_vote_cls(user=user, node=post, ip=request.META['REMOTE_ADDR']).save()
109 score_inc += (new_vote_cls == VoteUpAction) and 1 or -1
115 'update_post_score': [id, score_inc],
116 'update_user_post_vote': [id, vote_type]
120 votes_left = (int(settings.MAX_VOTES_PER_DAY) - user_vote_count_today) + (vote_type == 'none' and -1 or 1)
122 if int(settings.START_WARN_VOTES_LEFT) >= votes_left:
123 response['message'] = _("You have %(nvotes)s %(tvotes)s left today.") % \
124 {'nvotes': votes_left, 'tvotes': ungettext('vote', 'votes', votes_left)}
129 def flag_post(request, id):
131 return render_to_response('node/report.html', {'types': settings.FLAG_TYPES})
133 post = get_object_or_404(Node, id=id)
136 if not user.is_authenticated():
137 raise AnonymousNotAllowedException(_('flag posts'))
139 if user == post.author:
140 raise CannotDoOnOwnException(_('flag'))
142 if not (user.can_flag_offensive(post)):
143 raise NotEnoughRepPointsException(_('flag posts'))
145 user_flag_count_today = user.get_flagged_items_count_today()
147 if user_flag_count_today >= int(settings.MAX_FLAGS_PER_DAY):
148 raise NotEnoughLeftException(_('flags'), str(settings.MAX_FLAGS_PER_DAY))
151 current = FlagAction.objects.get(user=user, node=post)
152 raise CommandException(_("You already flagged this post with the following reason: %(reason)s") % {'reason': current.extra})
153 except ObjectDoesNotExist:
154 reason = request.POST.get('prompt', '').strip()
157 raise CommandException(_("Reason is empty"))
159 FlagAction(user=user, node=post, extra=reason, ip=request.META['REMOTE_ADDR']).save()
161 return {'message': _("Thank you for your report. A moderator will review your submission shortly.")}
164 def like_comment(request, id):
165 comment = get_object_or_404(Comment, id=id)
168 if not user.is_authenticated():
169 raise AnonymousNotAllowedException(_('like comments'))
171 if user == comment.user:
172 raise CannotDoOnOwnException(_('like'))
174 if not user.can_like_comment(comment):
175 raise NotEnoughRepPointsException( _('like comments'))
178 like = VoteUpCommentAction.objects.get(node=comment, user=user)
179 like.cancel(ip=request.META['REMOTE_ADDR'])
181 except ObjectDoesNotExist:
182 VoteUpCommentAction(node=comment, user=user, ip=request.META['REMOTE_ADDR']).save()
187 'update_post_score': [comment.id, likes and 1 or -1],
188 'update_user_post_vote': [comment.id, likes and 'up' or 'none']
193 def delete_comment(request, id):
194 comment = get_object_or_404(Comment, id=id)
197 if not user.is_authenticated():
198 raise AnonymousNotAllowedException(_('delete comments'))
200 if not user.can_delete_comment(comment):
201 raise NotEnoughRepPointsException( _('delete comments'))
203 if not comment.deleted:
204 DeleteAction(node=comment, user=user, ip=request.META['REMOTE_ADDR']).save()
208 'remove_comment': [comment.id],
213 def mark_favorite(request, id):
214 question = get_object_or_404(Question, id=id)
216 if not request.user.is_authenticated():
217 raise AnonymousNotAllowedException(_('mark a question as favorite'))
220 favorite = FavoriteAction.objects.get(node=question, user=request.user)
221 favorite.cancel(ip=request.META['REMOTE_ADDR'])
223 except ObjectDoesNotExist:
224 FavoriteAction(node=question, user=request.user, ip=request.META['REMOTE_ADDR']).save()
229 'update_favorite_count': [added and 1 or -1],
230 'update_favorite_mark': [added and 'on' or 'off']
235 def comment(request, id):
236 post = get_object_or_404(Node, id=id)
239 if not user.is_authenticated():
240 raise AnonymousNotAllowedException(_('comment'))
242 if not request.method == 'POST':
243 raise CommandException(_("Invalid request"))
245 comment_text = request.POST.get('comment', '').strip()
247 if not len(comment_text):
248 raise CommandException(_("Comment is empty"))
250 if len(comment_text) < settings.FORM_MIN_COMMENT_BODY:
251 raise CommandException(_("At least %d characters required on comment body.") % settings.FORM_MIN_COMMENT_BODY)
253 if len(comment_text) > settings.FORM_MAX_COMMENT_BODY:
254 raise CommandException(_("No more than %d characters on comment body.") % settings.FORM_MAX_COMMENT_BODY)
257 "user_ip":request.META["REMOTE_ADDR"],
258 "user_agent":request.environ['HTTP_USER_AGENT'],
259 "comment_author":request.user.username,
260 "comment_author_email":request.user.email,
261 "comment_author_url":request.user.website,
262 "comment":comment_text
264 if Node.isSpam(comment_text, data):
265 raise SpamNotAllowedException()
267 if 'id' in request.POST:
268 comment = get_object_or_404(Comment, id=request.POST['id'])
270 if not user.can_edit_comment(comment):
271 raise NotEnoughRepPointsException( _('edit comments'))
273 comment = ReviseAction(user=user, node=comment, ip=request.META['REMOTE_ADDR']).save(data=dict(text=comment_text)).node
275 if not user.can_comment(post):
276 raise NotEnoughRepPointsException( _('comment'))
278 comment = CommentAction(user=user, ip=request.META['REMOTE_ADDR']).save(data=dict(text=comment_text, parent=post)).node
280 if comment.active_revision.revision == 1:
284 id, comment.id, comment.comment, user.username, user.get_profile_url(),
285 reverse('delete_comment', kwargs={'id': comment.id}), reverse('node_markdown', kwargs={'id': comment.id})
292 'update_comment': [comment.id, comment.comment]
297 def node_markdown(request, id):
300 if not user.is_authenticated():
301 raise AnonymousNotAllowedException(_('accept answers'))
303 node = get_object_or_404(Node, id=id)
304 return HttpResponse(node.body, mimetype="text/plain")
308 def accept_answer(request, id):
311 if not user.is_authenticated():
312 raise AnonymousNotAllowedException(_('accept answers'))
314 answer = get_object_or_404(Answer, id=id)
315 question = answer.question
317 if not user.can_accept_answer(answer):
318 raise CommandException(_("Sorry but only the question author can accept an answer"))
323 answer.accepted.cancel(user, ip=request.META['REMOTE_ADDR'])
324 commands['unmark_accepted'] = [answer.id]
326 if question.answer_accepted:
327 accepted = question.accepted_answer
328 accepted.accepted.cancel(user, ip=request.META['REMOTE_ADDR'])
329 commands['unmark_accepted'] = [accepted.id]
331 AcceptAnswerAction(node=answer, user=user, ip=request.META['REMOTE_ADDR']).save()
332 commands['mark_accepted'] = [answer.id]
334 return {'commands': commands}
337 def delete_post(request, id):
338 post = get_object_or_404(Node, id=id)
341 if not user.is_authenticated():
342 raise AnonymousNotAllowedException(_('delete posts'))
344 if not (user.can_delete_post(post)):
345 raise NotEnoughRepPointsException(_('delete posts'))
347 ret = {'commands': {}}
350 post.deleted.cancel(user, ip=request.META['REMOTE_ADDR'])
351 ret['commands']['unmark_deleted'] = [post.node_type, id]
353 DeleteAction(node=post, user=user, ip=request.META['REMOTE_ADDR']).save()
355 ret['commands']['mark_deleted'] = [post.node_type, id]
360 def close(request, id, close):
361 if close and not request.POST:
362 return render_to_response('node/report.html', {'types': settings.CLOSE_TYPES})
364 question = get_object_or_404(Question, id=id)
367 if not user.is_authenticated():
368 raise AnonymousNotAllowedException(_('close questions'))
370 if question.extra_action:
371 if not user.can_reopen_question(question):
372 raise NotEnoughRepPointsException(_('reopen questions'))
374 question.extra_action.cancel(user, ip=request.META['REMOTE_ADDR'])
376 if not request.user.can_close_question(question):
377 raise NotEnoughRepPointsException(_('close questions'))
379 reason = request.POST.get('prompt', '').strip()
382 raise CommandException(_("Reason is empty"))
384 CloseAction(node=question, user=user, extra=reason, ip=request.META['REMOTE_ADDR']).save()
393 def subscribe(request, id):
394 question = get_object_or_404(Question, id=id)
397 subscription = QuestionSubscription.objects.get(question=question, user=request.user)
398 subscription.delete()
401 subscription = QuestionSubscription(question=question, user=request.user, auto_subscription=False)
407 'set_subscription_button': [subscribed and _('unsubscribe me') or _('subscribe me')],
408 'set_subscription_status': ['']
412 #internally grouped views - used by the tagging system
414 def mark_tag(request, tag=None, **kwargs):#tagging system
415 action = kwargs['action']
416 ts = MarkedTag.objects.filter(user=request.user, tag__name=tag)
417 if action == 'remove':
418 logging.debug('deleting tag %s' % tag)
421 reason = kwargs['reason']
424 t = Tag.objects.get(name=tag)
425 mt = MarkedTag(user=request.user, reason=reason, tag=t)
430 ts.update(reason=reason)
431 return HttpResponse(simplejson.dumps(''), mimetype="application/json")
433 def matching_tags(request):
434 if len(request.GET['q']) == 0:
435 raise CommandException(_("Invalid request"))
437 possible_tags = Tag.objects.filter(name__istartswith = request.GET['q'])
439 for tag in possible_tags:
440 tag_output += (tag.name + "|" + tag.name + "." + tag.used_count.__str__() + "\n")
442 return HttpResponse(tag_output, mimetype="text/plain")