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