]> git.openstreetmap.org Git - osqa.git/blob - forum/views/writers.py
98b523e6f0eb85ca912b06a82a1a2d2220ada89d
[osqa.git] / forum / views / writers.py
1 # encoding:utf-8
2 import os.path
3 import time, datetime, random
4 import logging
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
15
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
22
23
24 def upload(request):#ajax upload file to a question or answer
25     class FileTypeNotAllow(Exception):
26         pass
27     class FileSizeNotAllow(Exception):
28         pass
29     class UploadPermissionNotAuthorized(Exception):
30         pass
31
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>"
34
35     try:
36         f = request.FILES['file-upload']
37         # check upload permission
38         if not request.user.can_upload_files():
39             raise UploadPermissionNotAuthorized()
40
41         # check file type
42         file_name_suffix = os.path.splitext(f.name)[1].lower()
43
44         if not file_name_suffix in ('.jpg', '.jpeg', '.gif', '.png', '.bmp', '.tiff', '.ico'):
45             raise FileTypeNotAllow()
46
47         storage = FileSystemStorage(str(settings.UPFILES_FOLDER), str(settings.UPFILES_ALIAS))
48         new_file_name = storage.save(f.name, f)
49         # check file size
50         # byte
51         size = storage.size(new_file_name)
52
53         if size > float(settings.ALLOW_MAX_FILE_SIZE) * 1024 * 1024:
54             storage.delete(new_file_name)
55             raise FileSizeNotAllow()
56
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, '')
64     except Exception, e:
65         result = xml_template % ('', _('Error uploading file. Please contact the site administrator. Thank you. %s' % e), '')
66
67     return HttpResponse(result, mimetype="application/xml")
68
69
70 def ask(request):
71     if request.POST and "text" in request.POST:
72         form = AskForm(request.POST)
73         if form.is_valid():
74             if request.user.is_authenticated():
75                 data = {
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']
82                 }
83                 if Node.isSpam(request.POST['text'], data):
84                     raise SpamNotAllowedException("question")
85
86                 question = AskAction(user=request.user).save(data=form.cleaned_data).node
87                 return HttpResponseRedirect(question.get_absolute_url())
88             else:
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']})
94     else:
95         form = AskForm()
96
97     #tags = _get_tags_cache_json()
98     return render_to_response('ask.html', {
99         'form' : form,
100         #'tags' : tags,
101         'email_validation_faq_url':reverse('faq') + '#validate',
102         }, context_instance=RequestContext(request))
103
104 @login_required
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):
108         raise Http404
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)
113     else:
114         raise Http404
115
116 def _retag_question(request, question):
117     if request.method == 'POST':
118         form = RetagQuestionForm(question, request.POST)
119         if form.is_valid():
120             if form.has_changed():
121                 RetagAction(user=request.user, node=question).save(data=dict(tagnames=form.cleaned_data['tags']))
122
123             return HttpResponseRedirect(question.get_absolute_url())
124     else:
125         form = RetagQuestionForm(question)
126     return render_to_response('question_retag.html', {
127         'question': question,
128         'form' : form,
129         #'tags' : _get_tags_cache_json(),
130     }, context_instance=RequestContext(request))
131
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'])
137
138         if 'select_revision' in request.POST:
139             form = EditQuestionForm(question, revision)
140         else:
141             form = EditQuestionForm(question, revision, data=request.POST)
142
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)
146             else:
147                 if not revision == question.active_revision:
148                     RollbackAction(user=request.user, node=question).save(data=dict(activate=revision))
149
150             return HttpResponseRedirect(question.get_absolute_url())
151     else:
152         revision_form = RevisionForm(question)
153         form = EditQuestionForm(question)
154
155     return render_to_response('question_edit.html', {
156         'question': question,
157         'revision_form': revision_form,
158         'form' : form,
159         #'tags' : _get_tags_cache_json()
160     }, context_instance=RequestContext(request))
161
162 @login_required
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):
166         raise Http404
167     elif not request.user.can_edit_post(answer):
168         raise Http404
169
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'])
174
175         if 'select_revision' in request.POST:
176             form = EditAnswerForm(answer, revision)
177         else:
178             form = EditAnswerForm(answer, revision, data=request.POST)
179
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)
183             else:
184                 if not revision == answer.active_revision:
185                     RollbackAction(user=request.user, node=answer).save(data=dict(activate=revision))
186
187             return HttpResponseRedirect(answer.get_absolute_url())
188
189     else:
190         revision_form = RevisionForm(answer)
191         form = EditAnswerForm(answer)
192     return render_to_response('answer_edit.html', {
193                               'answer': answer,
194                               'revision_form': revision_form,
195                               'form': form,
196                               }, context_instance=RequestContext(request))
197
198 def answer(request, id):
199     question = get_object_or_404(Question, id=id)
200     if request.POST:
201         form = AnswerForm(question, request.POST)
202         if form.is_valid():
203             if request.user.is_authenticated():
204                 data = {
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']
211                 }
212                 if Node.isSpam(request.POST['text'], data):
213                     raise SpamNotAllowedException("answer")
214
215                 answer = AnswerAction(user=request.user).save(dict(question=question, **form.cleaned_data)).node
216                 return HttpResponseRedirect(answer.get_absolute_url())
217             else:
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'}))
222
223     return HttpResponseRedirect(question.get_absolute_url())
224