]> git.openstreetmap.org Git - osqa.git/blob - forum/views/writers.py
Adds a user preferences page. Not much to see yet, only the preference to make sorts...
[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 from forum.utils import html
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 def ask(request):
68     form = None
69
70     if request.POST:
71         if request.session.pop('reviewing_pending_data', False):
72             form = AskForm(initial=request.POST, user=request.user)
73         elif "text" in request.POST:
74             form = AskForm(request.POST, user=request.user)
75             if form.is_valid():
76                 if request.user.is_authenticated() and request.user.email_valid_and_can_ask():
77                     ask_action = AskAction(user=request.user, ip=request.META['REMOTE_ADDR']).save(data=form.cleaned_data)
78                     question = ask_action.node
79
80                     if settings.WIKI_ON and request.POST.get('wiki', False):
81                         question.nstate.wiki = ask_action
82
83                     return HttpResponseRedirect(question.get_absolute_url())
84                 else:
85                     request.session['pending_submission_data'] = {
86                         'POST': request.POST,
87                         'data_name': _("question"),
88                         'type': 'ask',
89                         'submission_url': reverse('ask'),
90                         'time': datetime.datetime.now()
91                     }
92
93                     if request.user.is_authenticated():
94                         request.user.message_set.create(message=_("Your question is pending until you %s.") % html.hyperlink(
95                             reverse('send_validation_email'), _("validate your email")
96                         ))
97                         return HttpResponseRedirect(reverse('index'))
98                     else:
99                         return HttpResponseRedirect(reverse('auth_signin'))
100         elif "go" in request.POST:
101             form = AskForm({'title': request.POST['q']}, user=request.user)
102             
103     if not form:
104         form = AskForm(user=request.user)
105
106     return render_to_response('ask.html', {
107         'form' : form,
108         }, context_instance=RequestContext(request))
109
110 @login_required
111 def edit_question(request, id):
112     question = get_object_or_404(Question, id=id)
113     if question.nis.deleted and not request.user.can_view_deleted_post(question):
114         raise Http404
115     if request.user.can_edit_post(question):
116         return _edit_question(request, question)
117     elif request.user.can_retag_questions():
118         return _retag_question(request, question)
119     else:
120         raise Http404
121
122 def _retag_question(request, question):
123     if request.method == 'POST':
124         form = RetagQuestionForm(question, request.POST)
125         if form.is_valid():
126             if form.has_changed():
127                 RetagAction(user=request.user, node=question, ip=request.META['REMOTE_ADDR']).save(data=dict(tagnames=form.cleaned_data['tags']))
128
129             return HttpResponseRedirect(question.get_absolute_url())
130     else:
131         form = RetagQuestionForm(question)
132     return render_to_response('question_retag.html', {
133         'question': question,
134         'form' : form,
135         #'tags' : _get_tags_cache_json(),
136     }, context_instance=RequestContext(request))
137
138 def _edit_question(request, question):
139     if request.method == 'POST':
140         revision_form = RevisionForm(question, data=request.POST)
141         revision_form.is_valid()
142         revision = question.revisions.get(revision=revision_form.cleaned_data['revision'])
143
144         if 'select_revision' in request.POST:
145             form = EditQuestionForm(question, request.user, revision)
146         else:
147             form = EditQuestionForm(question, request.user, revision, data=request.POST)
148
149         if not 'select_revision' in request.POST and form.is_valid():
150             if form.has_changed():
151                 action = ReviseAction(user=request.user, node=question, ip=request.META['REMOTE_ADDR']).save(data=form.cleaned_data)
152
153                 if settings.WIKI_ON:
154                     if request.POST.get('wiki', False) and not question.nis.wiki:
155                         question.nstate.wiki = action
156                     elif question.nis.wiki and (not request.POST.get('wiki', False)) and request.user.can_cancel_wiki(question):
157                         question.nstate.wiki = None
158             else:
159                 if not revision == question.active_revision:
160                     RollbackAction(user=request.user, node=question).save(data=dict(activate=revision))
161
162             return HttpResponseRedirect(question.get_absolute_url())
163     else:
164         revision_form = RevisionForm(question)
165         form = EditQuestionForm(question, request.user)
166
167     return render_to_response('question_edit.html', {
168         'question': question,
169         'revision_form': revision_form,
170         'form' : form,
171         #'tags' : _get_tags_cache_json()
172     }, context_instance=RequestContext(request))
173
174 @login_required
175 def edit_answer(request, id):
176     answer = get_object_or_404(Answer, id=id)
177     if answer.deleted and not request.user.can_view_deleted_post(answer):
178         raise Http404
179     elif not request.user.can_edit_post(answer):
180         raise Http404
181
182     if request.method == "POST":
183         revision_form = RevisionForm(answer, data=request.POST)
184         revision_form.is_valid()
185         revision = answer.revisions.get(revision=revision_form.cleaned_data['revision'])
186
187         if 'select_revision' in request.POST:
188             form = EditAnswerForm(answer, request.user, revision)
189         else:
190             form = EditAnswerForm(answer, request.user, revision, data=request.POST)
191
192         if not 'select_revision' in request.POST and form.is_valid():
193             if form.has_changed():
194                 action = ReviseAction(user=request.user, node=answer, ip=request.META['REMOTE_ADDR']).save(data=form.cleaned_data)
195
196                 if settings.WIKI_ON:
197                     if request.POST.get('wiki', False) and not answer.nis.wiki:
198                         answer.nstate.wiki = action
199                     elif answer.nis.wiki and (not request.POST.get('wiki', False)) and request.user.can_cancel_wiki(answer):
200                         answer.nstate.wiki = None
201             else:
202                 if not revision == answer.active_revision:
203                     RollbackAction(user=request.user, node=answer, ip=request.META['REMOTE_ADDR']).save(data=dict(activate=revision))
204
205             return HttpResponseRedirect(answer.get_absolute_url())
206
207     else:
208         revision_form = RevisionForm(answer)
209         form = EditAnswerForm(answer, request.user)
210     return render_to_response('answer_edit.html', {
211                               'answer': answer,
212                               'revision_form': revision_form,
213                               'form': form,
214                               }, context_instance=RequestContext(request))
215
216 def answer(request, id):
217     question = get_object_or_404(Question, id=id)
218
219     if request.POST:
220         form = AnswerForm(question, request.POST)
221
222         if request.session.pop('reviewing_pending_data', False) or not form.is_valid():
223             request.session['redirect_POST_data'] = request.POST
224             return HttpResponseRedirect(question.get_absolute_url() + '#fmanswer')
225
226         if request.user.is_authenticated() and request.user.email_valid_and_can_answer():
227             answer_action = AnswerAction(user=request.user, ip=request.META['REMOTE_ADDR']).save(dict(question=question, **form.cleaned_data))
228             answer = answer_action.node
229
230             if settings.WIKI_ON and request.POST.get('wiki', False):
231                 answer.nstate.wiki = answer_action
232
233             return HttpResponseRedirect(answer.get_absolute_url())
234         else:
235             request.session['pending_submission_data'] = {
236                 'POST': request.POST,
237                 'data_name': _("answer"),
238                 'type': 'answer',
239                 'submission_url': reverse('answer', kwargs={'id': id}),
240                 'time': datetime.datetime.now()
241             }
242
243             if request.user.is_authenticated():
244                 request.user.message_set.create(message=_("Your answer is pending until you %s.") % html.hyperlink(
245                     reverse('send_validation_email'), _("validate your email")
246                 ))
247                 return HttpResponseRedirect(question.get_absolute_url())
248             else:
249                 return HttpResponseRedirect(reverse('auth_signin'))
250
251     return HttpResponseRedirect(question.get_absolute_url())
252
253
254 def manage_pending_data(request, action, forward=None):
255     pending_data = request.session.pop('pending_submission_data', None)
256
257     if not pending_data:
258         raise Http404
259
260     if action == _("cancel"):
261         return HttpResponseRedirect(forward or request.META.get('HTTP_REFERER', '/'))
262     else:
263         if action == _("review"):
264             request.session['reviewing_pending_data'] = True
265
266         request.session['redirect_POST_data'] = pending_data['POST']
267         return HttpResponseRedirect(pending_data['submission_url'])
268
269