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 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
 
  17 class NotEnoughRepPointsException(Exception):
 
  18     def __init__(self, action):
 
  19         super(NotEnoughRepPointsException, self).__init__(
 
  21             Sorry, but you don't have enough reputation points to %(action)s.<br />
 
  22             Please check the <a href'%(faq_url)s'>faq</a>
 
  23             """ % {'action': action, 'faq_url': reverse('faq')})
 
  26 class CannotDoOnOwnException(Exception):
 
  27     def __init__(self, action):
 
  28         super(CannotDoOnOwnException, self).__init__(
 
  30             Sorry but you cannot %(action)s your own post.<br />
 
  31             Please check the <a href'%(faq_url)s'>faq</a>
 
  32             """ % {'action': action, 'faq_url': reverse('faq')})
 
  35 class AnonymousNotAllowedException(Exception):
 
  36     def __init__(self, action):
 
  37         super(AnonymousNotAllowedException, self).__init__(
 
  39             Sorry but anonymous users cannot %(action)s.<br />
 
  40             Please login or create an account <a href'%(signin_url)s'>here</a>.
 
  41             """ % {'action': action, 'signin_url': reverse('auth_signin')})
 
  44 class NotEnoughLeftException(Exception):
 
  45     def __init__(self, action, limit):
 
  46         super(NotEnoughRepPointsException, self).__init__(
 
  48             Sorry, but you don't have enough %(action)s left for today..<br />
 
  49             The limit is %(limit)s per day..<br />
 
  50             Please check the <a href'%(faq_url)s'>faq</a>
 
  51             """ % {'action': action, 'limit': limit, 'faq_url': reverse('faq')})
 
  54 class CannotDoubleActionException(Exception):
 
  55     def __init__(self, action):
 
  56         super(CannotDoubleActionException, self).__init__(
 
  58             Sorry, but you cannot %(action)s twice the same post.<br />
 
  59             Please check the <a href'%(faq_url)s'>faq</a>
 
  60             """ % {'action': action, 'faq_url': reverse('faq')})
 
  65 def vote_post(request, id, vote_type):
 
  66     post = get_object_or_404(Node, id=id).leaf
 
  67     vote_score = vote_type == 'up' and 1 or -1
 
  70     if not user.is_authenticated():
 
  71         raise AnonymousNotAllowedException(_('vote'))
 
  73     if user == post.author:
 
  74         raise CannotDoOnOwnException(_('vote'))
 
  76     if not (vote_type == 'up' and user.can_vote_up() or user.can_vote_down()):
 
  77         raise NotEnoughRepPointsException(vote_type == 'up' and _('upvote') or _('downvote'))
 
  79     user_vote_count_today = user.get_vote_count_today()
 
  81     if user_vote_count_today >= int(settings.MAX_VOTES_PER_DAY):
 
  82         raise NotEnoughLeftException(_('votes'), str(settings.MAX_VOTES_PER_DAY))
 
  85         vote = post.votes.get(canceled=False, user=user)
 
  87         if vote.voted_at < datetime.datetime.now() - datetime.timedelta(days=int(settings.DENY_UNVOTE_DAYS)):
 
  89                     _("Sorry but you cannot cancel a vote after %(ndays)d %(tdays)s from the original vote") %
 
  90                     {'ndays': int(settings.DENY_UNVOTE_DAYS), 'tdays': ungettext('day', 'days', int(settings.DENY_UNVOTE_DAYS))}
 
  95     except ObjectDoesNotExist:
 
  97         vote = Vote(user=user, node=post, vote=vote_score)
 
 102             'update_post_score': [id, vote.vote * (vote_type == 'none' and -1 or 1)],
 
 103             'update_user_post_vote': [id, vote_type]
 
 107     votes_left = int(settings.MAX_VOTES_PER_DAY) - user_vote_count_today + (vote_type == 'none' and -1 or 1)
 
 109     if int(settings.START_WARN_VOTES_LEFT) >= votes_left:
 
 110         response['message'] = _("You have %(nvotes)s %(tvotes)s left today.") % \
 
 111                     {'nvotes': votes_left, 'tvotes': ungettext('vote', 'votes', votes_left)}
 
 116 def flag_post(request, id):
 
 117     post = get_object_or_404(Node, id=id)
 
 120     if not user.is_authenticated():
 
 121         raise AnonymousNotAllowedException(_('flag posts'))
 
 123     if user == post.author:
 
 124         raise CannotDoOnOwnException(_('flag'))
 
 126     if not (user.can_flag_offensive(post)):
 
 127         raise NotEnoughRepPointsException(_('flag posts'))
 
 129     user_flag_count_today = user.get_flagged_items_count_today()
 
 131     if user_flag_count_today >= int(settings.MAX_FLAGS_PER_DAY):
 
 132         raise NotEnoughLeftException(_('flags'), str(settings.MAX_FLAGS_PER_DAY))
 
 135         post.flaggeditems.get(user=user)
 
 136         raise CannotDoubleActionException(_('flag'))
 
 137     except ObjectDoesNotExist:
 
 138         flag = FlaggedItem(user=user, content_object=post)
 
 144 def like_comment(request, id):
 
 145     comment = get_object_or_404(Comment, id=id)
 
 148     if not user.is_authenticated():
 
 149         raise AnonymousNotAllowedException(_('like comments'))
 
 151     if user == comment.user:
 
 152         raise CannotDoOnOwnException(_('like'))
 
 154     if not user.can_like_comment(comment):
 
 155         raise NotEnoughRepPointsException( _('like comments'))    
 
 158         like = LikedComment.active.get(comment=comment, user=user)
 
 161     except ObjectDoesNotExist:
 
 162         like = LikedComment(comment=comment, user=user)
 
 168             'update_comment_score': [comment.id, likes and 1 or -1],
 
 169             'update_likes_comment_mark': [comment.id, likes and 'on' or 'off']
 
 174 def delete_comment(request, id):
 
 175     comment = get_object_or_404(Comment, id=id)
 
 178     if not user.is_authenticated():
 
 179         raise AnonymousNotAllowedException(_('delete comments'))
 
 181     if not user.can_delete_comment(comment):
 
 182         raise NotEnoughRepPointsException( _('delete comments'))
 
 184     comment.mark_deleted(user)
 
 188             'remove_comment': [comment.id],
 
 193 def mark_favorite(request, id):
 
 194     question = get_object_or_404(Question, id=id)
 
 196     if not request.user.is_authenticated():
 
 197         raise AnonymousNotAllowedException(_('mark a question as favorite'))
 
 200         favorite = FavoriteQuestion.objects.get(question=question, user=request.user)
 
 203     except ObjectDoesNotExist:
 
 204         favorite = FavoriteQuestion(question=question, user=request.user)
 
 210             'update_favorite_count': [added and 1 or -1],
 
 211             'update_favorite_mark': [added and 'on' or 'off']
 
 216 def comment(request, id):
 
 217     post = get_object_or_404(Node, id=id)
 
 220     if not user.is_authenticated():
 
 221         raise AnonymousNotAllowedException(_('comment'))
 
 223     if not request.method == 'POST':
 
 224         raise Exception(_("Invalid request"))
 
 226     if 'id' in request.POST:
 
 227         comment = get_object_or_404(Comment, id=request.POST['id'])
 
 229         if not user.can_edit_comment(comment):
 
 230             raise NotEnoughRepPointsException( _('edit comments'))
 
 232         if not user.can_comment(post):
 
 233             raise NotEnoughRepPointsException( _('comment'))
 
 235         comment = Comment(parent=post)
 
 237     comment_text = request.POST.get('comment', '').strip()
 
 239     if not len(comment_text):
 
 240         raise Exception(_("Comment is empty"))
 
 242     comment.create_revision(user, body=comment_text)
 
 244     if comment.active_revision.revision == 1:
 
 248                     id, comment.id, comment_text, user.username, user.get_profile_url(), reverse('delete_comment', kwargs={'id': comment.id})
 
 255                 'update_comment': [comment.id, comment.comment]
 
 261 def accept_answer(request, id):
 
 264     if not user.is_authenticated():
 
 265         raise AnonymousNotAllowedException(_('accept answers'))
 
 267     answer = get_object_or_404(Answer, id=id)
 
 268     question = answer.question
 
 270     if not user.can_accept_answer(answer):
 
 271         raise Exception(_("Sorry but only the question author can accept an answer"))
 
 276         answer.unmark_accepted(user)
 
 277         commands['unmark_accepted'] = [answer.id]
 
 279         if question.accepted_answer is not None:
 
 280             accepted = question.accepted_answer
 
 281             accepted.unmark_accepted(user)
 
 282             commands['unmark_accepted'] = [accepted.id]
 
 284         answer.mark_accepted(user)
 
 285         commands['mark_accepted'] = [answer.id]
 
 287     return {'commands': commands}
 
 290 def delete_post(request, id):
 
 291     post = get_object_or_404(Node, id=id)
 
 294     if not user.is_authenticated():
 
 295         raise AnonymousNotAllowedException(_('delete posts'))
 
 297     if not (user.can_delete_post(post)):
 
 298         raise NotEnoughRepPointsException(_('delete posts'))
 
 300     post.mark_deleted(user)
 
 304                 'mark_deleted': [post.node_type, id]
 
 309 def subscribe(request, id):
 
 310     question = get_object_or_404(Question, id=id)
 
 313         subscription = QuestionSubscription.objects.get(question=question, user=request.user)
 
 314         subscription.delete()
 
 317         subscription = QuestionSubscription(question=question, user=request.user, auto_subscription=False)
 
 323                 'set_subscription_button': [subscribed and _('unsubscribe me') or _('subscribe me')],
 
 324                 'set_subscription_status': ['']
 
 328 #internally grouped views - used by the tagging system
 
 330 def mark_tag(request, tag=None, **kwargs):#tagging system
 
 331     action = kwargs['action']
 
 332     ts = MarkedTag.objects.filter(user=request.user, tag__name=tag)
 
 333     if action == 'remove':
 
 334         logging.debug('deleting tag %s' % tag)
 
 337         reason = kwargs['reason']
 
 340                 t = Tag.objects.get(name=tag)
 
 341                 mt = MarkedTag(user=request.user, reason=reason, tag=t)
 
 346             ts.update(reason=reason)
 
 347     return HttpResponse(simplejson.dumps(''), mimetype="application/json")
 
 350 def ajax_toggle_ignored_questions(request):#ajax tagging and tag-filtering system
 
 351     if request.user.hide_ignored_questions:
 
 352         new_hide_setting = False
 
 354         new_hide_setting = True
 
 355     request.user.hide_ignored_questions = new_hide_setting
 
 359 def ajax_command(request):#refactor? view processing ajax commands - note "vote" and view others do it too
 
 360     if 'command' not in request.POST:
 
 361         return HttpResponseForbidden(mimetype="application/json")
 
 362     if request.POST['command'] == 'toggle-ignored-questions':
 
 363         return ajax_toggle_ignored_questions(request)
 
 366 def close(request, id):#close question
 
 367     """view to initiate and process 
 
 370     question = get_object_or_404(Question, id=id)
 
 371     if not request.user.can_close_question(question):
 
 372         return HttpResponseForbidden()
 
 373     if request.method == 'POST':
 
 374         form = CloseForm(request.POST)
 
 376             reason = form.cleaned_data['reason']
 
 377             question.closed = True
 
 378             question.closed_by = request.user
 
 379             question.closed_at = datetime.datetime.now()
 
 380             question.close_reason = reason
 
 382         return HttpResponseRedirect(question.get_absolute_url())
 
 385         return render_to_response('close.html', {
 
 387             'question' : question,
 
 388             }, context_instance=RequestContext(request))
 
 391 def reopen(request, id):#re-open question
 
 392     """view to initiate and process 
 
 395     question = get_object_or_404(Question, id=id)
 
 397     if not request.user.can_reopen_question(question):
 
 398         return HttpResponseForbidden()
 
 399     if request.method == 'POST' :
 
 400         Question.objects.filter(id=question.id).update(closed=False,
 
 401             closed_by=None, closed_at=None, close_reason=None)
 
 402         return HttpResponseRedirect(question.get_absolute_url())
 
 404         return render_to_response('reopen.html', {
 
 405             'question' : question,
 
 406             }, context_instance=RequestContext(request))
 
 408 #osqa-user communication system
 
 409 def read_message(request):#marks message a read
 
 410     if request.method == "POST":
 
 411         if request.POST['formdata'] == 'required':
 
 412             request.session['message_silent'] = 1
 
 413             if request.user.is_authenticated():
 
 414                 request.user.delete_messages()
 
 415     return HttpResponse('')