]> git.openstreetmap.org Git - osqa.git/blob - forum/views/writers.py
304032c52d33f4f992a89c38b305ba15f0474e17
[osqa.git] / forum / views / writers.py
1 # encoding:utf-8
2 import os.path
3
4 import datetime
5
6 from django.core.urlresolvers import reverse
7 from django.core.files.storage import FileSystemStorage
8 from django.views.decorators.csrf import csrf_exempt
9 from django.shortcuts import render_to_response, get_object_or_404
10 from django.template import RequestContext
11 from django.http import HttpResponseRedirect, HttpResponse, Http404
12 from django.utils.html import *
13 from django.utils.translation import ugettext as _
14
15 from django.contrib import messages
16
17 from forum.actions import AskAction, AnswerAction, ReviseAction, RollbackAction, RetagAction, AnswerToQuestionAction, CommentToQuestionAction
18 from forum.forms import *
19 from forum.models import *
20 from forum.utils import html
21 from forum.http_responses import HttpResponseUnauthorized
22
23 from vars import PENDING_SUBMISSION_SESSION_ATTR
24
25 @csrf_exempt
26 def upload(request):#ajax upload file to a question or answer
27     class FileTypeNotAllow(Exception):
28         pass
29     class FileSizeNotAllow(Exception):
30         pass
31     class UploadPermissionNotAuthorized(Exception):
32         pass
33
34     xml_template = "<result><msg><![CDATA[%s]]></msg><error><![CDATA[%s]]></error><file_url>%s</file_url></result>"
35
36     try:
37         f = request.FILES['file-upload']
38         # check upload permission
39         if not request.user.can_upload_files():
40             raise UploadPermissionNotAuthorized()
41
42         # check file type
43         try:
44             file_name_suffix = os.path.splitext(f.name)[1].lower()
45         except KeyError:
46             raise FileTypeNotAllow()
47
48         if not file_name_suffix in ('.jpg', '.jpeg', '.gif', '.png', '.bmp', '.tiff', '.ico'):
49             raise FileTypeNotAllow()
50
51         storage = FileSystemStorage(str(settings.UPFILES_FOLDER), str(settings.UPFILES_ALIAS))
52         new_file_name = storage.save("_".join(f.name.split()), f)
53         # check file size
54         # byte
55         size = storage.size(new_file_name)
56
57         if size > float(settings.ALLOW_MAX_FILE_SIZE) * 1024 * 1024:
58             storage.delete(new_file_name)
59             raise FileSizeNotAllow()
60
61         result = xml_template % ('Good', '', str(settings.UPFILES_ALIAS) + new_file_name)
62     except UploadPermissionNotAuthorized:
63         result = xml_template % ('', _('uploading images is limited to users with >60 reputation points'), '')
64     except FileTypeNotAllow:
65         result = xml_template % ('', _("allowed file types are 'jpg', 'jpeg', 'gif', 'bmp', 'png', 'tiff'"), '')
66     except FileSizeNotAllow:
67         result = xml_template % ('', _("maximum upload file size is %sM") % settings.ALLOW_MAX_FILE_SIZE, '')
68     except Exception, e:
69         result = xml_template % ('', _('Error uploading file. Please contact the site administrator. Thank you. %s' % e), '')
70
71     return HttpResponse(result, mimetype="application/xml")
72
73 def ask(request):
74     form = None
75
76     if request.POST:
77         if request.session.pop('reviewing_pending_data', False):
78             form = AskForm(initial=request.POST, user=request.user)
79         elif "text" in request.POST:
80             form = AskForm(request.POST, user=request.user)
81             if form.is_valid():
82                 if request.user.is_authenticated() and request.user.email_valid_and_can_ask():
83                     ask_action = AskAction(user=request.user, ip=request.META['REMOTE_ADDR']).save(data=form.cleaned_data)
84                     question = ask_action.node
85
86                     if settings.WIKI_ON and request.POST.get('wiki', False):
87                         question.nstate.wiki = ask_action
88
89                     return HttpResponseRedirect(question.get_absolute_url())
90                 else:
91                     request.session[PENDING_SUBMISSION_SESSION_ATTR] = {
92                         'POST': request.POST,
93                         'data_name': _("question"),
94                         'type': 'ask',
95                         'submission_url': reverse('ask'),
96                         'time': datetime.datetime.now()
97                     }
98
99                     if request.user.is_authenticated():
100                         messages.info(request, _("Your question is pending until you %s.") % html.hyperlink(
101                             reverse('send_validation_email'), _("validate your email")
102                         ))
103                         return HttpResponseRedirect(reverse('index'))
104                     else:
105                         return HttpResponseRedirect(reverse('auth_signin'))
106         elif "go" in request.POST:
107             form = AskForm({'title': request.POST['q']}, user=request.user)
108             
109     if not form:
110         form = AskForm(user=request.user)
111
112     return render_to_response('ask.html', {
113         'form' : form,
114         'tab' : 'ask'
115         }, context_instance=RequestContext(request))
116
117 def convert_to_question(request, id):
118     user = request.user
119
120     node_type = request.GET.get('node_type', 'answer')
121     if node_type == 'comment':
122         node = get_object_or_404(Comment, id=id)
123         action_class = CommentToQuestionAction
124     else:
125         node = get_object_or_404(Answer, id=id)
126         action_class = AnswerToQuestionAction
127
128     if not user.can_convert_to_question(node):
129         return HttpResponseUnauthorized(request)
130
131     return _edit_question(request, node, template='node/convert_to_question.html', summary=_("Converted to question"),
132                            action_class =action_class, allow_rollback=False, url_getter=lambda a: Question.objects.get(id=a.id).get_absolute_url())
133
134 def edit_question(request, id):
135     question = get_object_or_404(Question, id=id)
136     if question.nis.deleted and not request.user.can_view_deleted_post(question):
137         raise Http404
138     if request.user.can_edit_post(question):
139         return _edit_question(request, question)
140     elif request.user.can_retag_questions():
141         return _retag_question(request, question)
142     else:
143         raise Http404
144
145 def _retag_question(request, question):
146     if request.method == 'POST':
147         form = RetagQuestionForm(question, request.POST)
148         if form.is_valid():
149             if form.has_changed():
150                 RetagAction(user=request.user, node=question, ip=request.META['REMOTE_ADDR']).save(data=dict(tagnames=form.cleaned_data['tags']))
151
152             return HttpResponseRedirect(question.get_absolute_url())
153     else:
154         form = RetagQuestionForm(question)
155     return render_to_response('question_retag.html', {
156         'question': question,
157         'form' : form,
158         #'tags' : _get_tags_cache_json(),
159     }, context_instance=RequestContext(request))
160
161 def _edit_question(request, question, template='question_edit.html', summary='', action_class=ReviseAction,
162                    allow_rollback=True, url_getter=lambda q: q.get_absolute_url(), additional_context=None):
163     if request.method == 'POST':
164         revision_form = RevisionForm(question, data=request.POST)
165         revision_form.is_valid()
166         revision = question.revisions.get(revision=revision_form.cleaned_data['revision'])
167
168         if 'select_revision' in request.POST:
169             form = EditQuestionForm(question, request.user, revision)
170         else:
171             form = EditQuestionForm(question, request.user, revision, data=request.POST)
172
173         if not 'select_revision' in request.POST and form.is_valid():
174             if form.has_changed():
175                 action = action_class(user=request.user, node=question, ip=request.META['REMOTE_ADDR']).save(data=form.cleaned_data)
176
177                 if settings.WIKI_ON:
178                     if request.POST.get('wiki', False) and not question.nis.wiki:
179                         question.nstate.wiki = action
180                     elif question.nis.wiki and (not request.POST.get('wiki', False)) and request.user.can_cancel_wiki(question):
181                         question.nstate.wiki = None
182             else:
183                 if not revision == question.active_revision:
184                     if allow_rollback:
185                         RollbackAction(user=request.user, node=question).save(data=dict(activate=revision))
186                     else:
187                         pass
188
189             return HttpResponseRedirect(url_getter(question))
190     else:
191         revision_form = RevisionForm(question)
192         form = EditQuestionForm(question, request.user, initial={'summary': summary})
193
194     context = {
195         'question': question,
196         'revision_form': revision_form,
197         'form' : form,
198     }
199
200     if not (additional_context is None):
201         context.update(additional_context)
202
203     return render_to_response(template, context, context_instance=RequestContext(request))
204
205
206 def edit_answer(request, id):
207     answer = get_object_or_404(Answer, id=id)
208     if answer.deleted and not request.user.can_view_deleted_post(answer):
209         raise Http404
210     elif not request.user.can_edit_post(answer):
211         raise Http404
212
213     if request.method == "POST":
214         revision_form = RevisionForm(answer, data=request.POST)
215         revision_form.is_valid()
216         revision = answer.revisions.get(revision=revision_form.cleaned_data['revision'])
217
218         if 'select_revision' in request.POST:
219             form = EditAnswerForm(answer, request.user, revision)
220         else:
221             form = EditAnswerForm(answer, request.user, revision, data=request.POST)
222
223         if not 'select_revision' in request.POST and form.is_valid():
224             if form.has_changed():
225                 action = ReviseAction(user=request.user, node=answer, ip=request.META['REMOTE_ADDR']).save(data=form.cleaned_data)
226
227                 if settings.WIKI_ON:
228                     if request.POST.get('wiki', False) and not answer.nis.wiki:
229                         answer.nstate.wiki = action
230                     elif answer.nis.wiki and (not request.POST.get('wiki', False)) and request.user.can_cancel_wiki(answer):
231                         answer.nstate.wiki = None
232             else:
233                 if not revision == answer.active_revision:
234                     RollbackAction(user=request.user, node=answer, ip=request.META['REMOTE_ADDR']).save(data=dict(activate=revision))
235
236             return HttpResponseRedirect(answer.get_absolute_url())
237
238     else:
239         revision_form = RevisionForm(answer)
240         form = EditAnswerForm(answer, request.user)
241     return render_to_response('answer_edit.html', {
242                               'answer': answer,
243                               'revision_form': revision_form,
244                               'form': form,
245                               }, context_instance=RequestContext(request))
246
247 def answer(request, id):
248     question = get_object_or_404(Question, id=id)
249
250     if request.POST:
251         form = AnswerForm(request.POST, request.user)
252
253         if request.session.pop('reviewing_pending_data', False) or not form.is_valid():
254             request.session['redirect_POST_data'] = request.POST
255             return HttpResponseRedirect(question.get_absolute_url() + '#fmanswer')
256
257         if request.user.is_authenticated() and request.user.email_valid_and_can_answer():
258             answer_action = AnswerAction(user=request.user, ip=request.META['REMOTE_ADDR']).save(dict(question=question, **form.cleaned_data))
259             answer = answer_action.node
260
261             if settings.WIKI_ON and request.POST.get('wiki', False):
262                 answer.nstate.wiki = answer_action
263
264             return HttpResponseRedirect(answer.get_absolute_url())
265         else:
266             request.session[PENDING_SUBMISSION_SESSION_ATTR] = {
267                 'POST': request.POST,
268                 'data_name': _("answer"),
269                 'type': 'answer',
270                 'submission_url': reverse('answer', kwargs={'id': id}),
271                 'time': datetime.datetime.now()
272             }
273
274             if request.user.is_authenticated():
275                 messages.info(request, _("Your answer is pending until you %s.") % html.hyperlink(
276                     reverse('send_validation_email'), _("validate your email")
277                 ))
278                 return HttpResponseRedirect(question.get_absolute_url())
279             else:
280                 return HttpResponseRedirect(reverse('auth_signin'))
281
282     return HttpResponseRedirect(question.get_absolute_url())
283
284
285 def manage_pending_data(request, action, forward=None):
286     pending_data = request.session.pop(PENDING_SUBMISSION_SESSION_ATTR, None)
287
288     if not pending_data:
289         raise Http404
290
291     if action == _("cancel"):
292         return HttpResponseRedirect(forward or request.META.get('HTTP_REFERER', '/'))
293     else:
294         if action == _("review"):
295             request.session['reviewing_pending_data'] = True
296
297         request.session['redirect_POST_data'] = pending_data['POST']
298         return HttpResponseRedirect(pending_data['submission_url'])
299
300