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()
40 file_name_suffix = os.path.splitext(f.name)[1].lower()
42 if not file_name_suffix in ('.jpg', '.jpeg', '.gif', '.png', '.bmp', '.tiff', '.ico'):
43 raise FileTypeNotAllow()
45 storage = FileSystemStorage(str(settings.UPFILES_FOLDER), str(settings.UPFILES_ALIAS))
46 new_file_name = storage.save(f.name, f)
49 size = storage.size(new_file_name)
51 if size > float(settings.ALLOW_MAX_FILE_SIZE) * 1024 * 1024:
52 storage.delete(new_file_name)
53 raise FileSizeNotAllow()
55 result = xml_template % ('Good', '', str(settings.UPFILES_ALIAS) + new_file_name)
56 except UploadPermissionNotAuthorized:
57 result = xml_template % ('', _('uploading images is limited to users with >60 reputation points'), '')
58 except FileTypeNotAllow:
59 result = xml_template % ('', _("allowed file types are 'jpg', 'jpeg', 'gif', 'bmp', 'png', 'tiff'"), '')
60 except FileSizeNotAllow:
61 result = xml_template % ('', _("maximum upload file size is %sM") % settings.ALLOW_MAX_FILE_SIZE, '')
63 result = xml_template % ('', _('Error uploading file. Please contact the site administrator. Thank you. %s' % e), '')
65 return HttpResponse(result, mimetype="application/xml")
71 if request.session.pop('reviewing_pending_data', False):
72 form = AskForm(initial=request.POST, user=request.user)
73 elif "text" in request.POST:
74 form = AskForm(request.POST, user=request.user)
76 if request.user.is_authenticated() and request.user.email_valid_and_can_ask():
77 ask_action = AskAction(user=request.user, ip=request.META['REMOTE_ADDR']).save(data=form.cleaned_data)
78 question = ask_action.node
80 if settings.WIKI_ON and request.POST.get('wiki', False):
81 question.nstate.wiki = ask_action
83 return HttpResponseRedirect(question.get_absolute_url())
85 request.session['pending_submission_data'] = {
87 'data_name': _("question"),
89 'submission_url': reverse('ask'),
90 'time': datetime.datetime.now()
93 if request.user.is_authenticated():
94 request.user.message_set.create(message=_("Your question is pending until you %s.") % html.hyperlink(
95 reverse('send_validation_email'), _("validate your email")
97 return HttpResponseRedirect(reverse('index'))
99 return HttpResponseRedirect(reverse('auth_signin'))
100 elif "go" in request.POST:
101 form = AskForm({'title': request.POST['q']}, user=request.user)
104 form = AskForm(user=request.user)
106 return render_to_response('ask.html', {
108 'email_validation_faq_url':reverse('faq') + '#validate',
109 }, context_instance=RequestContext(request))
112 def edit_question(request, id):
113 question = get_object_or_404(Question, id=id)
114 if question.nis.deleted and not request.user.can_view_deleted_post(question):
116 if request.user.can_edit_post(question):
117 return _edit_question(request, question)
118 elif request.user.can_retag_questions():
119 return _retag_question(request, question)
123 def _retag_question(request, question):
124 if request.method == 'POST':
125 form = RetagQuestionForm(question, request.POST)
127 if form.has_changed():
128 RetagAction(user=request.user, node=question, ip=request.META['REMOTE_ADDR']).save(data=dict(tagnames=form.cleaned_data['tags']))
130 return HttpResponseRedirect(question.get_absolute_url())
132 form = RetagQuestionForm(question)
133 return render_to_response('question_retag.html', {
134 'question': question,
136 #'tags' : _get_tags_cache_json(),
137 }, context_instance=RequestContext(request))
139 def _edit_question(request, question):
140 if request.method == 'POST':
141 revision_form = RevisionForm(question, data=request.POST)
142 revision_form.is_valid()
143 revision = question.revisions.get(revision=revision_form.cleaned_data['revision'])
145 if 'select_revision' in request.POST:
146 form = EditQuestionForm(question, request.user, revision)
148 form = EditQuestionForm(question, request.user, revision, data=request.POST)
150 if not 'select_revision' in request.POST and form.is_valid():
151 if form.has_changed():
152 action = ReviseAction(user=request.user, node=question, ip=request.META['REMOTE_ADDR']).save(data=form.cleaned_data)
155 if request.POST.get('wiki', False) and not question.nis.wiki:
156 question.nstate.wiki = action
157 elif question.nis.wiki and (not request.POST.get('wiki', False)) and request.user.can_cancel_wiki(question):
158 question.nstate.wiki = None
160 if not revision == question.active_revision:
161 RollbackAction(user=request.user, node=question).save(data=dict(activate=revision))
163 return HttpResponseRedirect(question.get_absolute_url())
165 revision_form = RevisionForm(question)
166 form = EditQuestionForm(question, request.user)
168 return render_to_response('question_edit.html', {
169 'question': question,
170 'revision_form': revision_form,
172 #'tags' : _get_tags_cache_json()
173 }, context_instance=RequestContext(request))
176 def edit_answer(request, id):
177 answer = get_object_or_404(Answer, id=id)
178 if answer.deleted and not request.user.can_view_deleted_post(answer):
180 elif not request.user.can_edit_post(answer):
183 if request.method == "POST":
184 revision_form = RevisionForm(answer, data=request.POST)
185 revision_form.is_valid()
186 revision = answer.revisions.get(revision=revision_form.cleaned_data['revision'])
188 if 'select_revision' in request.POST:
189 form = EditAnswerForm(answer, request.user, revision)
191 form = EditAnswerForm(answer, request.user, revision, data=request.POST)
193 if not 'select_revision' in request.POST and form.is_valid():
194 if form.has_changed():
195 action = ReviseAction(user=request.user, node=answer, ip=request.META['REMOTE_ADDR']).save(data=form.cleaned_data)
198 if request.POST.get('wiki', False) and not answer.nis.wiki:
199 answer.nstate.wiki = action
200 elif answer.nis.wiki and (not request.POST.get('wiki', False)) and request.user.can_cancel_wiki(answer):
201 answer.nstate.wiki = None
203 if not revision == answer.active_revision:
204 RollbackAction(user=request.user, node=answer, ip=request.META['REMOTE_ADDR']).save(data=dict(activate=revision))
206 return HttpResponseRedirect(answer.get_absolute_url())
209 revision_form = RevisionForm(answer)
210 form = EditAnswerForm(answer, request.user)
211 return render_to_response('answer_edit.html', {
213 'revision_form': revision_form,
215 }, context_instance=RequestContext(request))
217 def answer(request, id):
218 question = get_object_or_404(Question, id=id)
221 form = AnswerForm(question, request.POST)
223 if request.session.pop('reviewing_pending_data', False) or not form.is_valid():
224 request.session['redirect_POST_data'] = request.POST
225 return HttpResponseRedirect(question.get_absolute_url() + '#fmanswer')
227 if request.user.is_authenticated() and request.user.email_valid_and_can_answer():
228 answer_action = AnswerAction(user=request.user, ip=request.META['REMOTE_ADDR']).save(dict(question=question, **form.cleaned_data))
229 answer = answer_action.node
231 if settings.WIKI_ON and request.POST.get('wiki', False):
232 answer.nstate.wiki = answer_action
234 return HttpResponseRedirect(answer.get_absolute_url())
236 request.session['pending_submission_data'] = {
237 'POST': request.POST,
238 'data_name': _("answer"),
240 'submission_url': reverse('answer', kwargs={'id': id}),
241 'time': datetime.datetime.now()
244 if request.user.is_authenticated():
245 request.user.message_set.create(message=_("Your answer is pending until you %s.") % html.hyperlink(
246 reverse('send_validation_email'), _("validate your email")
248 return HttpResponseRedirect(question.get_absolute_url())
250 return HttpResponseRedirect(reverse('auth_signin'))
252 return HttpResponseRedirect(question.get_absolute_url())
255 def manage_pending_data(request, action, forward=None):
256 pending_data = request.session.pop('pending_submission_data', None)
261 if action == _("cancel"):
262 return HttpResponseRedirect(forward or request.META.get('HTTP_REFERER', '/'))
264 if action == _("review"):
265 request.session['reviewing_pending_data'] = True
267 request.session['redirect_POST_data'] = pending_data['POST']
268 return HttpResponseRedirect(pending_data['submission_url'])