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.forms import *
17 from forum.models import *
18 from forum.const import *
19 from forum.utils.forms import get_next_url
20 from forum.views.readers import _get_tags_cache_json
27 DEFAULT_PAGE_SIZE = 60
29 QUESTIONS_PAGE_SIZE = 10
31 ANSWERS_PAGE_SIZE = 10
33 def upload(request):#ajax upload file to a question or answer
34 class FileTypeNotAllow(Exception):
36 class FileSizeNotAllow(Exception):
38 class UploadPermissionNotAuthorized(Exception):
41 #<result><msg><![CDATA[%s]]></msg><error><![CDATA[%s]]></error><file_url>%s</file_url></result>
42 xml_template = "<result><msg><![CDATA[%s]]></msg><error><![CDATA[%s]]></error><file_url>%s</file_url></result>"
45 f = request.FILES['file-upload']
46 # check upload permission
47 if not request.user.can_upload_files():
48 raise UploadPermissionNotAuthorized()
51 file_name_suffix = os.path.splitext(f.name)[1].lower()
53 if not file_name_suffix in ('.jpg', '.jpeg', '.gif', '.png', '.bmp', '.tiff', '.ico'):
54 raise FileTypeNotAllow()
56 storage = FileSystemStorage(str(settings.UPFILES_FOLDER), str(settings.UPFILES_ALIAS))
57 new_file_name = storage.save(f.name, f)
60 size = storage.size(new_file_name)
62 if size > float(settings.ALLOW_MAX_FILE_SIZE) * 1024 * 1024:
63 storage.delete(new_file_name)
64 raise FileSizeNotAllow()
66 result = xml_template % ('Good', '', str(settings.UPFILES_ALIAS) + new_file_name)
67 except UploadPermissionNotAuthorized:
68 result = xml_template % ('', _('uploading images is limited to users with >60 reputation points'), '')
69 except FileTypeNotAllow:
70 result = xml_template % ('', _("allowed file types are 'jpg', 'jpeg', 'gif', 'bmp', 'png', 'tiff'"), '')
71 except FileSizeNotAllow:
72 result = xml_template % ('', _("maximum upload file size is %sM") % settings.ALLOW_MAX_FILE_SIZE, '')
74 result = xml_template % ('', _('Error uploading file. Please contact the site administrator. Thank you. %s' % e), '')
76 return HttpResponse(result, mimetype="application/xml")
79 def _create_post(request, post_cls, form, parent=None):
82 if parent is not None:
85 revision_data = dict(summary=_('Initial revision'), body=form.cleaned_data['text'])
87 if form.cleaned_data.get('title', None):
88 revision_data['title'] = strip_tags(form.cleaned_data['title'].strip())
90 if form.cleaned_data.get('tags', None):
91 revision_data['tagnames'] = form.cleaned_data['tags'].strip()
93 post.create_revision(request.user, **revision_data)
95 if form.cleaned_data['wiki']:
98 return HttpResponseRedirect(post.get_absolute_url())
103 if request.method == "POST" and "text" in request.POST:
104 form = AskForm(request.POST)
106 if request.user.is_authenticated():
107 return _create_post(request, Question, form)
109 return HttpResponseRedirect(reverse('auth_action_signin', kwargs={'action': 'newquestion'}))
110 elif request.method == "POST" and "go" in request.POST:
111 form = AskForm({'title': request.POST['q']})
115 tags = _get_tags_cache_json()
116 return render_to_response('ask.html', {
119 'email_validation_faq_url':reverse('faq') + '#validate',
120 }, context_instance=RequestContext(request))
123 def edit_question(request, id):
124 question = get_object_or_404(Question, id=id)
125 if question.deleted and not request.user.can_view_deleted_post(question):
127 if request.user.can_edit_post(question):
128 return _edit_question(request, question)
129 elif request.user.can_retag_questions():
130 return _retag_question(request, question)
134 def _retag_question(request, question):
135 if request.method == 'POST':
136 form = RetagQuestionForm(question, request.POST)
138 if form.has_changed():
139 active = question.active_revision
141 question.create_revision(
143 summary = _('Retag'),
144 title = active.title,
145 tagnames = form.cleaned_data['tags'],
149 return HttpResponseRedirect(question.get_absolute_url())
151 form = RetagQuestionForm(question)
152 return render_to_response('question_retag.html', {
153 'question': question,
155 'tags' : _get_tags_cache_json(),
156 }, context_instance=RequestContext(request))
158 def _edit_question(request, question):
159 if request.method == 'POST':
160 revision_form = RevisionForm(question, data=request.POST)
161 revision_form.is_valid()
162 revision = question.revisions.get(revision=revision_form.cleaned_data['revision'])
164 if 'select_revision' in request.POST:
165 form = EditQuestionForm(question, revision)
167 form = EditQuestionForm(question, revision, data=request.POST)
169 if not 'select_revision' in request.POST and form.is_valid():
170 if form.has_changed():
171 question.create_revision(
173 summary = form.cleaned_data['summary'],
174 title = strip_tags(form.cleaned_data['title'].strip()),
175 tagnames = form.cleaned_data['tags'].strip(),
176 body = form.cleaned_data['text'],
179 if form.cleaned_data.get('wiki', False):
183 if not revision == question.active_revision:
184 question.activate_revision(request.user, revision)
186 return HttpResponseRedirect(question.get_absolute_url())
188 revision_form = RevisionForm(question)
189 form = EditQuestionForm(question)
191 return render_to_response('question_edit.html', {
192 'question': question,
193 'revision_form': revision_form,
195 'tags' : _get_tags_cache_json()
196 }, context_instance=RequestContext(request))
199 def edit_answer(request, id):
200 answer = get_object_or_404(Answer, id=id)
201 if answer.deleted and not request.user.can_view_deleted_post(answer):
203 elif not request.user.can_edit_post(answer):
206 if request.method == "POST":
207 revision_form = RevisionForm(answer, data=request.POST)
208 revision_form.is_valid()
209 revision = answer.revisions.get(revision=revision_form.cleaned_data['revision'])
211 if 'select_revision' in request.POST:
212 form = EditAnswerForm(answer, revision)
214 form = EditAnswerForm(answer, revision, data=request.POST)
216 if not 'select_revision' in request.POST and form.is_valid():
217 if form.has_changed():
218 answer.create_revision(
220 summary = form.cleaned_data['summary'],
221 body = form.cleaned_data['text'],
224 if form.cleaned_data.get('wiki', False):
228 if not revision == answer.active_revision:
229 answer.activate_revision(request.user, revision)
231 return HttpResponseRedirect(answer.get_absolute_url())
234 revision_form = RevisionForm(answer)
235 form = EditAnswerForm(answer)
236 return render_to_response('answer_edit.html', {
238 'revision_form': revision_form,
240 }, context_instance=RequestContext(request))
242 def answer(request, id):
243 question = get_object_or_404(Question, id=id)
244 if request.method == "POST":
245 form = AnswerForm(question, request.POST)
247 if request.user.is_authenticated():
248 return _create_post(request, Answer, form, question)
250 return HttpResponseRedirect(reverse('auth_action_signin', kwargs={'action': 'newquestion'}))
252 return HttpResponseRedirect(question.get_absolute_url())