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