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