]> git.openstreetmap.org Git - osqa.git/blob - forum/views/readers.py
Fixing bug 482 in a way we escape all passed from URL parameters.
[osqa.git] / forum / views / readers.py
1 # encoding:utf-8
2 import datetime
3 import logging
4 from urllib import unquote
5 from forum import settings as django_settings
6 from django.shortcuts import render_to_response, get_object_or_404
7 from django.http import HttpResponseRedirect, HttpResponse, Http404, HttpResponsePermanentRedirect
8 from django.core.paginator import Paginator, EmptyPage, InvalidPage
9 from django.template import RequestContext
10 from django import template
11 from django.utils.html import *
12 from django.utils import simplejson
13 from django.db.models import Q, Count
14 from django.utils.translation import ugettext as _
15 from django.template.defaultfilters import slugify
16 from django.core.urlresolvers import reverse
17 from django.utils.datastructures import SortedDict
18 from django.views.decorators.cache import cache_page
19 from django.utils.http import urlquote  as django_urlquote
20 from django.template.defaultfilters import slugify
21 from django.utils.safestring import mark_safe
22
23 from forum.utils.html import sanitize_html, hyperlink
24 from forum.utils.diff import textDiff as htmldiff
25 from forum.utils import pagination
26 from forum.forms import *
27 from forum.models import *
28 from forum.forms import get_next_url
29 from forum.actions import QuestionViewAction
30 from forum.http_responses import HttpResponseUnauthorized
31 from forum.feed import RssQuestionFeed, RssAnswerFeed
32 from forum.utils.pagination import generate_uri
33 import decorators
34
35 class HottestQuestionsSort(pagination.SortBase):
36     def apply(self, questions):
37         return questions.annotate(new_child_count=Count('all_children')).filter(
38                 all_children__added_at__gt=datetime.datetime.now() - datetime.timedelta(days=1)).order_by('-new_child_count')
39
40
41 class QuestionListPaginatorContext(pagination.PaginatorContext):
42     def __init__(self, id='QUESTIONS_LIST', prefix='', default_pagesize=30):
43         super (QuestionListPaginatorContext, self).__init__(id, sort_methods=(
44             (_('active'), pagination.SimpleSort(_('active'), '-last_activity_at', _("Most <strong>recently updated</strong> questions"))),
45             (_('newest'), pagination.SimpleSort(_('newest'), '-added_at', _("most <strong>recently asked</strong> questions"))),
46             (_('hottest'), HottestQuestionsSort(_('hottest'), _("most <strong>active</strong> questions in the last 24 hours</strong>"))),
47             (_('mostvoted'), pagination.SimpleSort(_('most voted'), '-score', _("most <strong>voted</strong> questions"))),
48         ), pagesizes=(15, 30, 50), default_pagesize=default_pagesize, prefix=prefix)
49
50 class AnswerSort(pagination.SimpleSort):
51     def apply(self, answers):
52         if not settings.DISABLE_ACCEPTING_FEATURE:
53             return answers.order_by(*(['-marked'] + list(self._get_order_by())))
54         else:
55             return super(AnswerSort, self).apply(answers)
56
57 class AnswerPaginatorContext(pagination.PaginatorContext):
58     def __init__(self, id='ANSWER_LIST', prefix='', default_pagesize=10):
59         super (AnswerPaginatorContext, self).__init__(id, sort_methods=(
60             (_('oldest'), AnswerSort(_('oldest answers'), 'added_at', _("oldest answers will be shown first"))),
61             (_('newest'), AnswerSort(_('newest answers'), '-added_at', _("newest answers will be shown first"))),
62             (_('votes'), AnswerSort(_('popular answers'), ('-score', 'added_at'), _("most voted answers will be shown first"))),
63         ), default_sort=_('votes'), pagesizes=(5, 10, 20), default_pagesize=default_pagesize, prefix=prefix)
64
65 class TagPaginatorContext(pagination.PaginatorContext):
66     def __init__(self):
67         super (TagPaginatorContext, self).__init__('TAG_LIST', sort_methods=(
68             (_('name'), pagination.SimpleSort(_('by name'), 'name', _("sorted alphabetically"))),
69             (_('used'), pagination.SimpleSort(_('by popularity'), '-used_count', _("sorted by frequency of tag use"))),
70         ), default_sort=_('used'), pagesizes=(30, 60, 120))
71     
72
73 def feed(request):
74     return RssQuestionFeed(
75                 request,
76                 Question.objects.filter_state(deleted=False).order_by('-last_activity_at'),
77                 settings.APP_TITLE + _(' - ')+ _('latest questions'),
78                 settings.APP_DESCRIPTION)(request)
79
80 @decorators.render('index.html')
81 def index(request):
82     paginator_context = QuestionListPaginatorContext()
83     paginator_context.base_path = reverse('questions')
84     return question_list(request,
85                          Question.objects.all(),
86                          base_path=reverse('questions'),
87                          feed_url=reverse('latest_questions_feed'),
88                          paginator_context=paginator_context)
89
90 @decorators.render('questions.html', 'unanswered', _('unanswered'), weight=400)
91 def unanswered(request):
92     return question_list(request,
93                          Question.objects.exclude(id__in=Question.objects.filter(children__marked=True).distinct()),
94                          _('open questions without an accepted answer'),
95                          None,
96                          _("Unanswered Questions"))
97
98 @decorators.render('questions.html', 'questions', _('questions'), weight=0)
99 def questions(request):
100     return question_list(request, Question.objects.all(), _('questions'))
101
102 @decorators.render('questions.html')
103 def tag(request, tag):
104     return question_list(request,
105                          Question.objects.filter(tags__name=unquote(tag)),
106                          mark_safe(_('questions tagged <span class="tag">%(tag)s</span>') % {'tag': tag}),
107                          None,
108                          mark_safe(_('Questions Tagged With %(tag)s') % {'tag': tag}),
109                          False)
110
111 @decorators.render('questions.html', 'questions', tabbed=False)
112 def user_questions(request, mode, user, slug):
113     user = get_object_or_404(User, id=user)
114
115     if mode == _('asked-by'):
116         questions = Question.objects.filter(author=user)
117         description = _("Questions asked by %s")
118     elif mode == _('answered-by'):
119         questions = Question.objects.filter(children__author=user, children__node_type='answer').distinct()
120         description = _("Questions answered by %s")
121     elif mode == _('subscribed-by'):
122         if not (request.user.is_superuser or request.user == user):
123             return HttpResponseUnauthorized(request)
124         questions = user.subscriptions
125
126         if request.user == user:
127             description = _("Questions you subscribed %s")
128         else:
129             description = _("Questions subscribed by %s")
130     else:
131         raise Http404
132
133
134     return question_list(request, questions,
135                          mark_safe(description % hyperlink(user.get_profile_url(), user.username)),
136                          page_title=description % user.username)
137
138 def question_list(request, initial,
139                   list_description=_('questions'),
140                   base_path=None,
141                   page_title=_("All Questions"),
142                   allowIgnoreTags=True,
143                   feed_url=None,
144                   paginator_context=None):
145
146     questions = initial.filter_state(deleted=False)
147
148     if request.user.is_authenticated() and allowIgnoreTags:
149         questions = questions.filter(~Q(tags__id__in = request.user.marked_tags.filter(user_selections__reason = 'bad')))
150
151     if page_title is None:
152         page_title = _("Questions")
153
154     if request.GET.get('type', None) == 'rss':
155         questions = questions.order_by('-added_at')
156         return RssQuestionFeed(request, questions, page_title, list_description)(request)
157
158     keywords =  ""
159     if request.GET.get("q"):
160         keywords = request.GET.get("q").strip()
161
162     #answer_count = Answer.objects.filter_state(deleted=False).filter(parent__in=questions).count()
163     #answer_description = _("answers")
164
165     if not feed_url:
166         req_params = "&".join(generate_uri(request.GET, (_('page'), _('pagesize'), _('sort'))))
167         if req_params:
168             req_params = '&' + req_params
169
170         feed_url = mark_safe(escape(request.path + "?type=rss" + req_params))
171
172     return pagination.paginated(request, ('questions', paginator_context or QuestionListPaginatorContext()), {
173     "questions" : questions.distinct(),
174     "questions_count" : questions.count(),
175     "keywords" : keywords,
176     "list_description": list_description,
177     "base_path" : base_path,
178     "page_title" : page_title,
179     "tab" : "questions",
180     'feed_url': feed_url,
181     })
182
183
184 def search(request):
185     if request.method == "GET" and "q" in request.GET:
186         keywords = request.GET.get("q")
187         search_type = request.GET.get("t")
188
189         if not keywords:
190             return HttpResponseRedirect(reverse(index))
191         if search_type == 'tag':
192             return HttpResponseRedirect(reverse('tags') + '?q=%s' % urlquote(keywords.strip()))
193         elif search_type == "user":
194             return HttpResponseRedirect(reverse('users') + '?q=%s' % urlquote(keywords.strip()))
195         elif search_type == "question":
196             return question_search(request, keywords)
197     else:
198         return render_to_response("search.html", context_instance=RequestContext(request))
199
200 @decorators.render('questions.html')
201 def question_search(request, keywords):
202     can_rank, initial = Question.objects.search(keywords)
203
204     if can_rank:
205         paginator_context = QuestionListPaginatorContext()
206         paginator_context.sort_methods[_('ranking')] = pagination.SimpleSort(_('relevance'), '-ranking', _("most relevant questions"))
207         paginator_context.force_sort = _('ranking')
208     else:
209         paginator_context = None
210
211     return question_list(request, initial,
212                          _("questions matching '%(keywords)s'") % {'keywords': keywords},
213                          None,
214                          _("questions matching '%(keywords)s'") % {'keywords': keywords},
215                          paginator_context=paginator_context)
216
217
218 @decorators.render('tags.html', 'tags', _('tags'), weight=100)
219 def tags(request):
220     stag = ""
221     tags = Tag.active.all()
222
223     if request.method == "GET":
224         stag = request.GET.get("q", "").strip()
225         if stag:
226             tags = tags.filter(name__icontains=stag)
227
228     return pagination.paginated(request, ('tags', TagPaginatorContext()), {
229         "tags" : tags,
230         "stag" : stag,
231         "keywords" : stag
232     })
233
234 def update_question_view_times(request, question):
235     if not 'last_seen_in_question' in request.session:
236         request.session['last_seen_in_question'] = {}
237
238     last_seen = request.session['last_seen_in_question'].get(question.id, None)
239
240     if (not last_seen) or last_seen < question.last_activity_at:
241         QuestionViewAction(question, request.user, ip=request.META['REMOTE_ADDR']).save()
242         request.session['last_seen_in_question'][question.id] = datetime.datetime.now()
243
244     request.session['last_seen_in_question'][question.id] = datetime.datetime.now()
245
246 def match_question_slug(id, slug):
247     slug_words = slug.split('-')
248     qs = Question.objects.filter(title__istartswith=slug_words[0])
249
250     for q in qs:
251         if slug == urlquote(slugify(q.title)):
252             return q
253
254     return None
255
256 def answer_redirect(request, answer):
257     pc = AnswerPaginatorContext()
258
259     sort = pc.sort(request)
260
261     if sort == _('oldest'):
262         filter = Q(added_at__lt=answer.added_at)
263     elif sort == _('newest'):
264         filter = Q(added_at__gt=answer.added_at)
265     elif sort == _('votes'):
266         filter = Q(score__gt=answer.score) | Q(score=answer.score, added_at__lt=answer.added_at)
267     else:
268         raise Http404()
269
270     count = answer.question.answers.filter(Q(marked=True) | filter).count()
271     pagesize = pc.pagesize(request)
272
273     page = count / pagesize
274     
275     if count % pagesize:
276         page += 1
277         
278     if page == 0:
279         page = 1
280
281     return HttpResponsePermanentRedirect("%s?%s=%s#%s" % (
282         answer.question.get_absolute_url(), _('page'), page, answer.id))
283
284 @decorators.render("question.html", 'questions')
285 def question(request, id, slug='', answer=None):
286     try:
287         question = Question.objects.get(id=id)
288     except:
289         if slug:
290             question = match_question_slug(id, slug)
291             if question is not None:
292                 return HttpResponseRedirect(question.get_absolute_url())
293
294         raise Http404()
295
296     if question.nis.deleted and not request.user.can_view_deleted_post(question):
297         raise Http404
298
299     if request.GET.get('type', None) == 'rss':
300         return RssAnswerFeed(request, question, include_comments=request.GET.get('comments', None) == 'yes')(request)
301
302     if answer:
303         answer = get_object_or_404(Answer, id=answer)
304
305         if (question.nis.deleted and not request.user.can_view_deleted_post(question)) or answer.question != question:
306             raise Http404
307
308         if answer.marked:
309             return HttpResponsePermanentRedirect(question.get_absolute_url())
310
311         return answer_redirect(request, answer)
312
313     if settings.FORCE_SINGLE_URL and (slug != slugify(question.title)):
314         return HttpResponsePermanentRedirect(question.get_absolute_url())
315
316     if request.POST:
317         answer_form = AnswerForm(question, request.POST)
318     else:
319         answer_form = AnswerForm(question)
320
321     answers = request.user.get_visible_answers(question)
322
323     update_question_view_times(request, question)
324
325     if request.user.is_authenticated():
326         try:
327             subscription = QuestionSubscription.objects.get(question=question, user=request.user)
328         except:
329             subscription = False
330     else:
331         subscription = False
332
333     return pagination.paginated(request, ('answers', AnswerPaginatorContext()), {
334     "question" : question,
335     "answer" : answer_form,
336     "answers" : answers,
337     "similar_questions" : question.get_related_questions(),
338     "subscription": subscription,
339     })
340
341
342 REVISION_TEMPLATE = template.loader.get_template('node/revision.html')
343
344 def revisions(request, id):
345     post = get_object_or_404(Node, id=id).leaf
346     revisions = list(post.revisions.order_by('revised_at'))
347     rev_ctx = []
348
349     for i, revision in enumerate(revisions):
350         rev_ctx.append(dict(inst=revision, html=template.loader.get_template('node/revision.html').render(template.Context({
351         'title': revision.title,
352         'html': revision.html,
353         'tags': revision.tagname_list(),
354         }))))
355
356         if i > 0:
357             rev_ctx[i]['diff'] = mark_safe(htmldiff(rev_ctx[i-1]['html'], rev_ctx[i]['html']))
358         else:
359             rev_ctx[i]['diff'] = mark_safe(rev_ctx[i]['html'])
360
361         if not (revision.summary):
362             rev_ctx[i]['summary'] = _('Revision n. %(rev_number)d') % {'rev_number': revision.revision}
363         else:
364             rev_ctx[i]['summary'] = revision.summary
365
366     rev_ctx.reverse()
367
368     return render_to_response('revisions.html', {
369     'post': post,
370     'revisions': rev_ctx,
371     }, context_instance=RequestContext(request))
372
373
374