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