3 import time, datetime, random
5 from django.core.files.storage import FileSystemStorage
6 from django.shortcuts import render_to_response, get_object_or_404
7 from django.http import HttpResponseRedirect, HttpResponse, Http404
8 from django.template import RequestContext
9 from django.utils.html import *
10 from django.utils import simplejson
11 from django.utils.translation import ugettext as _
12 from django.core.urlresolvers import reverse
13 from django.core.exceptions import PermissionDenied
15 from forum.actions import AskAction, AnswerAction, ReviseAction, RollbackAction, RetagAction, AnswerToQuestionAction
16 from forum.forms import *
17 from forum.models import *
18 from forum.forms import get_next_url
19 from forum.utils import html
20 from forum.http_responses import HttpResponseUnauthorized
22 from vars import PENDING_SUBMISSION_SESSION_ATTR
24 def upload(request):#ajax upload file to a question or answer
25 class FileTypeNotAllow(Exception):
27 class FileSizeNotAllow(Exception):
29 class UploadPermissionNotAuthorized(Exception):
32 xml_template = "<result><msg><![CDATA[%s]]></msg><error><![CDATA[%s]]></error><file_url>%s</file_url></result>"
35 f = request.FILES['file-upload']
36 # check upload permission
37 if not request.user.can_upload_files():
38 raise UploadPermissionNotAuthorized()
42 file_name_suffix = os.path.splitext(f.name)[1].lower()
44 raise FileTypeNotAllow()
46 if not file_name_suffix in ('.jpg', '.jpeg', '.gif', '.png', '.bmp', '.tiff', '.ico'):
47 raise FileTypeNotAllow()
49 storage = FileSystemStorage(str(settings.UPFILES_FOLDER), str(settings.UPFILES_ALIAS))
50 new_file_name = storage.save("_".join(f.name.split()), f)
53 size = storage.size(new_file_name)
55 if size > float(settings.ALLOW_MAX_FILE_SIZE) * 1024 * 1024:
56 storage.delete(new_file_name)
57 raise FileSizeNotAllow()
59 result = xml_template % ('Good', '', str(settings.UPFILES_ALIAS) + new_file_name)
60 except UploadPermissionNotAuthorized:
61 result = xml_template % ('', _('uploading images is limited to users with >60 reputation points'), '')
62 except FileTypeNotAllow:
63 result = xml_template % ('', _("allowed file types are 'jpg', 'jpeg', 'gif', 'bmp', 'png', 'tiff'"), '')
64 except FileSizeNotAllow:
65 result = xml_template % ('', _("maximum upload file size is %sM") % settings.ALLOW_MAX_FILE_SIZE, '')
67 result = xml_template % ('', _('Error uploading file. Please contact the site administrator. Thank you. %s' % e), '')
69 return HttpResponse(result, mimetype="application/xml")
75 if request.session.pop('reviewing_pending_data', False):
76 form = AskForm(initial=request.POST, user=request.user)
77 elif "text" in request.POST:
78 form = AskForm(request.POST, user=request.user)
80 if request.user.is_authenticated() and request.user.email_valid_and_can_ask():
81 ask_action = AskAction(user=request.user, ip=request.META['REMOTE_ADDR']).save(data=form.cleaned_data)
82 question = ask_action.node
84 if settings.WIKI_ON and request.POST.get('wiki', False):
85 question.nstate.wiki = ask_action
87 return HttpResponseRedirect(question.get_absolute_url())
89 request.session[PENDING_SUBMISSION_SESSION_ATTR] = {
91 'data_name': _("question"),
93 'submission_url': reverse('ask'),
94 'time': datetime.datetime.now()
97 if request.user.is_authenticated():
98 request.user.message_set.create(message=_("Your question is pending until you %s.") % html.hyperlink(
99 reverse('send_validation_email'), _("validate your email")
101 return HttpResponseRedirect(reverse('index'))
103 return HttpResponseRedirect(reverse('auth_signin'))
104 elif "go" in request.POST:
105 form = AskForm({'title': request.POST['q']}, user=request.user)
108 form = AskForm(user=request.user)
110 return render_to_response('ask.html', {
113 }, context_instance=RequestContext(request))
115 def convert_to_question(request, id):
117 answer = get_object_or_404(Answer, id=id)
119 if not user.can_convert_to_question(answer):
120 return HttpResponseUnauthorized(request)
122 return _edit_question(request, answer, template='node/convert_to_question.html', summary=_("Converted to question"),
123 action_class=AnswerToQuestionAction, allow_rollback=False, url_getter=lambda a: Question.objects.get(id=a.id).get_absolute_url())
125 def edit_question(request, id):
126 question = get_object_or_404(Question, id=id)
127 if question.nis.deleted and not request.user.can_view_deleted_post(question):
129 if request.user.can_edit_post(question):
130 return _edit_question(request, question)
131 elif request.user.can_retag_questions():
132 return _retag_question(request, question)
136 def _retag_question(request, question):
137 if request.method == 'POST':
138 form = RetagQuestionForm(question, request.POST)
140 if form.has_changed():
141 RetagAction(user=request.user, node=question, ip=request.META['REMOTE_ADDR']).save(data=dict(tagnames=form.cleaned_data['tags']))
143 return HttpResponseRedirect(question.get_absolute_url())
145 form = RetagQuestionForm(question)
146 return render_to_response('question_retag.html', {
147 'question': question,
149 #'tags' : _get_tags_cache_json(),
150 }, context_instance=RequestContext(request))
152 def _edit_question(request, question, template='question_edit.html', summary='', action_class=ReviseAction, allow_rollback=True, url_getter=lambda q: q.get_absolute_url()):
153 if request.method == 'POST':
154 revision_form = RevisionForm(question, data=request.POST)
155 revision_form.is_valid()
156 revision = question.revisions.get(revision=revision_form.cleaned_data['revision'])
158 if 'select_revision' in request.POST:
159 form = EditQuestionForm(question, request.user, revision)
161 form = EditQuestionForm(question, request.user, revision, data=request.POST)
163 if not 'select_revision' in request.POST and form.is_valid():
164 if form.has_changed():
165 action = action_class(user=request.user, node=question, ip=request.META['REMOTE_ADDR']).save(data=form.cleaned_data)
168 if request.POST.get('wiki', False) and not question.nis.wiki:
169 question.nstate.wiki = action
170 elif question.nis.wiki and (not request.POST.get('wiki', False)) and request.user.can_cancel_wiki(question):
171 question.nstate.wiki = None
173 if not revision == question.active_revision:
175 RollbackAction(user=request.user, node=question).save(data=dict(activate=revision))
179 return HttpResponseRedirect(url_getter(question))
181 revision_form = RevisionForm(question)
182 form = EditQuestionForm(question, request.user, initial={'summary': summary})
184 return render_to_response(template, {
185 'question': question,
186 'revision_form': revision_form,
188 }, context_instance=RequestContext(request))
191 def edit_answer(request, id):
192 answer = get_object_or_404(Answer, id=id)
193 if answer.deleted and not request.user.can_view_deleted_post(answer):
195 elif not request.user.can_edit_post(answer):
198 if request.method == "POST":
199 revision_form = RevisionForm(answer, data=request.POST)
200 revision_form.is_valid()
201 revision = answer.revisions.get(revision=revision_form.cleaned_data['revision'])
203 if 'select_revision' in request.POST:
204 form = EditAnswerForm(answer, request.user, revision)
206 form = EditAnswerForm(answer, request.user, revision, data=request.POST)
208 if not 'select_revision' in request.POST and form.is_valid():
209 if form.has_changed():
210 action = ReviseAction(user=request.user, node=answer, ip=request.META['REMOTE_ADDR']).save(data=form.cleaned_data)
213 if request.POST.get('wiki', False) and not answer.nis.wiki:
214 answer.nstate.wiki = action
215 elif answer.nis.wiki and (not request.POST.get('wiki', False)) and request.user.can_cancel_wiki(answer):
216 answer.nstate.wiki = None
218 if not revision == answer.active_revision:
219 RollbackAction(user=request.user, node=answer, ip=request.META['REMOTE_ADDR']).save(data=dict(activate=revision))
221 return HttpResponseRedirect(answer.get_absolute_url())
224 revision_form = RevisionForm(answer)
225 form = EditAnswerForm(answer, request.user)
226 return render_to_response('answer_edit.html', {
228 'revision_form': revision_form,
230 }, context_instance=RequestContext(request))
232 def answer(request, id):
233 question = get_object_or_404(Question, id=id)
236 form = AnswerForm(request.POST, request.user)
238 if request.session.pop('reviewing_pending_data', False) or not form.is_valid():
239 request.session['redirect_POST_data'] = request.POST
240 return HttpResponseRedirect(question.get_absolute_url() + '#fmanswer')
242 if request.user.is_authenticated() and request.user.email_valid_and_can_answer():
243 answer_action = AnswerAction(user=request.user, ip=request.META['REMOTE_ADDR']).save(dict(question=question, **form.cleaned_data))
244 answer = answer_action.node
246 if settings.WIKI_ON and request.POST.get('wiki', False):
247 answer.nstate.wiki = answer_action
249 return HttpResponseRedirect(answer.get_absolute_url())
251 request.session[PENDING_SUBMISSION_SESSION_ATTR] = {
252 'POST': request.POST,
253 'data_name': _("answer"),
255 'submission_url': reverse('answer', kwargs={'id': id}),
256 'time': datetime.datetime.now()
259 if request.user.is_authenticated():
260 request.user.message_set.create(message=_("Your answer is pending until you %s.") % html.hyperlink(
261 reverse('send_validation_email'), _("validate your email")
263 return HttpResponseRedirect(question.get_absolute_url())
265 return HttpResponseRedirect(reverse('auth_signin'))
267 return HttpResponseRedirect(question.get_absolute_url())
270 def manage_pending_data(request, action, forward=None):
271 pending_data = request.session.pop(PENDING_SUBMISSION_SESSION_ATTR, None)
276 if action == _("cancel"):
277 return HttpResponseRedirect(forward or request.META.get('HTTP_REFERER', '/'))
279 if action == _("review"):
280 request.session['reviewing_pending_data'] = True
282 request.session['redirect_POST_data'] = pending_data['POST']
283 return HttpResponseRedirect(pending_data['submission_url'])