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.annotate(new_child_count=Count('all_children')).filter(
34 all_children__added_at__gt=datetime.datetime.now() - datetime.timedelta(days=1)).order_by('-new_child_count')
37 class QuestionListPaginatorContext(pagination.PaginatorContext):
38 def __init__(self, id='QUESTIONS_LIST', prefix='', pagesizes=(15, 30, 50), default_pagesize=30):
39 super (QuestionListPaginatorContext, self).__init__(id, sort_methods=(
40 (_('active'), pagination.SimpleSort(_('active'), '-last_activity_at', _("Most <strong>recently updated</strong> questions"))),
41 (_('newest'), pagination.SimpleSort(_('newest'), '-added_at', _("most <strong>recently asked</strong> questions"))),
42 (_('hottest'), HottestQuestionsSort(_('hottest'), _("most <strong>active</strong> questions in the last 24 hours</strong>"))),
43 (_('mostvoted'), pagination.SimpleSort(_('most voted'), '-score', _("most <strong>voted</strong> questions"))),
44 ), pagesizes=pagesizes, default_pagesize=default_pagesize, prefix=prefix)
46 class AnswerSort(pagination.SimpleSort):
47 def apply(self, answers):
48 if not settings.DISABLE_ACCEPTING_FEATURE:
49 return answers.order_by(*(['-marked'] + list(self._get_order_by())))
51 return super(AnswerSort, self).apply(answers)
53 class AnswerPaginatorContext(pagination.PaginatorContext):
54 def __init__(self, id='ANSWER_LIST', prefix='', default_pagesize=10):
55 super (AnswerPaginatorContext, self).__init__(id, sort_methods=(
56 (_('oldest'), AnswerSort(_('oldest answers'), 'added_at', _("oldest answers will be shown first"))),
57 (_('newest'), AnswerSort(_('newest answers'), '-added_at', _("newest answers will be shown first"))),
58 (_('votes'), AnswerSort(_('popular answers'), ('-score', 'added_at'), _("most voted answers will be shown first"))),
59 ), default_sort=_('votes'), pagesizes=(5, 10, 20), default_pagesize=default_pagesize, prefix=prefix)
61 class TagPaginatorContext(pagination.PaginatorContext):
63 super (TagPaginatorContext, self).__init__('TAG_LIST', sort_methods=(
64 (_('name'), pagination.SimpleSort(_('by name'), 'name', _("sorted alphabetically"))),
65 (_('used'), pagination.SimpleSort(_('by popularity'), '-used_count', _("sorted by frequency of tag use"))),
66 ), default_sort=_('used'), pagesizes=(30, 60, 120))
70 return RssQuestionFeed(
72 Question.objects.filter_state(deleted=False).order_by('-last_activity_at'),
73 settings.APP_TITLE + _(' - ')+ _('latest questions'),
74 settings.APP_DESCRIPTION)(request)
76 @decorators.render('index.html')
78 paginator_context = QuestionListPaginatorContext()
79 paginator_context.base_path = reverse('questions')
80 return question_list(request,
81 Question.objects.all(),
82 base_path=reverse('questions'),
83 feed_url=reverse('latest_questions_feed'),
84 paginator_context=paginator_context)
86 @decorators.render('questions.html', 'unanswered', _('unanswered'), weight=400)
87 def unanswered(request):
88 return question_list(request,
89 Question.objects.exclude(id__in=Question.objects.filter(children__marked=True).distinct()).exclude(marked=True),
90 _('open questions without an accepted answer'),
92 _("Unanswered Questions"))
94 @decorators.render('questions.html', 'questions', _('questions'), weight=0)
95 def questions(request):
96 return question_list(request,
97 Question.objects.all(),
100 @decorators.render('questions.html')
101 def tag(request, tag):
103 tag = Tag.active.get(name=unquote(tag))
104 except Tag.DoesNotExist:
107 # Getting the questions QuerySet
108 questions = Question.objects.filter(tags__id=tag.id)
110 if request.method == "GET":
111 user = request.GET.get('user', None)
115 questions = questions.filter(author=User.objects.get(username=user))
116 except User.DoesNotExist:
119 # The extra tag context we need to pass
124 # The context returned by the question_list function, contains info about the questions
125 question_context = question_list(request,
127 mark_safe(_(u'questions tagged <span class="tag">%(tag)s</span>') % {'tag': tag}),
129 mark_safe(_(u'Questions Tagged With %(tag)s') % {'tag': tag}),
132 # If the return data type is not a dict just return it
133 if not isinstance(question_context, dict):
134 return question_context
136 question_context = dict(question_context)
138 # Create the combined context
139 context = dict(question_context.items() + tag_context.items())
143 @decorators.render('questions.html', 'questions', tabbed=False)
144 def user_questions(request, mode, user, slug):
145 user = get_object_or_404(User, id=user)
147 if mode == _('asked-by'):
148 questions = Question.objects.filter(author=user)
149 description = _("Questions asked by %s")
150 elif mode == _('answered-by'):
151 questions = Question.objects.filter(children__author=user, children__node_type='answer').distinct()
152 description = _("Questions answered by %s")
153 elif mode == _('subscribed-by'):
154 if not (request.user.is_superuser or request.user == user):
155 return HttpResponseUnauthorized(request)
156 questions = user.subscriptions
158 if request.user == user:
159 description = _("Questions you subscribed %s")
161 description = _("Questions subscribed by %s")
166 return question_list(request, questions,
167 mark_safe(description % hyperlink(user.get_profile_url(), user.username)),
168 page_title=description % user.username)
170 def question_list(request, initial,
171 list_description=_('questions'),
173 page_title=_("All Questions"),
174 allowIgnoreTags=True,
176 paginator_context=None,
178 feed_sort=('-added_at',),
179 feed_req_params_exclude=(_('page'), _('pagesize'), _('sort')),
182 if show_summary is None:
183 show_summary = bool(settings.SHOW_SUMMARY_ON_QUESTIONS_LIST)
185 questions = initial.filter_state(deleted=False)
187 if request.user.is_authenticated() and allowIgnoreTags:
188 questions = questions.filter(~Q(tags__id__in = request.user.marked_tags.filter(user_selections__reason = 'bad')))
190 if page_title is None:
191 page_title = _("Questions")
193 if request.GET.get('type', None) == 'rss':
195 questions = questions.order_by(*feed_sort)
196 return RssQuestionFeed(request, questions, page_title, list_description)(request)
199 if request.GET.get("q"):
200 keywords = request.GET.get("q").strip()
202 #answer_count = Answer.objects.filter_state(deleted=False).filter(parent__in=questions).count()
203 #answer_description = _("answers")
206 req_params = generate_uri(request.GET, feed_req_params_exclude)
209 req_params = '&' + req_params
211 feed_url = request.path + "?type=rss" + req_params
214 'questions' : questions.distinct(),
215 'questions_count' : questions.count(),
216 'keywords' : keywords,
217 'list_description': list_description,
218 'base_path' : base_path,
219 'page_title' : page_title,
221 'feed_url': feed_url,
222 'show_summary' : show_summary,
224 context.update(extra_context)
226 return pagination.paginated(request,
227 ('questions', paginator_context or QuestionListPaginatorContext()), context)
231 if request.method == "GET" and "q" in request.GET:
232 keywords = request.GET.get("q")
233 search_type = request.GET.get("t")
236 return HttpResponseRedirect(reverse(index))
237 if search_type == 'tag':
238 return HttpResponseRedirect(reverse('tags') + '?q=%s' % urlquote(keywords.strip()))
239 elif search_type == "user":
240 return HttpResponseRedirect(reverse('users') + '?q=%s' % urlquote(keywords.strip()))
242 return question_search(request, keywords)
244 return render_to_response("search.html", context_instance=RequestContext(request))
246 @decorators.render('questions.html')
247 def question_search(request, keywords):
249 can_rank, initial = Question.objects.search(keywords)
254 if isinstance(can_rank, basestring):
255 sort_order = can_rank
258 paginator_context = QuestionListPaginatorContext()
259 paginator_context.sort_methods[_('ranking')] = pagination.SimpleSort(_('relevance'), sort_order, _("most relevant questions"))
260 paginator_context.force_sort = _('ranking')
262 paginator_context = None
264 feed_url = mark_safe(escape(request.path + "?type=rss&q=" + keywords))
266 return question_list(request, initial,
267 _("questions matching '%(keywords)s'") % {'keywords': keywords},
269 _("questions matching '%(keywords)s'") % {'keywords': keywords},
270 paginator_context=paginator_context,
271 feed_url=feed_url, feed_sort=rank_feed and (can_rank,) or '-added_at')
274 @decorators.render('tags.html', 'tags', _('tags'), weight=100)
277 tags = Tag.active.all()
279 if request.method == "GET":
280 stag = request.GET.get("q", "").strip()
282 tags = tags.filter(name__icontains=stag)
284 return pagination.paginated(request, ('tags', TagPaginatorContext()), {
290 def update_question_view_times(request, question):
291 last_seen_in_question = request.session.get('last_seen_in_question', {})
293 last_seen = last_seen_in_question.get(question.id, None)
295 if (not last_seen) or (last_seen < question.last_activity_at):
296 QuestionViewAction(question, request.user, ip=request.META['REMOTE_ADDR']).save()
297 last_seen_in_question[question.id] = datetime.datetime.now()
298 request.session['last_seen_in_question'] = last_seen_in_question
300 def match_question_slug(id, slug):
301 slug_words = slug.split('-')
302 qs = Question.objects.filter(title__istartswith=slug_words[0])
305 if slug == urlquote(slugify(q.title)):
310 def answer_redirect(request, answer):
311 pc = AnswerPaginatorContext()
313 sort = pc.sort(request)
315 if sort == _('oldest'):
316 filter = Q(added_at__lt=answer.added_at)
317 elif sort == _('newest'):
318 filter = Q(added_at__gt=answer.added_at)
319 elif sort == _('votes'):
320 filter = Q(score__gt=answer.score) | Q(score=answer.score, added_at__lt=answer.added_at)
324 count = answer.question.answers.filter(Q(marked=True) | filter).exclude(state_string="(deleted)").count()
325 pagesize = pc.pagesize(request)
327 page = count / pagesize
335 return HttpResponseRedirect("%s?%s=%s&focusedAnswerId=%s#%s" % (
336 answer.question.get_absolute_url(), _('page'), page, answer.id, answer.id))
338 @decorators.render("question.html", 'questions')
339 def question(request, id, slug='', answer=None):
341 question = Question.objects.get(id=id)
344 question = match_question_slug(id, slug)
345 if question is not None:
346 return HttpResponseRedirect(question.get_absolute_url())
350 if question.nis.deleted and not request.user.can_view_deleted_post(question):
353 if request.GET.get('type', None) == 'rss':
354 return RssAnswerFeed(request, question, include_comments=request.GET.get('comments', None) == 'yes')(request)
357 answer = get_object_or_404(Answer, id=answer)
359 if (question.nis.deleted and not request.user.can_view_deleted_post(question)) or answer.question != question:
363 return HttpResponsePermanentRedirect(question.get_absolute_url())
365 return answer_redirect(request, answer)
367 if settings.FORCE_SINGLE_URL and (slug != slugify(question.title)):
368 return HttpResponsePermanentRedirect(question.get_absolute_url())
371 answer_form = AnswerForm(request.POST, user=request.user)
373 answer_form = AnswerForm(user=request.user)
375 answers = request.user.get_visible_answers(question)
377 update_question_view_times(request, question)
379 if request.user.is_authenticated():
381 subscription = QuestionSubscription.objects.get(question=question, user=request.user)
387 focused_answer_id = int(request.GET.get("focusedAnswerId", None))
388 except TypeError, ValueError:
389 focused_answer_id = None
391 return pagination.paginated(request, ('answers', AnswerPaginatorContext()), {
392 "question" : question,
393 "answer" : answer_form,
395 "similar_questions" : question.get_related_questions(),
396 "subscription": subscription,
397 "embed_youtube_videos" : settings.EMBED_YOUTUBE_VIDEOS,
398 "focused_answer_id" : focused_answer_id
402 REVISION_TEMPLATE = template.loader.get_template('node/revision.html')
404 def revisions(request, id):
405 post = get_object_or_404(Node, id=id).leaf
406 revisions = list(post.revisions.order_by('revised_at'))
409 for i, revision in enumerate(revisions):
410 rev_ctx.append(dict(inst=revision, html=template.loader.get_template('node/revision.html').render(template.Context({
411 'title': revision.title,
412 'html': revision.html,
413 'tags': revision.tagname_list(),
417 rev_ctx[i]['diff'] = mark_safe(htmldiff(rev_ctx[i-1]['html'], rev_ctx[i]['html']))
419 rev_ctx[i]['diff'] = mark_safe(rev_ctx[i]['html'])
421 if not (revision.summary):
422 rev_ctx[i]['summary'] = _('Revision n. %(rev_number)d') % {'rev_number': revision.revision}
424 rev_ctx[i]['summary'] = revision.summary
428 return render_to_response('revisions.html', {
430 'revisions': rev_ctx,
431 }, context_instance=RequestContext(request))