2 from django.conf import settings
3 from django.utils import simplejson
4 from django.http import HttpResponse, HttpResponseRedirect
5 from django.shortcuts import get_object_or_404
6 from django.utils.translation import ugettext as _
7 from django.template import RequestContext
8 from forum.models import *
9 from forum.forms import CloseForm
10 from forum import auth
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
16 def vote(request, id):#refactor - pretty incomprehensible view used by various ajax calls
17 #issues: this subroutine is too long, contains many magic numbers and other issues
18 #it's called "vote" but many actions processed here have nothing to do with voting
27 offensiveQuestion : 7,
31 questionSubscribeUpdates:11
32 questionUnSubscribeUpdates:12
35 response_data['allowed'] = -1, Accept his own answer 0, no allowed - Anonymous 1, Allowed - by default
36 response_data['success'] = 0, failed 1, Success - by default
37 response_data['status'] = 0, By default 1, Answer has been accepted already(Cancel)
40 allowed = -3, Don't have enough votes left
41 -2, Don't have enough reputation score
43 0, no allowed - Anonymous
44 1, Allowed - by default
45 status = 0, By default
47 2, Vote is too old to be canceled
50 allowed = -3, Don't have enough flags left
51 -2, Don't have enough reputation score to do this
54 status = 0, by default
65 def __can_vote(vote_score, user):#refactor - belongs to auth.py
66 if vote_score == 1:#refactor magic number
67 return auth.can_vote_up(request.user)
69 return auth.can_vote_down(request.user)
72 if not request.user.is_authenticated():
73 response_data['allowed'] = 0
74 response_data['success'] = 0
76 elif request.is_ajax() and request.method == 'POST':
77 question = get_object_or_404(Question, id=id)
78 vote_type = request.POST.get('type')
82 answer_id = request.POST.get('postId')
83 answer = get_object_or_404(Answer, id=answer_id)
84 # make sure question author is current user
85 if question.author == request.user:
86 # answer user who is also question author is not allow to accept answer
87 if answer.author == question.author:
88 response_data['success'] = 0
89 response_data['allowed'] = -1
90 # check if answer has been accepted already
92 auth.onAnswerAcceptCanceled(answer, request.user)
93 response_data['status'] = 1
95 # set other answers in this question not accepted first
96 for answer_of_question in Answer.objects.get_answers_from_question(question, request.user):
97 if answer_of_question != answer and answer_of_question.accepted:
98 auth.onAnswerAcceptCanceled(answer_of_question, request.user)
100 #make sure retrieve data again after above author changes, they may have related data
101 answer = get_object_or_404(Answer, id=answer_id)
102 auth.onAnswerAccept(answer, request.user)
104 response_data['allowed'] = 0
105 response_data['success'] = 0
107 elif vote_type == '4':
108 has_favorited = False
109 fav_questions = FavoriteQuestion.objects.filter(question=question)
110 # if the same question has been favorited before, then delete it
111 if fav_questions is not None:
112 for item in fav_questions:
113 if item.user == request.user:
115 response_data['status'] = 1
116 response_data['count'] = len(fav_questions) - 1
117 if response_data['count'] < 0:
118 response_data['count'] = 0
120 # if above deletion has not been executed, just insert a new favorite question
121 if not has_favorited:
122 new_item = FavoriteQuestion(question=question, user=request.user)
124 response_data['count'] = FavoriteQuestion.objects.filter(question=question).count()
125 Question.objects.update_favorite_count(question)
127 elif vote_type in ['1', '2', '5', '6']:
131 if vote_type in ['5', '6']:
132 answer_id = request.POST.get('postId')
133 answer = get_object_or_404(Answer, id=answer_id)
136 if vote_type in ['2', '6']:
139 if post.author == request.user:
140 response_data['allowed'] = -1
141 elif not __can_vote(vote_score, request.user):
142 response_data['allowed'] = -2
143 elif post.votes.filter(user=request.user).count() > 0:
144 vote = post.votes.filter(user=request.user)[0]
145 # unvote should be less than certain time
146 if (datetime.datetime.now().day - vote.voted_at.day) >= auth.VOTE_RULES['scope_deny_unvote_days']:
147 response_data['status'] = 2
152 auth.onUpVotedCanceled(vote, post, request.user)
156 auth.onDownVotedCanceled(vote, post, request.user)
158 response_data['status'] = 1
159 response_data['count'] = post.score
160 elif Vote.objects.get_votes_count_today_from_user(request.user) >= auth.VOTE_RULES['scope_votes_per_user_per_day']:
161 response_data['allowed'] = -3
163 vote = Vote(user=request.user, content_object=post, vote=vote_score, voted_at=datetime.datetime.now())
166 auth.onUpVoted(vote, post, request.user)
169 auth.onDownVoted(vote, post, request.user)
171 votes_left = auth.VOTE_RULES['scope_votes_per_user_per_day'] - Vote.objects.get_votes_count_today_from_user(request.user)
172 if votes_left <= auth.VOTE_RULES['scope_warn_votes_left']:
173 response_data['message'] = u'%s votes left' % votes_left
174 response_data['count'] = post.score
175 elif vote_type in ['7', '8']:
179 post_id = request.POST.get('postId')
180 post = get_object_or_404(Answer, id=post_id)
182 if FlaggedItem.objects.get_flagged_items_count_today(request.user) >= auth.VOTE_RULES['scope_flags_per_user_per_day']:
183 response_data['allowed'] = -3
184 elif not auth.can_flag_offensive(request.user):
185 response_data['allowed'] = -2
186 elif post.flagged_items.filter(user=request.user).count() > 0:
187 response_data['status'] = 1
189 item = FlaggedItem(user=request.user, content_object=post, flagged_at=datetime.datetime.now())
190 auth.onFlaggedItem(item, post, request.user)
191 response_data['count'] = post.offensive_flag_count
192 # send signal when question or answer be marked offensive
193 mark_offensive.send(sender=post.__class__, instance=post, mark_by=request.user)
194 elif vote_type in ['9', '10']:
197 if vote_type == '10':
198 post_id = request.POST.get('postId')
199 post = get_object_or_404(Answer, id=post_id)
201 if not auth.can_delete_post(request.user, post):
202 response_data['allowed'] = -2
203 elif post.deleted == True:
204 logging.debug('debug restoring post in view')
205 auth.onDeleteCanceled(post, request.user)
206 response_data['status'] = 1
208 auth.onDeleted(post, request.user)
209 delete_post_or_answer.send(sender=post.__class__, instance=post, delete_by=request.user)
210 elif vote_type == '11':#subscribe q updates
212 if user.is_authenticated():
213 if user not in question.followed_by.all():
214 question.followed_by.add(user)
215 if settings.EMAIL_VALIDATION == 'on' and user.email_isvalid == False:
216 response_data['message'] = \
217 _('subscription saved, %(email)s needs validation, see %(details_url)s') \
218 % {'email':user.email,'details_url':reverse('faq') + '#validate'}
219 feed_setting = EmailFeedSetting.objects.get(subscriber=user,feed_type='q_sel')
220 if feed_setting.frequency == 'n':
221 feed_setting.frequency = 'd'
223 if 'message' in response_data:
224 response_data['message'] += '<br/>'
225 response_data['message'] = _('email update frequency has been set to daily')
226 #response_data['status'] = 1
227 #responst_data['allowed'] = 1
230 #response_data['status'] = 0
231 #response_data['allowed'] = 0
232 elif vote_type == '12':#unsubscribe q updates
234 if user.is_authenticated():
235 if user in question.followed_by.all():
236 question.followed_by.remove(user)
238 response_data['success'] = 0
239 response_data['message'] = u'Request mode is not supported. Please try again.'
241 data = simplejson.dumps(response_data)
244 response_data['message'] = str(e)
245 data = simplejson.dumps(response_data)
246 return HttpResponse(data, mimetype="application/json")
248 #internally grouped views - used by the tagging system
250 def mark_tag(request, tag=None, **kwargs):#tagging system
251 action = kwargs['action']
252 ts = MarkedTag.objects.filter(user=request.user, tag__name=tag)
253 if action == 'remove':
254 logging.debug('deleting tag %s' % tag)
257 reason = kwargs['reason']
260 t = Tag.objects.get(name=tag)
261 mt = MarkedTag(user=request.user, reason=reason, tag=t)
266 ts.update(reason=reason)
267 return HttpResponse(simplejson.dumps(''), mimetype="application/json")
270 def ajax_toggle_ignored_questions(request):#ajax tagging and tag-filtering system
271 if request.user.hide_ignored_questions:
272 new_hide_setting = False
274 new_hide_setting = True
275 request.user.hide_ignored_questions = new_hide_setting
279 def ajax_command(request):#refactor? view processing ajax commands - note "vote" and view others do it too
280 if 'command' not in request.POST:
281 return HttpResponseForbidden(mimetype="application/json")
282 if request.POST['command'] == 'toggle-ignored-questions':
283 return ajax_toggle_ignored_questions(request)
286 def close(request, id):#close question
287 """view to initiate and process
290 question = get_object_or_404(Question, id=id)
291 if not auth.can_close_question(request.user, question):
292 return HttpResponse('Permission denied.')
293 if request.method == 'POST':
294 form = CloseForm(request.POST)
296 reason = form.cleaned_data['reason']
297 question.closed = True
298 question.closed_by = request.user
299 question.closed_at = datetime.datetime.now()
300 question.close_reason = reason
302 return HttpResponseRedirect(question.get_absolute_url())
305 return render_to_response('close.html', {
307 'question' : question,
308 }, context_instance=RequestContext(request))
311 def reopen(request, id):#re-open question
312 """view to initiate and process
315 question = get_object_or_404(Question, id=id)
317 if not auth.can_reopen_question(request.user, question):
318 return HttpResponse('Permission denied.')
319 if request.method == 'POST' :
320 Question.objects.filter(id=question.id).update(closed=False,
321 closed_by=None, closed_at=None, close_reason=None)
322 return HttpResponseRedirect(question.get_absolute_url())
324 return render_to_response('reopen.html', {
325 'question' : question,
326 }, context_instance=RequestContext(request))
328 #osqa-user communication system
329 def read_message(request):#marks message a read
330 if request.method == "POST":
331 if request.POST['formdata'] == 'required':
332 request.session['message_silent'] = 1
333 if request.user.is_authenticated():
334 request.user.delete_messages()
335 return HttpResponse('')