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
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()
39 file_name_suffix = os.path.splitext(f.name)[1].lower()
41 if not file_name_suffix in ('.jpg', '.jpeg', '.gif', '.png', '.bmp', '.tiff', '.ico'):
42 raise FileTypeNotAllow()
44 storage = FileSystemStorage(str(settings.UPFILES_FOLDER), str(settings.UPFILES_ALIAS))
45 new_file_name = storage.save(f.name, f)
48 size = storage.size(new_file_name)
50 if size > float(settings.ALLOW_MAX_FILE_SIZE) * 1024 * 1024:
51 storage.delete(new_file_name)
52 raise FileSizeNotAllow()
54 result = xml_template % ('Good', '', str(settings.UPFILES_ALIAS) + new_file_name)
55 except UploadPermissionNotAuthorized:
56 result = xml_template % ('', _('uploading images is limited to users with >60 reputation points'), '')
57 except FileTypeNotAllow:
58 result = xml_template % ('', _("allowed file types are 'jpg', 'jpeg', 'gif', 'bmp', 'png', 'tiff'"), '')
59 except FileSizeNotAllow:
60 result = xml_template % ('', _("maximum upload file size is %sM") % settings.ALLOW_MAX_FILE_SIZE, '')
62 result = xml_template % ('', _('Error uploading file. Please contact the site administrator. Thank you. %s' % e), '')
64 return HttpResponse(result, mimetype="application/xml")
67 if request.POST and "text" in request.POST:
68 form = AskForm(request.POST, user=request.user)
70 if request.user.is_authenticated():
71 ask_action = AskAction(user=request.user, ip=request.META['REMOTE_ADDR']).save(data=form.cleaned_data)
72 question = ask_action.node
74 if settings.WIKI_ON and request.POST.get('wiki', False):
75 question.nstate.wiki = ask_action
77 return HttpResponseRedirect(question.get_absolute_url())
79 request.session['temp_node_data'] = request.POST
80 request.session['temp_node_type'] = 'question'
81 return HttpResponseRedirect(reverse('auth_action_signin', kwargs={'action': 'newquestion'}))
82 elif request.method == "POST" and "go" in request.POST:
83 form = AskForm({'title': request.POST['q']}, user=request.user)
85 form = AskForm(user=request.user)
87 return render_to_response('ask.html', {
89 'email_validation_faq_url':reverse('faq') + '#validate',
90 }, context_instance=RequestContext(request))
93 def edit_question(request, id):
94 question = get_object_or_404(Question, id=id)
95 if question.nis.deleted and not request.user.can_view_deleted_post(question):
97 if request.user.can_edit_post(question):
98 return _edit_question(request, question)
99 elif request.user.can_retag_questions():
100 return _retag_question(request, question)
104 def _retag_question(request, question):
105 if request.method == 'POST':
106 form = RetagQuestionForm(question, request.POST)
108 if form.has_changed():
109 RetagAction(user=request.user, node=question, ip=request.META['REMOTE_ADDR']).save(data=dict(tagnames=form.cleaned_data['tags']))
111 return HttpResponseRedirect(question.get_absolute_url())
113 form = RetagQuestionForm(question)
114 return render_to_response('question_retag.html', {
115 'question': question,
117 #'tags' : _get_tags_cache_json(),
118 }, context_instance=RequestContext(request))
120 def _edit_question(request, question):
121 if request.method == 'POST':
122 revision_form = RevisionForm(question, data=request.POST)
123 revision_form.is_valid()
124 revision = question.revisions.get(revision=revision_form.cleaned_data['revision'])
126 if 'select_revision' in request.POST:
127 form = EditQuestionForm(question, request.user, revision)
129 form = EditQuestionForm(question, request.user, revision, data=request.POST)
131 if not 'select_revision' in request.POST and form.is_valid():
132 if form.has_changed():
133 action = ReviseAction(user=request.user, node=question, ip=request.META['REMOTE_ADDR']).save(data=form.cleaned_data)
136 if request.POST.get('wiki', False) and not question.nis.wiki:
137 question.nstate.wiki = action
138 elif question.nis.wiki and (not request.POST.get('wiki', False)) and request.user.can_cancel_wiki(question):
139 question.nstate.wiki = None
141 if not revision == question.active_revision:
142 RollbackAction(user=request.user, node=question).save(data=dict(activate=revision))
144 return HttpResponseRedirect(question.get_absolute_url())
146 revision_form = RevisionForm(question)
147 form = EditQuestionForm(question, request.user)
149 return render_to_response('question_edit.html', {
150 'question': question,
151 'revision_form': revision_form,
153 #'tags' : _get_tags_cache_json()
154 }, context_instance=RequestContext(request))
157 def edit_answer(request, id):
158 answer = get_object_or_404(Answer, id=id)
159 if answer.deleted and not request.user.can_view_deleted_post(answer):
161 elif not request.user.can_edit_post(answer):
164 if request.method == "POST":
165 revision_form = RevisionForm(answer, data=request.POST)
166 revision_form.is_valid()
167 revision = answer.revisions.get(revision=revision_form.cleaned_data['revision'])
169 if 'select_revision' in request.POST:
170 form = EditAnswerForm(answer, request.user, revision)
172 form = EditAnswerForm(answer, request.user, revision, data=request.POST)
174 if not 'select_revision' in request.POST and form.is_valid():
175 if form.has_changed():
176 action = ReviseAction(user=request.user, node=answer, ip=request.META['REMOTE_ADDR']).save(data=form.cleaned_data)
179 if request.POST.get('wiki', False) and not answer.nis.wiki:
180 answer.nstate.wiki = action
181 elif answer.nis.wiki and (not request.POST.get('wiki', False)) and request.user.can_cancel_wiki(answer):
182 answer.nstate.wiki = None
184 if not revision == answer.active_revision:
185 RollbackAction(user=request.user, node=answer, ip=request.META['REMOTE_ADDR']).save(data=dict(activate=revision))
187 return HttpResponseRedirect(answer.get_absolute_url())
190 revision_form = RevisionForm(answer)
191 form = EditAnswerForm(answer, request.user)
192 return render_to_response('answer_edit.html', {
194 'revision_form': revision_form,
196 }, context_instance=RequestContext(request))
198 def answer(request, id):
199 question = get_object_or_404(Question, id=id)
201 form = AnswerForm(question, request.POST)
203 if request.user.is_authenticated():
204 answer_action = AnswerAction(user=request.user, ip=request.META['REMOTE_ADDR']).save(dict(question=question, **form.cleaned_data))
205 answer = answer_action.node
207 if settings.WIKI_ON and request.POST.get('wiki', False):
208 answer.nstate.wiki = answer_action
210 return HttpResponseRedirect(answer.get_absolute_url())
212 request.session['temp_node_data'] = request.POST
213 request.session['temp_node_type'] = 'answer'
214 request.session['temp_question_id'] = id
215 return HttpResponseRedirect(reverse('auth_action_signin', kwargs={'action': 'newquestion'}))
217 request.session['redirect_POST_data'] = request.POST
218 return HttpResponseRedirect(question.get_absolute_url() + '#fmanswer')
220 return HttpResponseRedirect(question.get_absolute_url())