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