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