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.utils.http import urlquote
12 from django.db.models import Q, Count
13 from django.utils.translation import ugettext as _
14 from django.core.urlresolvers import reverse
15 from django.template.defaultfilters import slugify
16 from django.utils.safestring import mark_safe
18 from forum import settings as django_settings
19 from forum.utils.html import hyperlink
20 from forum.utils.diff import textDiff as htmldiff
21 from forum.utils import pagination
22 from forum.forms import *
23 from forum.models import *
24 from forum.actions import QuestionViewAction
25 from forum.http_responses import HttpResponseUnauthorized
26 from forum.feed import RssQuestionFeed, RssAnswerFeed
27 from forum.utils.pagination import generate_uri
31 class HottestQuestionsSort(pagination.SortBase):
32 def apply(self, questions):
33 return questions.extra(select={'new_child_count': '''
36 WHERE fn1.abs_parent_id = forum_node.id
37 AND fn1.id != forum_node.id
38 AND NOT(fn1.state_string LIKE '%%(deleted)%%')
41 select_params=[ (datetime.datetime.now() - datetime.timedelta(days=2))
42 .strftime('%Y-%m-%d')]
43 ).order_by('-new_child_count', 'last_activity_at')
45 class UnansweredQuestionsSort(pagination.SortBase):
46 def apply(self, questions):
47 return questions.extra(select={'answer_count': '''
50 WHERE fn1.abs_parent_id = forum_node.id
51 AND fn1.id != forum_node.id
52 AND fn1.node_type='answer'
53 AND NOT(fn1.state_string LIKE '%%(deleted)%%')'''
54 }).order_by('answer_count', 'last_activity_at')
56 class QuestionListPaginatorContext(pagination.PaginatorContext):
57 def __init__(self, id='QUESTIONS_LIST', prefix='', pagesizes=(15, 30, 50), default_pagesize=30):
58 super (QuestionListPaginatorContext, self).__init__(id, sort_methods=(
59 (_('active'), pagination.SimpleSort(_('active'), '-last_activity_at', _("Most <strong>recently updated</strong> questions"))),
60 (_('newest'), pagination.SimpleSort(_('newest'), '-added_at', _("most <strong>recently asked</strong> questions"))),
61 (_('hottest'), HottestQuestionsSort(_('hottest'), _("most <strong>active</strong> questions in the last 24 hours</strong>"))),
62 (_('mostvoted'), pagination.SimpleSort(_('most voted'), '-score', _("most <strong>voted</strong> questions"))),
63 (_('unanswered'), UnansweredQuestionsSort('unanswered', "questions with no answers")),
64 ), pagesizes=pagesizes, default_pagesize=default_pagesize, prefix=prefix)
66 class AnswerSort(pagination.SimpleSort):
67 def apply(self, answers):
68 if not settings.DISABLE_ACCEPTING_FEATURE:
69 return answers.order_by(*(['-marked'] + list(self._get_order_by())))
71 return super(AnswerSort, self).apply(answers)
73 class AnswerPaginatorContext(pagination.PaginatorContext):
74 def __init__(self, id='ANSWER_LIST', prefix='', default_pagesize=10):
75 super (AnswerPaginatorContext, self).__init__(id, sort_methods=(
76 (_('active'), AnswerSort(_('active answers'), '-last_activity_at', _("most recently updated answers/comments will be shown first"))),
77 (_('oldest'), AnswerSort(_('oldest answers'), 'added_at', _("oldest answers will be shown first"))),
78 (_('newest'), AnswerSort(_('newest answers'), '-added_at', _("newest answers will be shown first"))),
79 (_('votes'), AnswerSort(_('popular answers'), ('-score', 'added_at'), _("most voted answers will be shown first"))),
80 ), default_sort=_('votes'), pagesizes=(5, 10, 20), default_pagesize=default_pagesize, prefix=prefix)
82 class TagPaginatorContext(pagination.PaginatorContext):
84 super (TagPaginatorContext, self).__init__('TAG_LIST', sort_methods=(
85 (_('name'), pagination.SimpleSort(_('by name'), 'name', _("sorted alphabetically"))),
86 (_('used'), pagination.SimpleSort(_('by popularity'), '-used_count', _("sorted by frequency of tag use"))),
87 ), default_sort=_('used'), pagesizes=(30, 60, 120))
91 return RssQuestionFeed(
93 Question.objects.filter_state(deleted=False).order_by('-last_activity_at'),
94 settings.APP_TITLE + _(' - ')+ _('latest questions'),
95 settings.APP_DESCRIPTION)(request)
97 @decorators.render('index.html')
99 paginator_context = QuestionListPaginatorContext()
100 paginator_context.base_path = reverse('questions')
101 return question_list(request,
102 Question.objects.all(),
103 base_path=reverse('questions'),
104 feed_url=reverse('latest_questions_feed'),
105 paginator_context=paginator_context)
107 @decorators.render('questions.html', 'unanswered', _('unanswered'), weight=400)
108 def unanswered(request):
109 return question_list(request,
110 Question.objects.exclude(id__in=Question.objects.filter(children__marked=True).distinct()).exclude(marked=True),
111 _('open questions without an accepted answer'),
113 _("Unanswered Questions"))
115 @decorators.render('questions.html', 'questions', _('questions'), weight=0)
116 def questions(request):
117 return question_list(request,
118 Question.objects.all(),
121 @decorators.render('questions.html')
122 def tag(request, tag):
124 tag = Tag.active.get(name=unquote(tag))
125 except Tag.DoesNotExist:
128 # Getting the questions QuerySet
129 questions = Question.objects.filter(tags__id=tag.id)
131 if request.method == "GET":
132 user = request.GET.get('user', None)
136 questions = questions.filter(author=User.objects.get(username=user))
137 except User.DoesNotExist:
140 # The extra tag context we need to pass
145 # The context returned by the question_list function, contains info about the questions
146 question_context = question_list(request,
148 mark_safe(_(u'questions tagged <span class="tag">%(tag)s</span>') % {'tag': tag}),
150 mark_safe(_(u'Questions Tagged With %(tag)s') % {'tag': tag}),
153 # If the return data type is not a dict just return it
154 if not isinstance(question_context, dict):
155 return question_context
157 question_context = dict(question_context)
159 # Create the combined context
160 context = dict(question_context.items() + tag_context.items())
164 @decorators.render('questions.html', 'questions', tabbed=False)
165 def user_questions(request, mode, user, slug):
166 user = get_object_or_404(User, id=user)
168 if mode == _('asked-by'):
169 questions = Question.objects.filter(author=user)
170 description = _("Questions asked by %s")
171 elif mode == _('answered-by'):
172 questions = Question.objects.filter(children__author=user, children__node_type='answer').distinct()
173 description = _("Questions answered by %s")
174 elif mode == _('subscribed-by'):
175 if not (request.user.is_superuser or request.user == user):
176 return HttpResponseUnauthorized(request)
177 questions = user.subscriptions
179 if request.user == user:
180 description = _("Questions you subscribed %s")
182 description = _("Questions subscribed by %s")
187 return question_list(request, questions,
188 mark_safe(description % hyperlink(user.get_profile_url(), user.username)),
189 page_title=description % user.username)
191 def question_list(request, initial,
192 list_description=_('questions'),
194 page_title=_("All Questions"),
195 allowIgnoreTags=True,
197 paginator_context=None,
199 feed_sort=('-added_at',),
200 feed_req_params_exclude=(_('page'), _('pagesize'), _('sort')),
203 if show_summary is None:
204 show_summary = bool(settings.SHOW_SUMMARY_ON_QUESTIONS_LIST)
206 questions = initial.filter_state(deleted=False)
208 if request.user.is_authenticated() and allowIgnoreTags:
209 questions = questions.filter(~Q(tags__id__in = request.user.marked_tags.filter(user_selections__reason = 'bad')))
211 if page_title is None:
212 page_title = _("Questions")
214 if request.GET.get('type', None) == 'rss':
216 questions = questions.order_by(*feed_sort)
217 return RssQuestionFeed(request, questions, page_title, list_description)(request)
220 if request.GET.get("q"):
221 keywords = request.GET.get("q").strip()
223 #answer_count = Answer.objects.filter_state(deleted=False).filter(parent__in=questions).count()
224 #answer_description = _("answers")
227 req_params = generate_uri(request.GET, feed_req_params_exclude)
230 req_params = '&' + req_params
232 feed_url = request.path + "?type=rss" + req_params
235 'questions' : questions.distinct(),
236 'questions_count' : questions.count(),
237 'keywords' : keywords,
238 'list_description': list_description,
239 'base_path' : base_path,
240 'page_title' : page_title,
242 'feed_url': feed_url,
243 'show_summary' : show_summary,
245 context.update(extra_context)
247 return pagination.paginated(request,
248 ('questions', paginator_context or QuestionListPaginatorContext()), context)
252 if request.method == "GET" and "q" in request.GET:
253 keywords = request.GET.get("q")
254 search_type = request.GET.get("t")
257 return HttpResponseRedirect(reverse(index))
258 if search_type == 'tag':
259 return HttpResponseRedirect(reverse('tags') + '?q=%s' % urlquote(keywords.strip()))
260 elif search_type == "user":
261 return HttpResponseRedirect(reverse('users') + '?q=%s' % urlquote(keywords.strip()))
263 return question_search(request, keywords)
265 return render_to_response("search.html", context_instance=RequestContext(request))
267 @decorators.render('questions.html')
268 def question_search(request, keywords):
270 can_rank, initial = Question.objects.search(keywords)
275 if isinstance(can_rank, basestring):
276 sort_order = can_rank
279 paginator_context = QuestionListPaginatorContext()
280 paginator_context.sort_methods[_('ranking')] = pagination.SimpleSort(_('relevance'), sort_order, _("most relevant questions"))
281 paginator_context.force_sort = _('ranking')
283 paginator_context = None
285 feed_url = mark_safe(escape(request.path + "?type=rss&q=" + keywords))
287 return question_list(request, initial,
288 _("questions matching '%(keywords)s'") % {'keywords': keywords},
290 _("questions matching '%(keywords)s'") % {'keywords': keywords},
291 paginator_context=paginator_context,
292 feed_url=feed_url, feed_sort=rank_feed and (can_rank,) or '-added_at')
295 @decorators.render('tags.html', 'tags', _('tags'), weight=100)
298 tags = Tag.active.all()
300 if request.method == "GET":
301 stag = request.GET.get("q", "").strip()
303 tags = tags.filter(name__icontains=stag)
305 return pagination.paginated(request, ('tags', TagPaginatorContext()), {
311 def update_question_view_times(request, question):
312 last_seen_in_question = request.session.get('last_seen_in_question', {})
314 last_seen = last_seen_in_question.get(question.id, None)
316 if (not last_seen) or (last_seen < question.last_activity_at):
317 QuestionViewAction(question, request.user, ip=request.META['REMOTE_ADDR']).save()
318 last_seen_in_question[question.id] = datetime.datetime.now()
319 request.session['last_seen_in_question'] = last_seen_in_question
321 def match_question_slug(id, slug):
322 slug_words = slug.split('-')
323 qs = Question.objects.filter(title__istartswith=slug_words[0])
326 if slug == urlquote(slugify(q.title)):
331 def answer_redirect(request, answer):
332 pc = AnswerPaginatorContext()
334 sort = pc.sort(request)
336 if sort == _('oldest'):
337 filter = Q(added_at__lt=answer.added_at)
338 elif sort == _('newest'):
339 filter = Q(added_at__gt=answer.added_at)
340 elif sort == _('votes'):
341 filter = Q(score__gt=answer.score) | Q(score=answer.score, added_at__lt=answer.added_at)
345 count = answer.question.answers.filter(Q(marked=True) | filter).exclude(state_string="(deleted)").count()
346 pagesize = pc.pagesize(request)
348 page = count / pagesize
356 return HttpResponseRedirect("%s?%s=%s&focusedAnswerId=%s#%s" % (
357 answer.question.get_absolute_url(), _('page'), page, answer.id, answer.id))
359 @decorators.render("question.html", 'questions')
360 def question(request, id, slug='', answer=None):
362 question = Question.objects.get(id=id)
365 question = match_question_slug(id, slug)
366 if question is not None:
367 return HttpResponseRedirect(question.get_absolute_url())
371 if question.nis.deleted and not request.user.can_view_deleted_post(question):
374 if request.GET.get('type', None) == 'rss':
375 return RssAnswerFeed(request, question, include_comments=request.GET.get('comments', None) == 'yes')(request)
378 answer = get_object_or_404(Answer, id=answer)
380 if (question.nis.deleted and not request.user.can_view_deleted_post(question)) or answer.question != question:
384 return HttpResponsePermanentRedirect(question.get_absolute_url())
386 return answer_redirect(request, answer)
388 if settings.FORCE_SINGLE_URL and (slug != slugify(question.title)):
389 return HttpResponsePermanentRedirect(question.get_absolute_url())
392 answer_form = AnswerForm(request.POST, user=request.user)
394 answer_form = AnswerForm(user=request.user)
396 answers = request.user.get_visible_answers(question)
398 update_question_view_times(request, question)
400 if request.user.is_authenticated():
402 subscription = QuestionSubscription.objects.get(question=question, user=request.user)
408 focused_answer_id = int(request.GET.get("focusedAnswerId", None))
409 except TypeError, ValueError:
410 focused_answer_id = None
412 return pagination.paginated(request, ('answers', AnswerPaginatorContext()), {
413 "question" : question,
414 "answer" : answer_form,
416 "similar_questions" : question.get_related_questions(),
417 "subscription": subscription,
418 "embed_youtube_videos" : settings.EMBED_YOUTUBE_VIDEOS,
419 "focused_answer_id" : focused_answer_id
423 REVISION_TEMPLATE = template.loader.get_template('node/revision.html')
425 def revisions(request, id):
426 post = get_object_or_404(Node, id=id).leaf
427 revisions = list(post.revisions.order_by('revised_at'))
430 for i, revision in enumerate(revisions):
431 rev_ctx.append(dict(inst=revision, html=template.loader.get_template('node/revision.html').render(template.Context({
432 'title': revision.title,
433 'html': revision.html,
434 'tags': revision.tagname_list(),
438 rev_ctx[i]['diff'] = mark_safe(htmldiff(rev_ctx[i-1]['html'], rev_ctx[i]['html']))
440 rev_ctx[i]['diff'] = mark_safe(rev_ctx[i]['html'])
442 if not (revision.summary):
443 rev_ctx[i]['summary'] = _('Revision n. %(rev_number)d') % {'rev_number': revision.revision}
445 rev_ctx[i]['summary'] = revision.summary
449 return render_to_response('revisions.html', {
451 'revisions': rev_ctx,
452 }, context_instance=RequestContext(request))