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