4 from django.views.decorators.csrf import csrf_exempt
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.translation import ugettext as _
12 from forum.actions import AskAction, AnswerAction, ReviseAction, RollbackAction, RetagAction, AnswerToQuestionAction, CommentToQuestionAction
13 from forum.forms import *
14 from forum.models import *
15 from forum.utils import html
17 from forum.http_responses import HttpResponseUnauthorized
19 from vars import PENDING_SUBMISSION_SESSION_ATTR
22 def upload(request):#ajax upload file to a question or answer
23 class FileTypeNotAllow(Exception):
25 class FileSizeNotAllow(Exception):
27 class UploadPermissionNotAuthorized(Exception):
30 xml_template = "<result><msg><![CDATA[%s]]></msg><error><![CDATA[%s]]></error><file_url>%s</file_url></result>"
33 f = request.FILES['file-upload']
34 # check upload permission
35 if not request.user.can_upload_files():
36 raise UploadPermissionNotAuthorized()
40 file_name_suffix = os.path.splitext(f.name)[1].lower()
42 raise FileTypeNotAllow()
44 if not file_name_suffix in ('.jpg', '.jpeg', '.gif', '.png', '.bmp', '.tiff', '.ico'):
45 raise FileTypeNotAllow()
47 storage = FileSystemStorage(str(settings.UPFILES_FOLDER), str(settings.UPFILES_ALIAS))
48 new_file_name = storage.save("_".join(f.name.split()), f)
51 size = storage.size(new_file_name)
53 if size > float(settings.ALLOW_MAX_FILE_SIZE) * 1024 * 1024:
54 storage.delete(new_file_name)
55 raise FileSizeNotAllow()
57 result = xml_template % ('Good', '', str(settings.UPFILES_ALIAS) + new_file_name)
58 except UploadPermissionNotAuthorized:
59 result = xml_template % ('', _('uploading images is limited to users with >60 reputation points'), '')
60 except FileTypeNotAllow:
61 result = xml_template % ('', _("allowed file types are 'jpg', 'jpeg', 'gif', 'bmp', 'png', 'tiff'"), '')
62 except FileSizeNotAllow:
63 result = xml_template % ('', _("maximum upload file size is %sM") % settings.ALLOW_MAX_FILE_SIZE, '')
65 result = xml_template % ('', _('Error uploading file. Please contact the site administrator. Thank you. %s' % e), '')
67 return HttpResponse(result, mimetype="application/xml")
73 if request.session.pop('reviewing_pending_data', False):
74 form = AskForm(initial=request.POST, user=request.user)
75 elif "text" in request.POST:
76 form = AskForm(request.POST, user=request.user)
78 if request.user.is_authenticated() and request.user.email_valid_and_can_ask():
79 ask_action = AskAction(user=request.user, ip=request.META['REMOTE_ADDR']).save(data=form.cleaned_data)
80 question = ask_action.node
82 if settings.WIKI_ON and request.POST.get('wiki', False):
83 question.nstate.wiki = ask_action
85 return HttpResponseRedirect(question.get_absolute_url())
87 request.session[PENDING_SUBMISSION_SESSION_ATTR] = {
89 'data_name': _("question"),
91 'submission_url': reverse('ask'),
92 'time': datetime.datetime.now()
95 if request.user.is_authenticated():
96 request.user.message_set.create(message=_("Your question is pending until you %s.") % html.hyperlink(
97 reverse('send_validation_email'), _("validate your email")
99 return HttpResponseRedirect(reverse('index'))
101 return HttpResponseRedirect(reverse('auth_signin'))
102 elif "go" in request.POST:
103 form = AskForm({'title': request.POST['q']}, user=request.user)
106 form = AskForm(user=request.user)
108 return render_to_response('ask.html', {
111 }, context_instance=RequestContext(request))
113 def convert_to_question(request, id):
116 node_type = request.GET.get('node_type', 'answer')
117 if node_type == 'comment':
118 node = get_object_or_404(Comment, id=id)
119 action_class = CommentToQuestionAction
121 node = get_object_or_404(Answer, id=id)
122 action_class = AnswerToQuestionAction
124 if not user.can_convert_to_question(node):
125 return HttpResponseUnauthorized(request)
127 return _edit_question(request, node, template='node/convert_to_question.html', summary=_("Converted to question"),
128 action_class =action_class, allow_rollback=False, url_getter=lambda a: Question.objects.get(id=a.id).get_absolute_url())
130 def edit_question(request, id):
131 question = get_object_or_404(Question, id=id)
132 if question.nis.deleted and not request.user.can_view_deleted_post(question):
134 if request.user.can_edit_post(question):
135 return _edit_question(request, question)
136 elif request.user.can_retag_questions():
137 return _retag_question(request, question)
141 def _retag_question(request, question):
142 if request.method == 'POST':
143 form = RetagQuestionForm(question, request.POST)
145 if form.has_changed():
146 RetagAction(user=request.user, node=question, ip=request.META['REMOTE_ADDR']).save(data=dict(tagnames=form.cleaned_data['tags']))
148 return HttpResponseRedirect(question.get_absolute_url())
150 form = RetagQuestionForm(question)
151 return render_to_response('question_retag.html', {
152 'question': question,
154 #'tags' : _get_tags_cache_json(),
155 }, context_instance=RequestContext(request))
157 def _edit_question(request, question, template='question_edit.html', summary='', action_class=ReviseAction, allow_rollback=True, url_getter=lambda q: q.get_absolute_url()):
158 if request.method == 'POST':
159 revision_form = RevisionForm(question, data=request.POST)
160 revision_form.is_valid()
161 revision = question.revisions.get(revision=revision_form.cleaned_data['revision'])
163 if 'select_revision' in request.POST:
164 form = EditQuestionForm(question, request.user, revision)
166 form = EditQuestionForm(question, request.user, revision, data=request.POST)
168 if not 'select_revision' in request.POST and form.is_valid():
169 if form.has_changed():
170 action = action_class(user=request.user, node=question, ip=request.META['REMOTE_ADDR']).save(data=form.cleaned_data)
173 if request.POST.get('wiki', False) and not question.nis.wiki:
174 question.nstate.wiki = action
175 elif question.nis.wiki and (not request.POST.get('wiki', False)) and request.user.can_cancel_wiki(question):
176 question.nstate.wiki = None
178 if not revision == question.active_revision:
180 RollbackAction(user=request.user, node=question).save(data=dict(activate=revision))
184 return HttpResponseRedirect(url_getter(question))
186 revision_form = RevisionForm(question)
187 form = EditQuestionForm(question, request.user, initial={'summary': summary})
189 return render_to_response(template, {
190 'question': question,
191 'revision_form': revision_form,
193 }, context_instance=RequestContext(request))
196 def edit_answer(request, id):
197 answer = get_object_or_404(Answer, id=id)
198 if answer.deleted and not request.user.can_view_deleted_post(answer):
200 elif not request.user.can_edit_post(answer):
203 if request.method == "POST":
204 revision_form = RevisionForm(answer, data=request.POST)
205 revision_form.is_valid()
206 revision = answer.revisions.get(revision=revision_form.cleaned_data['revision'])
208 if 'select_revision' in request.POST:
209 form = EditAnswerForm(answer, request.user, revision)
211 form = EditAnswerForm(answer, request.user, revision, data=request.POST)
213 if not 'select_revision' in request.POST and form.is_valid():
214 if form.has_changed():
215 action = ReviseAction(user=request.user, node=answer, ip=request.META['REMOTE_ADDR']).save(data=form.cleaned_data)
218 if request.POST.get('wiki', False) and not answer.nis.wiki:
219 answer.nstate.wiki = action
220 elif answer.nis.wiki and (not request.POST.get('wiki', False)) and request.user.can_cancel_wiki(answer):
221 answer.nstate.wiki = None
223 if not revision == answer.active_revision:
224 RollbackAction(user=request.user, node=answer, ip=request.META['REMOTE_ADDR']).save(data=dict(activate=revision))
226 return HttpResponseRedirect(answer.get_absolute_url())
229 revision_form = RevisionForm(answer)
230 form = EditAnswerForm(answer, request.user)
231 return render_to_response('answer_edit.html', {
233 'revision_form': revision_form,
235 }, context_instance=RequestContext(request))
237 def answer(request, id):
238 question = get_object_or_404(Question, id=id)
241 form = AnswerForm(request.POST, request.user)
243 if request.session.pop('reviewing_pending_data', False) or not form.is_valid():
244 request.session['redirect_POST_data'] = request.POST
245 return HttpResponseRedirect(question.get_absolute_url() + '#fmanswer')
247 if request.user.is_authenticated() and request.user.email_valid_and_can_answer():
248 answer_action = AnswerAction(user=request.user, ip=request.META['REMOTE_ADDR']).save(dict(question=question, **form.cleaned_data))
249 answer = answer_action.node
251 if settings.WIKI_ON and request.POST.get('wiki', False):
252 answer.nstate.wiki = answer_action
254 return HttpResponseRedirect(answer.get_absolute_url())
256 request.session[PENDING_SUBMISSION_SESSION_ATTR] = {
257 'POST': request.POST,
258 'data_name': _("answer"),
260 'submission_url': reverse('answer', kwargs={'id': id}),
261 'time': datetime.datetime.now()
264 if request.user.is_authenticated():
265 request.user.message_set.create(message=_("Your answer is pending until you %s.") % html.hyperlink(
266 reverse('send_validation_email'), _("validate your email")
268 return HttpResponseRedirect(question.get_absolute_url())
270 return HttpResponseRedirect(reverse('auth_signin'))
272 return HttpResponseRedirect(question.get_absolute_url())
275 def manage_pending_data(request, action, forward=None):
276 pending_data = request.session.pop(PENDING_SUBMISSION_SESSION_ATTR, None)
281 if action == _("cancel"):
282 return HttpResponseRedirect(forward or request.META.get('HTTP_REFERER', '/'))
284 if action == _("review"):
285 request.session['reviewing_pending_data'] = True
287 request.session['redirect_POST_data'] = pending_data['POST']
288 return HttpResponseRedirect(pending_data['submission_url'])