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.utils.forms import get_next_url
20 from forum.views.commands import SpamNotAllowedException
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")
69 if request.POST and "text" in request.POST:
70 form = AskForm(request.POST)
72 if request.user.is_authenticated():
74 "user_ip":request.META["REMOTE_ADDR"],
75 "user_agent":request.environ['HTTP_USER_AGENT'],
76 "comment_author":request.user.username,
77 "comment_author_email":request.user.email,
78 "comment_author_url":request.user.website,
79 "comment":request.POST['text']
81 if Node.isSpam(request.POST['text'], data):
82 raise SpamNotAllowedException("question")
84 question = AskAction(user=request.user).save(data=form.cleaned_data).node
85 return HttpResponseRedirect(question.get_absolute_url())
87 request.session['temp_node_data'] = request.POST
88 request.session['temp_node_type'] = 'question'
89 return HttpResponseRedirect(reverse('auth_action_signin', kwargs={'action': 'newquestion'}))
90 elif request.method == "POST" and "go" in request.POST:
91 form = AskForm({'title': request.POST['q']})
95 #tags = _get_tags_cache_json()
96 return render_to_response('ask.html', {
99 'email_validation_faq_url':reverse('faq') + '#validate',
100 }, context_instance=RequestContext(request))
103 def edit_question(request, id):
104 question = get_object_or_404(Question, id=id)
105 if question.deleted and not request.user.can_view_deleted_post(question):
107 if request.user.can_edit_post(question):
108 return _edit_question(request, question)
109 elif request.user.can_retag_questions():
110 return _retag_question(request, question)
114 def _retag_question(request, question):
115 if request.method == 'POST':
116 form = RetagQuestionForm(question, request.POST)
118 if form.has_changed():
119 RetagAction(user=request.user, node=question).save(data=dict(tagnames=form.cleaned_data['tags']))
121 return HttpResponseRedirect(question.get_absolute_url())
123 form = RetagQuestionForm(question)
124 return render_to_response('question_retag.html', {
125 'question': question,
127 #'tags' : _get_tags_cache_json(),
128 }, context_instance=RequestContext(request))
130 def _edit_question(request, question):
131 if request.method == 'POST':
132 revision_form = RevisionForm(question, data=request.POST)
133 revision_form.is_valid()
134 revision = question.revisions.get(revision=revision_form.cleaned_data['revision'])
136 if 'select_revision' in request.POST:
137 form = EditQuestionForm(question, revision)
139 form = EditQuestionForm(question, revision, data=request.POST)
141 if not 'select_revision' in request.POST and form.is_valid():
142 if form.has_changed():
143 ReviseAction(user=request.user, node=question).save(data=form.cleaned_data)
145 if not revision == question.active_revision:
146 RollbackAction(user=request.user, node=question).save(data=dict(activate=revision))
148 return HttpResponseRedirect(question.get_absolute_url())
150 revision_form = RevisionForm(question)
151 form = EditQuestionForm(question)
153 return render_to_response('question_edit.html', {
154 'question': question,
155 'revision_form': revision_form,
157 #'tags' : _get_tags_cache_json()
158 }, context_instance=RequestContext(request))
161 def edit_answer(request, id):
162 answer = get_object_or_404(Answer, id=id)
163 if answer.deleted and not request.user.can_view_deleted_post(answer):
165 elif not request.user.can_edit_post(answer):
168 if request.method == "POST":
169 revision_form = RevisionForm(answer, data=request.POST)
170 revision_form.is_valid()
171 revision = answer.revisions.get(revision=revision_form.cleaned_data['revision'])
173 if 'select_revision' in request.POST:
174 form = EditAnswerForm(answer, revision)
176 form = EditAnswerForm(answer, revision, data=request.POST)
178 if not 'select_revision' in request.POST and form.is_valid():
179 if form.has_changed():
180 ReviseAction(user=request.user, node=answer).save(data=form.cleaned_data)
182 if not revision == answer.active_revision:
183 RollbackAction(user=request.user, node=answer).save(data=dict(activate=revision))
185 return HttpResponseRedirect(answer.get_absolute_url())
188 revision_form = RevisionForm(answer)
189 form = EditAnswerForm(answer)
190 return render_to_response('answer_edit.html', {
192 'revision_form': revision_form,
194 }, context_instance=RequestContext(request))
196 def answer(request, id):
197 question = get_object_or_404(Question, id=id)
199 form = AnswerForm(question, request.POST)
201 if request.user.is_authenticated():
203 "user_ip":request.META["REMOTE_ADDR"],
204 "user_agent":request.environ['HTTP_USER_AGENT'],
205 "comment_author":request.user.username,
206 "comment_author_email":request.user.email,
207 "comment_author_url":request.user.website,
208 "comment":request.POST['text']
210 if Node.isSpam(request.POST['text'], data):
211 raise SpamNotAllowedException("answer")
213 answer = AnswerAction(user=request.user).save(dict(question=question, **form.cleaned_data)).node
214 return HttpResponseRedirect(answer.get_absolute_url())
216 request.session['temp_node_data'] = request.POST
217 request.session['temp_node_type'] = 'answer'
218 request.session['temp_question_id'] = id
219 return HttpResponseRedirect(reverse('auth_action_signin', kwargs={'action': 'newquestion'}))
221 return HttpResponseRedirect(question.get_absolute_url())