]> git.openstreetmap.org Git - osqa.git/blob - forum/views/commands.py
Closing OSQA 102, the ip address on the feedback email is empty.
[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, 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
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 NotEnoughLeftException(CommandException):
47     def __init__(self, action, limit):
48         super(NotEnoughLeftException, self).__init__(
49             _("""
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')})
54         )
55
56 class CannotDoubleActionException(CommandException):
57     def __init__(self, action):
58         super(CannotDoubleActionException, self).__init__(
59             _("""
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')})
63         )
64
65
66 @command
67 def vote_post(request, id, vote_type):
68     post = get_object_or_404(Node, id=id).leaf
69     user = request.user
70
71     if not user.is_authenticated():
72         raise AnonymousNotAllowedException(_('vote'))
73
74     if user == post.author:
75         raise CannotDoOnOwnException(_('vote'))
76
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'))
79
80     user_vote_count_today = user.get_vote_count_today()
81
82     if user_vote_count_today >= int(settings.MAX_VOTES_PER_DAY):
83         raise NotEnoughLeftException(_('votes'), str(settings.MAX_VOTES_PER_DAY))
84
85     new_vote_cls = (vote_type == 'up') and VoteUpAction or VoteDownAction
86     score_inc = 0
87
88     try:
89         old_vote = Action.objects.get_for_types((VoteUpAction, VoteDownAction), node=post, user=user)
90
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))}
95             )
96
97         old_vote.cancel(ip=request.META['REMOTE_ADDR'])
98         score_inc += (old_vote.__class__ == VoteDownAction) and 1 or -1
99     except ObjectDoesNotExist:
100         old_vote = None
101
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
105     else:
106         vote_type = "none"
107
108     response = {
109         'commands': {
110             'update_post_score': [id, score_inc],
111             'update_user_post_vote': [id, vote_type]
112         }
113     }
114
115     votes_left = (int(settings.MAX_VOTES_PER_DAY) - user_vote_count_today) + (vote_type == 'none' and -1 or 1)
116
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)}
120
121     return response
122
123 @command
124 def flag_post(request, id):
125     if not request.POST:
126         return render_to_response('node/report.html', {'types': settings.FLAG_TYPES})
127
128     post = get_object_or_404(Node, id=id)
129     user = request.user
130
131     if not user.is_authenticated():
132         raise AnonymousNotAllowedException(_('flag posts'))
133
134     if user == post.author:
135         raise CannotDoOnOwnException(_('flag'))
136
137     if not (user.can_flag_offensive(post)):
138         raise NotEnoughRepPointsException(_('flag posts'))
139
140     user_flag_count_today = user.get_flagged_items_count_today()
141
142     if user_flag_count_today >= int(settings.MAX_FLAGS_PER_DAY):
143         raise NotEnoughLeftException(_('flags'), str(settings.MAX_FLAGS_PER_DAY))
144
145     try:
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()
150
151         if not len(reason):
152             raise CommandException(_("Reason is empty"))
153
154         FlagAction(user=user, node=post, extra=reason, ip=request.META['REMOTE_ADDR']).save()
155
156     return {'message': _("Thank you for your report. A moderator will review your submission shortly.")}
157         
158 @command
159 def like_comment(request, id):
160     comment = get_object_or_404(Comment, id=id)
161     user = request.user
162
163     if not user.is_authenticated():
164         raise AnonymousNotAllowedException(_('like comments'))
165
166     if user == comment.user:
167         raise CannotDoOnOwnException(_('like'))
168
169     if not user.can_like_comment(comment):
170         raise NotEnoughRepPointsException( _('like comments'))    
171
172     try:
173         like = VoteUpCommentAction.objects.get(node=comment, user=user)
174         like.cancel(ip=request.META['REMOTE_ADDR'])
175         likes = False
176     except ObjectDoesNotExist:
177         VoteUpCommentAction(node=comment, user=user, ip=request.META['REMOTE_ADDR']).save()
178         likes = True
179
180     return {
181         'commands': {
182             'update_post_score': [comment.id, likes and 1 or -1],
183             'update_user_post_vote': [comment.id, likes and 'up' or 'none']
184         }
185     }
186
187 @command
188 def delete_comment(request, id):
189     comment = get_object_or_404(Comment, id=id)
190     user = request.user
191
192     if not user.is_authenticated():
193         raise AnonymousNotAllowedException(_('delete comments'))
194
195     if not user.can_delete_comment(comment):
196         raise NotEnoughRepPointsException( _('delete comments'))
197
198     if not comment.deleted:
199         DeleteAction(node=comment, user=user, ip=request.META['REMOTE_ADDR']).save()
200
201     return {
202         'commands': {
203             'remove_comment': [comment.id],
204         }
205     }
206
207 @command
208 def mark_favorite(request, id):
209     question = get_object_or_404(Question, id=id)
210
211     if not request.user.is_authenticated():
212         raise AnonymousNotAllowedException(_('mark a question as favorite'))
213
214     try:
215         favorite = FavoriteAction.objects.get(node=question, user=request.user)
216         favorite.cancel(ip=request.META['REMOTE_ADDR'])
217         added = False
218     except ObjectDoesNotExist:
219         FavoriteAction(node=question, user=request.user, ip=request.META['REMOTE_ADDR']).save()
220         added = True
221
222     return {
223         'commands': {
224             'update_favorite_count': [added and 1 or -1],
225             'update_favorite_mark': [added and 'on' or 'off']
226         }
227     }
228
229 @decoratable
230 @command
231 def comment(request, id):
232     post = get_object_or_404(Node, id=id)
233     user = request.user
234
235     if not user.is_authenticated():
236         raise AnonymousNotAllowedException(_('comment'))
237
238     if not request.method == 'POST':
239         raise CommandException(_("Invalid request"))
240
241     comment_text = request.POST.get('comment', '').strip()
242
243     if not len(comment_text):
244         raise CommandException(_("Comment is empty"))
245
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)
248
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)
251
252     if 'id' in request.POST:
253         comment = get_object_or_404(Comment, id=request.POST['id'])
254
255         if not user.can_edit_comment(comment):
256             raise NotEnoughRepPointsException( _('edit comments'))
257
258         comment = ReviseAction(user=user, node=comment, ip=request.META['REMOTE_ADDR']).save(data=dict(text=comment_text)).node
259     else:
260         if not user.can_comment(post):
261             raise NotEnoughRepPointsException( _('comment'))
262
263         comment = CommentAction(user=user, ip=request.META['REMOTE_ADDR']).save(data=dict(text=comment_text, parent=post)).node
264
265     if comment.active_revision.revision == 1:
266         return {
267             'commands': {
268                 'insert_comment': [
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})
271                 ]
272             }
273         }
274     else:
275         return {
276             'commands': {
277                 'update_comment': [comment.id, comment.comment]
278             }
279         }
280
281 @command
282 def node_markdown(request, id):
283     user = request.user
284
285     if not user.is_authenticated():
286         raise AnonymousNotAllowedException(_('accept answers'))
287
288     node = get_object_or_404(Node, id=id)
289     return HttpResponse(node.body, mimetype="text/plain")
290
291
292 @command
293 def accept_answer(request, id):
294     user = request.user
295
296     if not user.is_authenticated():
297         raise AnonymousNotAllowedException(_('accept answers'))
298
299     answer = get_object_or_404(Answer, id=id)
300     question = answer.question
301
302     if not user.can_accept_answer(answer):
303         raise CommandException(_("Sorry but only the question author can accept an answer"))
304
305     commands = {}
306
307     if answer.accepted:
308         answer.accepted.cancel(user, ip=request.META['REMOTE_ADDR'])
309         commands['unmark_accepted'] = [answer.id]
310     else:
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]
315
316         AcceptAnswerAction(node=answer, user=user, ip=request.META['REMOTE_ADDR']).save()
317         commands['mark_accepted'] = [answer.id]
318
319     return {'commands': commands}
320
321 @command    
322 def delete_post(request, id):
323     post = get_object_or_404(Node, id=id)
324     user = request.user
325
326     if not user.is_authenticated():
327         raise AnonymousNotAllowedException(_('delete posts'))
328
329     if not (user.can_delete_post(post)):
330         raise NotEnoughRepPointsException(_('delete posts'))
331
332     ret = {'commands': {}}
333
334     if post.deleted:
335         post.deleted.cancel(user, ip=request.META['REMOTE_ADDR'])
336         ret['commands']['unmark_deleted'] = [post.node_type, id]
337     else:
338         DeleteAction(node=post, user=user, ip=request.META['REMOTE_ADDR']).save()
339
340         ret['commands']['mark_deleted'] = [post.node_type, id]
341
342     return ret
343
344 @command
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})
348
349     question = get_object_or_404(Question, id=id)
350     user = request.user
351
352     if not user.is_authenticated():
353         raise AnonymousNotAllowedException(_('close questions'))
354
355     if question.extra_action:
356         if not user.can_reopen_question(question):
357             raise NotEnoughRepPointsException(_('reopen questions'))
358
359         question.extra_action.cancel(user, ip=request.META['REMOTE_ADDR'])
360     else:
361         if not request.user.can_close_question(question):
362             raise NotEnoughRepPointsException(_('close questions'))
363
364         reason = request.POST.get('prompt', '').strip()
365
366         if not len(reason):
367             raise CommandException(_("Reason is empty"))
368
369         CloseAction(node=question, user=user, extra=reason, ip=request.META['REMOTE_ADDR']).save()
370
371     return {
372         'commands': {
373             'refresh_page': []
374         }
375     }
376
377 @command
378 def subscribe(request, id):
379     question = get_object_or_404(Question, id=id)
380
381     try:
382         subscription = QuestionSubscription.objects.get(question=question, user=request.user)
383         subscription.delete()
384         subscribed = False
385     except:
386         subscription = QuestionSubscription(question=question, user=request.user, auto_subscription=False)
387         subscription.save()
388         subscribed = True
389
390     return {
391         'commands': {
392                 'set_subscription_button': [subscribed and _('unsubscribe me') or _('subscribe me')],
393                 'set_subscription_status': ['']
394             }
395     }
396
397 #internally grouped views - used by the tagging system
398 @ajax_login_required
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)
404         ts.delete()
405     else:
406         reason = kwargs['reason']
407         if len(ts) == 0:
408             try:
409                 t = Tag.objects.get(name=tag)
410                 mt = MarkedTag(user=request.user, reason=reason, tag=t)
411                 mt.save()
412             except:
413                 pass
414         else:
415             ts.update(reason=reason)
416     return HttpResponse(simplejson.dumps(''), mimetype="application/json")
417
418 def matching_tags(request):
419     if len(request.GET['q']) == 0:
420        raise CommandException(_("Invalid request"))
421
422     possible_tags = Tag.objects.filter(name__istartswith = request.GET['q'])
423     tag_output = ''
424     for tag in possible_tags:
425         tag_output += (tag.name + "|" + tag.name + "." + tag.used_count.__str__() + "\n")
426         
427     return HttpResponse(tag_output, mimetype="text/plain")
428
429
430
431
432
433
434