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.contrib.auth.decorators import login_required
8 from django.http import HttpResponseRedirect, HttpResponse, Http404
9 from django.template import RequestContext
10 from django.utils.html import *
11 from django.utils import simplejson
12 from django.utils.translation import ugettext as _
13 from django.core.urlresolvers import reverse
14 from django.core.exceptions import PermissionDenied
16 from forum.actions import AskAction, AnswerAction, ReviseAction, RollbackAction, RetagAction
17 from forum.forms import *
18 from forum.models import *
19 from forum.forms import get_next_url
20 from forum.utils import html
23 def upload(request):#ajax upload file to a question or answer
24 class FileTypeNotAllow(Exception):
26 class FileSizeNotAllow(Exception):
28 class UploadPermissionNotAuthorized(Exception):
31 xml_template = "<result><msg><![CDATA[%s]]></msg><error><![CDATA[%s]]></error><file_url>%s</file_url></result>"
34 f = request.FILES['file-upload']
35 # check upload permission
36 if not request.user.can_upload_files():
37 raise UploadPermissionNotAuthorized()
41 file_name_suffix = os.path.splitext(f.name)[1].lower()
43 raise FileTypeNotAllow()
45 if not file_name_suffix in ('.jpg', '.jpeg', '.gif', '.png', '.bmp', '.tiff', '.ico'):
46 raise FileTypeNotAllow()
48 storage = FileSystemStorage(str(settings.UPFILES_FOLDER), str(settings.UPFILES_ALIAS))
49 new_file_name = storage.save("_".join(f.name.split()), f)
52 size = storage.size(new_file_name)
54 if size > float(settings.ALLOW_MAX_FILE_SIZE) * 1024 * 1024:
55 storage.delete(new_file_name)
56 raise FileSizeNotAllow()
58 result = xml_template % ('Good', '', str(settings.UPFILES_ALIAS) + new_file_name)
59 except UploadPermissionNotAuthorized:
60 result = xml_template % ('', _('uploading images is limited to users with >60 reputation points'), '')
61 except FileTypeNotAllow:
62 result = xml_template % ('', _("allowed file types are 'jpg', 'jpeg', 'gif', 'bmp', 'png', 'tiff'"), '')
63 except FileSizeNotAllow:
64 result = xml_template % ('', _("maximum upload file size is %sM") % settings.ALLOW_MAX_FILE_SIZE, '')
66 result = xml_template % ('', _('Error uploading file. Please contact the site administrator. Thank you. %s' % e), '')
68 return HttpResponse(result, mimetype="application/xml")
74 if request.session.pop('reviewing_pending_data', False):
75 form = AskForm(initial=request.POST, user=request.user)
76 elif "text" in request.POST:
77 form = AskForm(request.POST, user=request.user)
79 if request.user.is_authenticated() and request.user.email_valid_and_can_ask():
80 ask_action = AskAction(user=request.user, ip=request.META['REMOTE_ADDR']).save(data=form.cleaned_data)
81 question = ask_action.node
83 if settings.WIKI_ON and request.POST.get('wiki', False):
84 question.nstate.wiki = ask_action
86 return HttpResponseRedirect(question.get_absolute_url())
88 request.session['pending_submission_data'] = {
90 'data_name': _("question"),
92 'submission_url': reverse('ask'),
93 'time': datetime.datetime.now()
96 if request.user.is_authenticated():
97 request.user.message_set.create(message=_("Your question is pending until you %s.") % html.hyperlink(
98 reverse('send_validation_email'), _("validate your email")
100 return HttpResponseRedirect(reverse('index'))
102 return HttpResponseRedirect(reverse('auth_signin'))
103 elif "go" in request.POST:
104 form = AskForm({'title': request.POST['q']}, user=request.user)
107 form = AskForm(user=request.user)
109 return render_to_response('ask.html', {
111 }, context_instance=RequestContext(request))
114 def edit_question(request, id):
115 question = get_object_or_404(Question, id=id)
116 if question.nis.deleted and not request.user.can_view_deleted_post(question):
118 if request.user.can_edit_post(question):
119 return _edit_question(request, question)
120 elif request.user.can_retag_questions():
121 return _retag_question(request, question)
125 def _retag_question(request, question):
126 if request.method == 'POST':
127 form = RetagQuestionForm(question, request.POST)
129 if form.has_changed():
130 RetagAction(user=request.user, node=question, ip=request.META['REMOTE_ADDR']).save(data=dict(tagnames=form.cleaned_data['tags']))
132 return HttpResponseRedirect(question.get_absolute_url())
134 form = RetagQuestionForm(question)
135 return render_to_response('question_retag.html', {
136 'question': question,
138 #'tags' : _get_tags_cache_json(),
139 }, context_instance=RequestContext(request))
141 def _edit_question(request, question):
142 if request.method == 'POST':
143 revision_form = RevisionForm(question, data=request.POST)
144 revision_form.is_valid()
145 revision = question.revisions.get(revision=revision_form.cleaned_data['revision'])
147 if 'select_revision' in request.POST:
148 form = EditQuestionForm(question, request.user, revision)
150 form = EditQuestionForm(question, request.user, revision, data=request.POST)
152 if not 'select_revision' in request.POST and form.is_valid():
153 if form.has_changed():
154 action = ReviseAction(user=request.user, node=question, ip=request.META['REMOTE_ADDR']).save(data=form.cleaned_data)
157 if request.POST.get('wiki', False) and not question.nis.wiki:
158 question.nstate.wiki = action
159 elif question.nis.wiki and (not request.POST.get('wiki', False)) and request.user.can_cancel_wiki(question):
160 question.nstate.wiki = None
162 if not revision == question.active_revision:
163 RollbackAction(user=request.user, node=question).save(data=dict(activate=revision))
165 return HttpResponseRedirect(question.get_absolute_url())
167 revision_form = RevisionForm(question)
168 form = EditQuestionForm(question, request.user)
170 return render_to_response('question_edit.html', {
171 'question': question,
172 'revision_form': revision_form,
174 #'tags' : _get_tags_cache_json()
175 }, context_instance=RequestContext(request))
178 def edit_answer(request, id):
179 answer = get_object_or_404(Answer, id=id)
180 if answer.deleted and not request.user.can_view_deleted_post(answer):
182 elif not request.user.can_edit_post(answer):
185 if request.method == "POST":
186 revision_form = RevisionForm(answer, data=request.POST)
187 revision_form.is_valid()
188 revision = answer.revisions.get(revision=revision_form.cleaned_data['revision'])
190 if 'select_revision' in request.POST:
191 form = EditAnswerForm(answer, request.user, revision)
193 form = EditAnswerForm(answer, request.user, revision, data=request.POST)
195 if not 'select_revision' in request.POST and form.is_valid():
196 if form.has_changed():
197 action = ReviseAction(user=request.user, node=answer, ip=request.META['REMOTE_ADDR']).save(data=form.cleaned_data)
200 if request.POST.get('wiki', False) and not answer.nis.wiki:
201 answer.nstate.wiki = action
202 elif answer.nis.wiki and (not request.POST.get('wiki', False)) and request.user.can_cancel_wiki(answer):
203 answer.nstate.wiki = None
205 if not revision == answer.active_revision:
206 RollbackAction(user=request.user, node=answer, ip=request.META['REMOTE_ADDR']).save(data=dict(activate=revision))
208 return HttpResponseRedirect(answer.get_absolute_url())
211 revision_form = RevisionForm(answer)
212 form = EditAnswerForm(answer, request.user)
213 return render_to_response('answer_edit.html', {
215 'revision_form': revision_form,
217 }, context_instance=RequestContext(request))
219 def answer(request, id):
220 question = get_object_or_404(Question, id=id)
223 form = AnswerForm(question, request.POST)
225 if request.session.pop('reviewing_pending_data', False) or not form.is_valid():
226 request.session['redirect_POST_data'] = request.POST
227 return HttpResponseRedirect(question.get_absolute_url() + '#fmanswer')
229 if request.user.is_authenticated() and request.user.email_valid_and_can_answer():
230 answer_action = AnswerAction(user=request.user, ip=request.META['REMOTE_ADDR']).save(dict(question=question, **form.cleaned_data))
231 answer = answer_action.node
233 if settings.WIKI_ON and request.POST.get('wiki', False):
234 answer.nstate.wiki = answer_action
236 return HttpResponseRedirect(answer.get_absolute_url())
238 request.session['pending_submission_data'] = {
239 'POST': request.POST,
240 'data_name': _("answer"),
242 'submission_url': reverse('answer', kwargs={'id': id}),
243 'time': datetime.datetime.now()
246 if request.user.is_authenticated():
247 request.user.message_set.create(message=_("Your answer is pending until you %s.") % html.hyperlink(
248 reverse('send_validation_email'), _("validate your email")
250 return HttpResponseRedirect(question.get_absolute_url())
252 return HttpResponseRedirect(reverse('auth_signin'))
254 return HttpResponseRedirect(question.get_absolute_url())
257 def manage_pending_data(request, action, forward=None):
258 pending_data = request.session.pop('pending_submission_data', None)
263 if action == _("cancel"):
264 return HttpResponseRedirect(forward or request.META.get('HTTP_REFERER', '/'))
266 if action == _("review"):
267 request.session['reviewing_pending_data'] = True
269 request.session['redirect_POST_data'] = pending_data['POST']
270 return HttpResponseRedirect(pending_data['submission_url'])