]> git.openstreetmap.org Git - osqa.git/blob - forum/views/commands.py
Fixed http://jira.osqa.net/browse/OSQA-217. Previous commit claiming to fix this...
[osqa.git] / forum / views / commands.py
1 import datetime
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.forms import CloseForm
11 from forum.actions import *
12 from django.core.urlresolvers import reverse
13 from django.contrib.auth.decorators import login_required
14 from forum.utils.decorators import ajax_method, ajax_login_required
15 from decorators import command, CommandException
16 from forum import settings
17 import logging
18
19 class NotEnoughRepPointsException(CommandException):
20     def __init__(self, action):
21         super(NotEnoughRepPointsException, self).__init__(
22             _("""
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')})
26         )
27
28 class CannotDoOnOwnException(CommandException):
29     def __init__(self, action):
30         super(CannotDoOnOwnException, self).__init__(
31             _("""
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')})
35         )
36
37 class AnonymousNotAllowedException(CommandException):
38     def __init__(self, action):
39         super(AnonymousNotAllowedException, self).__init__(
40             _("""
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')})
44         )
45
46 class SpamNotAllowedException(CommandException):
47     def __init__(self, action = "comment"):
48         super(SpamNotAllowedException, self).__init__(
49             _("""Your %s has been marked as spam.""" % action)
50         )
51
52 class NotEnoughLeftException(CommandException):
53     def __init__(self, action, limit):
54         super(NotEnoughLeftException, self).__init__(
55             _("""
56             Sorry, but you don't have enough %(action)s left for today..<br />
57             The limit is %(limit)s per day..<br />
58             Please check the <a href'%(faq_url)s'>faq</a>
59             """ % {'action': action, 'limit': limit, 'faq_url': reverse('faq')})
60         )
61
62 class CannotDoubleActionException(CommandException):
63     def __init__(self, action):
64         super(CannotDoubleActionException, self).__init__(
65             _("""
66             Sorry, but you cannot %(action)s twice the same post.<br />
67             Please check the <a href'%(faq_url)s'>faq</a>
68             """ % {'action': action, 'faq_url': reverse('faq')})
69         )
70
71
72 @command
73 def vote_post(request, id, vote_type):
74     post = get_object_or_404(Node, id=id).leaf
75     user = request.user
76
77     if not user.is_authenticated():
78         raise AnonymousNotAllowedException(_('vote'))
79
80     if user == post.author:
81         raise CannotDoOnOwnException(_('vote'))
82
83     if not (vote_type == 'up' and user.can_vote_up() or user.can_vote_down()):
84         raise NotEnoughRepPointsException(vote_type == 'up' and _('upvote') or _('downvote'))
85
86     user_vote_count_today = user.get_vote_count_today()
87
88     if user_vote_count_today >= int(settings.MAX_VOTES_PER_DAY):
89         raise NotEnoughLeftException(_('votes'), str(settings.MAX_VOTES_PER_DAY))
90
91     new_vote_cls = (vote_type == 'up') and VoteUpAction or VoteDownAction
92     score_inc = 0
93
94     try:
95         old_vote = Action.objects.get_for_types((VoteUpAction, VoteDownAction), node=post, user=user)
96
97         if old_vote.action_date < datetime.datetime.now() - datetime.timedelta(days=int(settings.DENY_UNVOTE_DAYS)):
98             raise CommandException(
99                     _("Sorry but you cannot cancel a vote after %(ndays)d %(tdays)s from the original vote") %
100                     {'ndays': int(settings.DENY_UNVOTE_DAYS), 'tdays': ungettext('day', 'days', int(settings.DENY_UNVOTE_DAYS))}
101             )
102
103         old_vote.cancel(ip=request.META['REMOTE_ADDR'])
104         score_inc += (old_vote.__class__ == VoteDownAction) and 1 or -1
105     except ObjectDoesNotExist:
106         old_vote = None
107
108     if old_vote.__class__ != new_vote_cls:
109         new_vote_cls(user=user, node=post, ip=request.META['REMOTE_ADDR']).save()
110         score_inc += (new_vote_cls == VoteUpAction) and 1 or -1
111     else:
112         vote_type = "none"
113
114     response = {
115         'commands': {
116             'update_post_score': [id, score_inc],
117             'update_user_post_vote': [id, vote_type]
118         }
119     }
120
121     votes_left = (int(settings.MAX_VOTES_PER_DAY) - user_vote_count_today) + (vote_type == 'none' and -1 or 1)
122
123     if int(settings.START_WARN_VOTES_LEFT) >= votes_left:
124         response['message'] = _("You have %(nvotes)s %(tvotes)s left today.") % \
125                     {'nvotes': votes_left, 'tvotes': ungettext('vote', 'votes', votes_left)}
126
127     return response
128
129 @command
130 def flag_post(request, id):
131     if not request.POST:
132         return render_to_response('node/report.html', {'types': settings.FLAG_TYPES})
133
134     post = get_object_or_404(Node, id=id)
135     user = request.user
136
137     if not user.is_authenticated():
138         raise AnonymousNotAllowedException(_('flag posts'))
139
140     if user == post.author:
141         raise CannotDoOnOwnException(_('flag'))
142
143     if not (user.can_flag_offensive(post)):
144         raise NotEnoughRepPointsException(_('flag posts'))
145
146     user_flag_count_today = user.get_flagged_items_count_today()
147
148     if user_flag_count_today >= int(settings.MAX_FLAGS_PER_DAY):
149         raise NotEnoughLeftException(_('flags'), str(settings.MAX_FLAGS_PER_DAY))
150
151     try:
152         current = FlagAction.objects.get(user=user, node=post)
153         raise CommandException(_("You already flagged this post with the following reason: %(reason)s") % {'reason': current.extra})
154     except ObjectDoesNotExist:
155         reason = request.POST.get('prompt', '').strip()
156
157         if not len(reason):
158             raise CommandException(_("Reason is empty"))
159
160         FlagAction(user=user, node=post, extra=reason, ip=request.META['REMOTE_ADDR']).save()
161
162     return {'message': _("Thank you for your report. A moderator will review your submission shortly.")}
163         
164 @command
165 def like_comment(request, id):
166     comment = get_object_or_404(Comment, id=id)
167     user = request.user
168
169     if not user.is_authenticated():
170         raise AnonymousNotAllowedException(_('like comments'))
171
172     if user == comment.user:
173         raise CannotDoOnOwnException(_('like'))
174
175     if not user.can_like_comment(comment):
176         raise NotEnoughRepPointsException( _('like comments'))    
177
178     try:
179         like = VoteUpCommentAction.objects.get(node=comment, user=user)
180         like.cancel(ip=request.META['REMOTE_ADDR'])
181         likes = False
182     except ObjectDoesNotExist:
183         VoteUpCommentAction(node=comment, user=user, ip=request.META['REMOTE_ADDR']).save()
184         likes = True
185
186     return {
187         'commands': {
188             'update_post_score': [comment.id, likes and 1 or -1],
189             'update_user_post_vote': [comment.id, likes and 'up' or 'none']
190         }
191     }
192
193 @command
194 def delete_comment(request, id):
195     comment = get_object_or_404(Comment, id=id)
196     user = request.user
197
198     if not user.is_authenticated():
199         raise AnonymousNotAllowedException(_('delete comments'))
200
201     if not user.can_delete_comment(comment):
202         raise NotEnoughRepPointsException( _('delete comments'))
203
204     if not comment.deleted:
205         DeleteAction(node=comment, user=user, ip=request.META['REMOTE_ADDR']).save()
206
207     return {
208         'commands': {
209             'remove_comment': [comment.id],
210         }
211     }
212
213 @command
214 def mark_favorite(request, id):
215     question = get_object_or_404(Question, id=id)
216
217     if not request.user.is_authenticated():
218         raise AnonymousNotAllowedException(_('mark a question as favorite'))
219
220     try:
221         favorite = FavoriteAction.objects.get(node=question, user=request.user)
222         favorite.cancel(ip=request.META['REMOTE_ADDR'])
223         added = False
224     except ObjectDoesNotExist:
225         FavoriteAction(node=question, user=request.user, ip=request.META['REMOTE_ADDR']).save()
226         added = True
227
228     return {
229         'commands': {
230             'update_favorite_count': [added and 1 or -1],
231             'update_favorite_mark': [added and 'on' or 'off']
232         }
233     }
234
235 @command
236 def comment(request, id):
237     post = get_object_or_404(Node, id=id)
238     user = request.user
239
240     if not user.is_authenticated():
241         raise AnonymousNotAllowedException(_('comment'))
242
243     if not request.method == 'POST':
244         raise CommandException(_("Invalid request"))
245
246     comment_text = request.POST.get('comment', '').strip()
247
248     if not len(comment_text):
249         raise CommandException(_("Comment is empty"))
250
251     if len(comment_text) < settings.FORM_MIN_COMMENT_BODY:
252         raise CommandException(_("At least %d characters required on comment body.") % settings.FORM_MIN_COMMENT_BODY)
253
254     if len(comment_text) > settings.FORM_MAX_COMMENT_BODY:
255         raise CommandException(_("No more than %d characters on comment body.") % settings.FORM_MAX_COMMENT_BODY)
256
257     data = {
258         "user_ip":request.META["REMOTE_ADDR"],
259         "user_agent":request.environ['HTTP_USER_AGENT'],
260         "comment_author":request.user.username,
261         "comment_author_email":request.user.email,
262         "comment_author_url":request.user.website,
263         "comment":comment_text
264     }
265     if Node.isSpam(comment_text, data):
266         raise SpamNotAllowedException()
267
268     if 'id' in request.POST:
269         comment = get_object_or_404(Comment, id=request.POST['id'])
270
271         if not user.can_edit_comment(comment):
272             raise NotEnoughRepPointsException( _('edit comments'))
273
274         comment = ReviseAction(user=user, node=comment, ip=request.META['REMOTE_ADDR']).save(data=dict(text=comment_text)).node
275     else:
276         if not user.can_comment(post):
277             raise NotEnoughRepPointsException( _('comment'))
278
279         comment = CommentAction(user=user, ip=request.META['REMOTE_ADDR']).save(data=dict(text=comment_text, parent=post)).node
280
281     if comment.active_revision.revision == 1:
282         return {
283             'commands': {
284                 'insert_comment': [
285                     id, comment.id, comment.comment, user.username, user.get_profile_url(),
286                         reverse('delete_comment', kwargs={'id': comment.id}), reverse('node_markdown', kwargs={'id': comment.id})
287                 ]
288             }
289         }
290     else:
291         return {
292             'commands': {
293                 'update_comment': [comment.id, comment.comment]
294             }
295         }
296
297 @command
298 def node_markdown(request, id):
299     user = request.user
300
301     if not user.is_authenticated():
302         raise AnonymousNotAllowedException(_('accept answers'))
303
304     node = get_object_or_404(Node, id=id)
305     return HttpResponse(node.body, mimetype="text/plain")
306
307
308 @command
309 def accept_answer(request, id):
310     user = request.user
311
312     if not user.is_authenticated():
313         raise AnonymousNotAllowedException(_('accept answers'))
314
315     answer = get_object_or_404(Answer, id=id)
316     question = answer.question
317
318     if not user.can_accept_answer(answer):
319         raise CommandException(_("Sorry but only the question author can accept an answer"))
320
321     commands = {}
322
323     if answer.accepted:
324         answer.accepted.cancel(user, ip=request.META['REMOTE_ADDR'])
325         commands['unmark_accepted'] = [answer.id]
326     else:
327         if question.answer_accepted:
328             accepted = question.accepted_answer
329             accepted.accepted.cancel(user, ip=request.META['REMOTE_ADDR'])
330             commands['unmark_accepted'] = [accepted.id]
331
332         AcceptAnswerAction(node=answer, user=user, ip=request.META['REMOTE_ADDR']).save()
333         commands['mark_accepted'] = [answer.id]
334
335     return {'commands': commands}
336
337 @command    
338 def delete_post(request, id):
339     post = get_object_or_404(Node, id=id)
340     user = request.user
341
342     if not user.is_authenticated():
343         raise AnonymousNotAllowedException(_('delete posts'))
344
345     if not (user.can_delete_post(post)):
346         raise NotEnoughRepPointsException(_('delete posts'))
347
348     ret = {'commands': {}}
349
350     if post.deleted:
351         post.deleted.cancel(user, ip=request.META['REMOTE_ADDR'])
352         ret['commands']['unmark_deleted'] = [post.node_type, id]
353     else:
354         DeleteAction(node=post, user=user, ip=request.META['REMOTE_ADDR']).save()
355
356         ret['commands']['mark_deleted'] = [post.node_type, id]
357
358     return ret
359
360 @command
361 def close(request, id, close):
362     if close and not request.POST:
363         return render_to_response('node/report.html', {'types': settings.CLOSE_TYPES})
364
365     question = get_object_or_404(Question, id=id)
366     user = request.user
367
368     if not user.is_authenticated():
369         raise AnonymousNotAllowedException(_('close questions'))
370
371     if question.extra_action:
372         if not user.can_reopen_question(question):
373             raise NotEnoughRepPointsException(_('reopen questions'))
374
375         question.extra_action.cancel(user, ip=request.META['REMOTE_ADDR'])
376     else:
377         if not request.user.can_close_question(question):
378             raise NotEnoughRepPointsException(_('close questions'))
379
380         reason = request.POST.get('prompt', '').strip()
381
382         if not len(reason):
383             raise CommandException(_("Reason is empty"))
384
385         CloseAction(node=question, user=user, extra=reason, ip=request.META['REMOTE_ADDR']).save()
386
387     return {
388         'commands': {
389             'refresh_page': []
390         }
391     }
392
393 @command
394 def subscribe(request, id):
395     question = get_object_or_404(Question, id=id)
396
397     try:
398         subscription = QuestionSubscription.objects.get(question=question, user=request.user)
399         subscription.delete()
400         subscribed = False
401     except:
402         subscription = QuestionSubscription(question=question, user=request.user, auto_subscription=False)
403         subscription.save()
404         subscribed = True
405
406     return {
407         'commands': {
408                 'set_subscription_button': [subscribed and _('unsubscribe me') or _('subscribe me')],
409                 'set_subscription_status': ['']
410             }
411     }
412
413 #internally grouped views - used by the tagging system
414 @ajax_login_required
415 def mark_tag(request, tag=None, **kwargs):#tagging system
416     action = kwargs['action']
417     ts = MarkedTag.objects.filter(user=request.user, tag__name=tag)
418     if action == 'remove':
419         logging.debug('deleting tag %s' % tag)
420         ts.delete()
421     else:
422         reason = kwargs['reason']
423         if len(ts) == 0:
424             try:
425                 t = Tag.objects.get(name=tag)
426                 mt = MarkedTag(user=request.user, reason=reason, tag=t)
427                 mt.save()
428             except:
429                 pass
430         else:
431             ts.update(reason=reason)
432     return HttpResponse(simplejson.dumps(''), mimetype="application/json")
433
434 def matching_tags(request):
435     if len(request.GET['q']) == 0:
436        raise CommandException(_("Invalid request"))
437
438     possible_tags = Tag.objects.filter(name__istartswith = request.GET['q'])
439     tag_output = ''
440     for tag in possible_tags:
441         tag_output += (tag.name + "|" + tag.name + "." + tag.used_count.__str__() + "\n")
442         
443     return HttpResponse(tag_output, mimetype="text/plain")
444
445
446
447
448
449
450