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