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