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