]> git.openstreetmap.org Git - osqa.git/blob - forum/views/writers.py
Removes the necessity of the "decoratable" decorator in modules and makes the api...
[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, 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.forms import get_next_url
20
21
22 def upload(request):#ajax upload file to a question or answer
23     class FileTypeNotAllow(Exception):
24         pass
25     class FileSizeNotAllow(Exception):
26         pass
27     class UploadPermissionNotAuthorized(Exception):
28         pass
29
30     xml_template = "<result><msg><![CDATA[%s]]></msg><error><![CDATA[%s]]></error><file_url>%s</file_url></result>"
31
32     try:
33         f = request.FILES['file-upload']
34         # check upload permission
35         if not request.user.can_upload_files():
36             raise UploadPermissionNotAuthorized()
37
38         # check file type
39         file_name_suffix = os.path.splitext(f.name)[1].lower()
40
41         if not file_name_suffix in ('.jpg', '.jpeg', '.gif', '.png', '.bmp', '.tiff', '.ico'):
42             raise FileTypeNotAllow()
43
44         storage = FileSystemStorage(str(settings.UPFILES_FOLDER), str(settings.UPFILES_ALIAS))
45         new_file_name = storage.save(f.name, f)
46         # check file size
47         # byte
48         size = storage.size(new_file_name)
49
50         if size > float(settings.ALLOW_MAX_FILE_SIZE) * 1024 * 1024:
51             storage.delete(new_file_name)
52             raise FileSizeNotAllow()
53
54         result = xml_template % ('Good', '', str(settings.UPFILES_ALIAS) + new_file_name)
55     except UploadPermissionNotAuthorized:
56         result = xml_template % ('', _('uploading images is limited to users with >60 reputation points'), '')
57     except FileTypeNotAllow:
58         result = xml_template % ('', _("allowed file types are 'jpg', 'jpeg', 'gif', 'bmp', 'png', 'tiff'"), '')
59     except FileSizeNotAllow:
60         result = xml_template % ('', _("maximum upload file size is %sM") % settings.ALLOW_MAX_FILE_SIZE, '')
61     except Exception, e:
62         result = xml_template % ('', _('Error uploading file. Please contact the site administrator. Thank you. %s' % e), '')
63
64     return HttpResponse(result, mimetype="application/xml")
65
66 def ask(request):
67     if request.POST and "text" in request.POST:
68         form = AskForm(request.POST, user=request.user)
69         if form.is_valid():
70             if request.user.is_authenticated():
71                 ask_action = AskAction(user=request.user, ip=request.META['REMOTE_ADDR']).save(data=form.cleaned_data)
72                 question = ask_action.node
73
74                 if settings.WIKI_ON and request.POST.get('wiki', False):
75                     question.nstate.wiki = ask_action
76
77                 return HttpResponseRedirect(question.get_absolute_url())
78             else:
79                 request.session['temp_node_data'] = request.POST
80                 request.session['temp_node_type'] = 'question'
81                 return HttpResponseRedirect(reverse('auth_action_signin', kwargs={'action': 'newquestion'}))
82     elif request.method == "POST" and "go" in request.POST:
83         form = AskForm({'title': request.POST['q']}, user=request.user)
84     else:
85         form = AskForm(user=request.user)
86
87     return render_to_response('ask.html', {
88         'form' : form,
89         'email_validation_faq_url':reverse('faq') + '#validate',
90         }, context_instance=RequestContext(request))
91
92 @login_required
93 def edit_question(request, id):
94     question = get_object_or_404(Question, id=id)
95     if question.nis.deleted and not request.user.can_view_deleted_post(question):
96         raise Http404
97     if request.user.can_edit_post(question):
98         return _edit_question(request, question)
99     elif request.user.can_retag_questions():
100         return _retag_question(request, question)
101     else:
102         raise Http404
103
104 def _retag_question(request, question):
105     if request.method == 'POST':
106         form = RetagQuestionForm(question, request.POST)
107         if form.is_valid():
108             if form.has_changed():
109                 RetagAction(user=request.user, node=question, ip=request.META['REMOTE_ADDR']).save(data=dict(tagnames=form.cleaned_data['tags']))
110
111             return HttpResponseRedirect(question.get_absolute_url())
112     else:
113         form = RetagQuestionForm(question)
114     return render_to_response('question_retag.html', {
115         'question': question,
116         'form' : form,
117         #'tags' : _get_tags_cache_json(),
118     }, context_instance=RequestContext(request))
119
120 def _edit_question(request, question):
121     if request.method == 'POST':
122         revision_form = RevisionForm(question, data=request.POST)
123         revision_form.is_valid()
124         revision = question.revisions.get(revision=revision_form.cleaned_data['revision'])
125
126         if 'select_revision' in request.POST:
127             form = EditQuestionForm(question, request.user, revision)
128         else:
129             form = EditQuestionForm(question, request.user, revision, data=request.POST)
130
131         if not 'select_revision' in request.POST and form.is_valid():
132             if form.has_changed():
133                 action = ReviseAction(user=request.user, node=question, ip=request.META['REMOTE_ADDR']).save(data=form.cleaned_data)
134
135                 if settings.WIKI_ON:
136                     if request.POST.get('wiki', False) and not question.nis.wiki:
137                         question.nstate.wiki = action
138                     elif question.nis.wiki and (not request.POST.get('wiki', False)) and request.user.can_cancel_wiki(question):
139                         question.nstate.wiki = None
140             else:
141                 if not revision == question.active_revision:
142                     RollbackAction(user=request.user, node=question).save(data=dict(activate=revision))
143
144             return HttpResponseRedirect(question.get_absolute_url())
145     else:
146         revision_form = RevisionForm(question)
147         form = EditQuestionForm(question, request.user)
148
149     return render_to_response('question_edit.html', {
150         'question': question,
151         'revision_form': revision_form,
152         'form' : form,
153         #'tags' : _get_tags_cache_json()
154     }, context_instance=RequestContext(request))
155
156 @login_required
157 def edit_answer(request, id):
158     answer = get_object_or_404(Answer, id=id)
159     if answer.deleted and not request.user.can_view_deleted_post(answer):
160         raise Http404
161     elif not request.user.can_edit_post(answer):
162         raise Http404
163
164     if request.method == "POST":
165         revision_form = RevisionForm(answer, data=request.POST)
166         revision_form.is_valid()
167         revision = answer.revisions.get(revision=revision_form.cleaned_data['revision'])
168
169         if 'select_revision' in request.POST:
170             form = EditAnswerForm(answer, request.user, revision)
171         else:
172             form = EditAnswerForm(answer, request.user, revision, data=request.POST)
173
174         if not 'select_revision' in request.POST and form.is_valid():
175             if form.has_changed():
176                 action = ReviseAction(user=request.user, node=answer, ip=request.META['REMOTE_ADDR']).save(data=form.cleaned_data)
177
178                 if settings.WIKI_ON:
179                     if request.POST.get('wiki', False) and not answer.nis.wiki:
180                         answer.nstate.wiki = action
181                     elif answer.nis.wiki and (not request.POST.get('wiki', False)) and request.user.can_cancel_wiki(answer):
182                         answer.nstate.wiki = None
183             else:
184                 if not revision == answer.active_revision:
185                     RollbackAction(user=request.user, node=answer, ip=request.META['REMOTE_ADDR']).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, request.user)
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                 answer_action = AnswerAction(user=request.user, ip=request.META['REMOTE_ADDR']).save(dict(question=question, **form.cleaned_data))
205                 answer = answer_action.node
206
207                 if settings.WIKI_ON and request.POST.get('wiki', False):
208                     answer.nstate.wiki = answer_action
209
210                 return HttpResponseRedirect(answer.get_absolute_url())
211             else:
212                 request.session['temp_node_data'] = request.POST
213                 request.session['temp_node_type'] = 'answer'
214                 request.session['temp_question_id'] = id
215                 return HttpResponseRedirect(reverse('auth_action_signin', kwargs={'action': 'newquestion'}))
216         else:
217             request.session['redirect_POST_data'] = request.POST
218             return HttpResponseRedirect(question.get_absolute_url() + '#fmanswer')
219
220     return HttpResponseRedirect(question.get_absolute_url())
221