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