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, HttpResponseForbidden, 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.const import *
20 from forum.utils.forms import get_next_url
21 from forum.views.commands import SpamNotAllowedException
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 #<result><msg><![CDATA[%s]]></msg><error><![CDATA[%s]]></error><file_url>%s</file_url></result>
33 xml_template = "<result><msg><![CDATA[%s]]></msg><error><![CDATA[%s]]></error><file_url>%s</file_url></result>"
36 f = request.FILES['file-upload']
37 # check upload permission
38 if not request.user.can_upload_files():
39 raise UploadPermissionNotAuthorized()
42 file_name_suffix = os.path.splitext(f.name)[1].lower()
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(f.name, 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")
71 if request.POST and "text" in request.POST:
72 form = AskForm(request.POST)
74 if request.user.is_authenticated():
76 "user_ip":request.META["REMOTE_ADDR"],
77 "user_agent":request.environ['HTTP_USER_AGENT'],
78 "comment_author":request.user.username,
79 "comment_author_email":request.user.email,
80 "comment_author_url":request.user.website,
81 "comment":request.POST['text']
83 if Node.isSpam(request.POST['text'], data):
84 raise SpamNotAllowedException("question")
86 question = AskAction(user=request.user).save(data=form.cleaned_data).node
87 return HttpResponseRedirect(question.get_absolute_url())
89 request.session['temp_node_data'] = request.POST
90 request.session['temp_node_type'] = 'question'
91 return HttpResponseRedirect(reverse('auth_action_signin', kwargs={'action': 'newquestion'}))
92 elif request.method == "POST" and "go" in request.POST:
93 form = AskForm({'title': request.POST['q']})
97 #tags = _get_tags_cache_json()
98 return render_to_response('ask.html', {
101 'email_validation_faq_url':reverse('faq') + '#validate',
102 }, context_instance=RequestContext(request))
105 def edit_question(request, id):
106 question = get_object_or_404(Question, id=id)
107 if question.deleted and not request.user.can_view_deleted_post(question):
109 if request.user.can_edit_post(question):
110 return _edit_question(request, question)
111 elif request.user.can_retag_questions():
112 return _retag_question(request, question)
116 def _retag_question(request, question):
117 if request.method == 'POST':
118 form = RetagQuestionForm(question, request.POST)
120 if form.has_changed():
121 RetagAction(user=request.user, node=question).save(data=dict(tagnames=form.cleaned_data['tags']))
123 return HttpResponseRedirect(question.get_absolute_url())
125 form = RetagQuestionForm(question)
126 return render_to_response('question_retag.html', {
127 'question': question,
129 #'tags' : _get_tags_cache_json(),
130 }, context_instance=RequestContext(request))
132 def _edit_question(request, question):
133 if request.method == 'POST':
134 revision_form = RevisionForm(question, data=request.POST)
135 revision_form.is_valid()
136 revision = question.revisions.get(revision=revision_form.cleaned_data['revision'])
138 if 'select_revision' in request.POST:
139 form = EditQuestionForm(question, revision)
141 form = EditQuestionForm(question, revision, data=request.POST)
143 if not 'select_revision' in request.POST and form.is_valid():
144 if form.has_changed():
145 ReviseAction(user=request.user, node=question).save(data=form.cleaned_data)
147 if not revision == question.active_revision:
148 RollbackAction(user=request.user, node=question).save(data=dict(activate=revision))
150 return HttpResponseRedirect(question.get_absolute_url())
152 revision_form = RevisionForm(question)
153 form = EditQuestionForm(question)
155 return render_to_response('question_edit.html', {
156 'question': question,
157 'revision_form': revision_form,
159 #'tags' : _get_tags_cache_json()
160 }, context_instance=RequestContext(request))
163 def edit_answer(request, id):
164 answer = get_object_or_404(Answer, id=id)
165 if answer.deleted and not request.user.can_view_deleted_post(answer):
167 elif not request.user.can_edit_post(answer):
170 if request.method == "POST":
171 revision_form = RevisionForm(answer, data=request.POST)
172 revision_form.is_valid()
173 revision = answer.revisions.get(revision=revision_form.cleaned_data['revision'])
175 if 'select_revision' in request.POST:
176 form = EditAnswerForm(answer, revision)
178 form = EditAnswerForm(answer, revision, data=request.POST)
180 if not 'select_revision' in request.POST and form.is_valid():
181 if form.has_changed():
182 ReviseAction(user=request.user, node=answer).save(data=form.cleaned_data)
184 if not revision == answer.active_revision:
185 RollbackAction(user=request.user, node=answer).save(data=dict(activate=revision))
187 return HttpResponseRedirect(answer.get_absolute_url())
190 revision_form = RevisionForm(answer)
191 form = EditAnswerForm(answer)
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():
205 "user_ip":request.META["REMOTE_ADDR"],
206 "user_agent":request.environ['HTTP_USER_AGENT'],
207 "comment_author":request.user.username,
208 "comment_author_email":request.user.email,
209 "comment_author_url":request.user.website,
210 "comment":request.POST['text']
212 if Node.isSpam(request.POST['text'], data):
213 raise SpamNotAllowedException("answer")
215 answer = AnswerAction(user=request.user).save(dict(question=question, **form.cleaned_data)).node
216 return HttpResponseRedirect(answer.get_absolute_url())
218 request.session['temp_node_data'] = request.POST
219 request.session['temp_node_type'] = 'answer'
220 request.session['temp_question_id'] = id
221 return HttpResponseRedirect(reverse('auth_action_signin', kwargs={'action': 'newquestion'}))
223 return HttpResponseRedirect(question.get_absolute_url())