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.template import RequestContext
10 from django import template
11 from django.utils.html import *
12 from django.utils import simplejson
13 from django.db.models import Q, Count
14 from django.utils.translation import ugettext as _
15 from django.template.defaultfilters import slugify
16 from django.core.urlresolvers import reverse
17 from django.utils.datastructures import SortedDict
18 from django.views.decorators.cache import cache_page
19 from django.utils.http import urlquote as django_urlquote
20 from django.template.defaultfilters import slugify
21 from django.utils.safestring import mark_safe
23 from forum.utils.html import sanitize_html, hyperlink
24 from forum.utils.diff import textDiff as htmldiff
25 from forum.utils import pagination
26 from forum.forms import *
27 from forum.models import *
28 from forum.forms import get_next_url
29 from forum.actions import QuestionViewAction
30 from forum.http_responses import HttpResponseUnauthorized
31 from forum.feed import RssQuestionFeed, RssAnswerFeed
32 from forum.utils.pagination import generate_uri
35 class HottestQuestionsSort(pagination.SortBase):
36 def apply(self, questions):
37 return questions.annotate(new_child_count=Count('all_children')).filter(
38 all_children__added_at__gt=datetime.datetime.now() - datetime.timedelta(days=1)).order_by('-new_child_count')
41 class QuestionListPaginatorContext(pagination.PaginatorContext):
42 def __init__(self, id='QUESTIONS_LIST', prefix='', default_pagesize=30):
43 super (QuestionListPaginatorContext, self).__init__(id, sort_methods=(
44 (_('active'), pagination.SimpleSort(_('active'), '-last_activity_at', _("Most <strong>recently updated</strong> questions"))),
45 (_('newest'), pagination.SimpleSort(_('newest'), '-added_at', _("most <strong>recently asked</strong> questions"))),
46 (_('hottest'), HottestQuestionsSort(_('hottest'), _("most <strong>active</strong> questions in the last 24 hours</strong>"))),
47 (_('mostvoted'), pagination.SimpleSort(_('most voted'), '-score', _("most <strong>voted</strong> questions"))),
48 ), pagesizes=(15, 30, 50), default_pagesize=default_pagesize, prefix=prefix)
50 class AnswerSort(pagination.SimpleSort):
51 def apply(self, answers):
52 if not settings.DISABLE_ACCEPTING_FEATURE:
53 return answers.order_by(*(['-marked'] + list(self._get_order_by())))
55 return super(AnswerSort, self).apply(answers)
57 class AnswerPaginatorContext(pagination.PaginatorContext):
58 def __init__(self, id='ANSWER_LIST', prefix='', default_pagesize=10):
59 super (AnswerPaginatorContext, self).__init__(id, sort_methods=(
60 (_('oldest'), AnswerSort(_('oldest answers'), 'added_at', _("oldest answers will be shown first"))),
61 (_('newest'), AnswerSort(_('newest answers'), '-added_at', _("newest answers will be shown first"))),
62 (_('votes'), AnswerSort(_('popular answers'), ('-score', 'added_at'), _("most voted answers will be shown first"))),
63 ), default_sort=_('votes'), pagesizes=(5, 10, 20), default_pagesize=default_pagesize, prefix=prefix)
65 class TagPaginatorContext(pagination.PaginatorContext):
67 super (TagPaginatorContext, self).__init__('TAG_LIST', sort_methods=(
68 (_('name'), pagination.SimpleSort(_('by name'), 'name', _("sorted alphabetically"))),
69 (_('used'), pagination.SimpleSort(_('by popularity'), '-used_count', _("sorted by frequency of tag use"))),
70 ), default_sort=_('used'), pagesizes=(30, 60, 120))
74 return RssQuestionFeed(
76 Question.objects.filter_state(deleted=False).order_by('-last_activity_at'),
77 settings.APP_TITLE + _(' - ')+ _('latest questions'),
78 settings.APP_DESCRIPTION)(request)
80 @decorators.render('index.html')
82 paginator_context = QuestionListPaginatorContext()
83 paginator_context.base_path = reverse('questions')
84 return question_list(request,
85 Question.objects.all(),
86 base_path=reverse('questions'),
87 feed_url=reverse('latest_questions_feed'),
88 paginator_context=paginator_context)
90 @decorators.render('questions.html', 'unanswered', _('unanswered'), weight=400)
91 def unanswered(request):
92 return question_list(request,
93 Question.objects.exclude(id__in=Question.objects.filter(children__marked=True).distinct()),
94 _('open questions without an accepted answer'),
96 _("Unanswered Questions"))
98 @decorators.render('questions.html', 'questions', _('questions'), weight=0)
99 def questions(request):
100 return question_list(request, Question.objects.all(), _('questions'))
102 @decorators.render('questions.html')
103 def tag(request, tag):
105 tag = Tag.active.get(name=unquote(tag))
106 except Tag.DoesNotExist:
109 return question_list(request,
110 Question.objects.filter(tags=tag),
111 mark_safe(_('questions tagged <span class="tag">%(tag)s</span>') % {'tag': tag}),
113 mark_safe(_('Questions Tagged With %(tag)s') % {'tag': tag}),
116 @decorators.render('questions.html', 'questions', tabbed=False)
117 def user_questions(request, mode, user, slug):
118 user = get_object_or_404(User, id=user)
120 if mode == _('asked-by'):
121 questions = Question.objects.filter(author=user)
122 description = _("Questions asked by %s")
123 elif mode == _('answered-by'):
124 questions = Question.objects.filter(children__author=user, children__node_type='answer').distinct()
125 description = _("Questions answered by %s")
126 elif mode == _('subscribed-by'):
127 if not (request.user.is_superuser or request.user == user):
128 return HttpResponseUnauthorized(request)
129 questions = user.subscriptions
131 if request.user == user:
132 description = _("Questions you subscribed %s")
134 description = _("Questions subscribed by %s")
139 return question_list(request, questions,
140 mark_safe(description % hyperlink(user.get_profile_url(), user.username)),
141 page_title=description % user.username)
143 def question_list(request, initial,
144 list_description=_('questions'),
146 page_title=_("All Questions"),
147 allowIgnoreTags=True,
149 paginator_context=None):
151 questions = initial.filter_state(deleted=False)
153 if request.user.is_authenticated() and allowIgnoreTags:
154 questions = questions.filter(~Q(tags__id__in = request.user.marked_tags.filter(user_selections__reason = 'bad')))
156 if page_title is None:
157 page_title = _("Questions")
159 if request.GET.get('type', None) == 'rss':
160 questions = questions.order_by('-added_at')
161 return RssQuestionFeed(request, questions, page_title, list_description)(request)
164 if request.GET.get("q"):
165 keywords = request.GET.get("q").strip()
167 #answer_count = Answer.objects.filter_state(deleted=False).filter(parent__in=questions).count()
168 #answer_description = _("answers")
171 req_params = "&".join(generate_uri(request.GET, (_('page'), _('pagesize'), _('sort'))))
173 req_params = '&' + req_params
175 feed_url = mark_safe(escape(request.path + "?type=rss" + req_params))
177 return pagination.paginated(request, ('questions', paginator_context or QuestionListPaginatorContext()), {
178 "questions" : questions.distinct(),
179 "questions_count" : questions.count(),
180 "keywords" : keywords,
181 "list_description": list_description,
182 "base_path" : base_path,
183 "page_title" : page_title,
185 'feed_url': feed_url,
190 if request.method == "GET" and "q" in request.GET:
191 keywords = request.GET.get("q")
192 search_type = request.GET.get("t")
195 return HttpResponseRedirect(reverse(index))
196 if search_type == 'tag':
197 return HttpResponseRedirect(reverse('tags') + '?q=%s' % urlquote(keywords.strip()))
198 elif search_type == "user":
199 return HttpResponseRedirect(reverse('users') + '?q=%s' % urlquote(keywords.strip()))
201 return question_search(request, keywords)
203 return render_to_response("search.html", context_instance=RequestContext(request))
205 @decorators.render('questions.html')
206 def question_search(request, keywords):
207 can_rank, initial = Question.objects.search(keywords)
210 paginator_context = QuestionListPaginatorContext()
211 paginator_context.sort_methods[_('ranking')] = pagination.SimpleSort(_('relevance'), '-ranking', _("most relevant questions"))
212 paginator_context.force_sort = _('ranking')
214 paginator_context = None
216 feed_url = mark_safe(escape(request.path + "?type=rss&q=" + keywords))
218 return question_list(request, initial,
219 _("questions matching '%(keywords)s'") % {'keywords': keywords},
221 _("questions matching '%(keywords)s'") % {'keywords': keywords},
222 paginator_context=paginator_context,
226 @decorators.render('tags.html', 'tags', _('tags'), weight=100)
229 tags = Tag.active.all()
231 if request.method == "GET":
232 stag = request.GET.get("q", "").strip()
234 tags = tags.filter(name__icontains=stag)
236 return pagination.paginated(request, ('tags', TagPaginatorContext()), {
242 def update_question_view_times(request, question):
243 last_seen_in_question = request.session.get('last_seen_in_question', {})
245 last_seen = last_seen_in_question.get(question.id, None)
247 if (not last_seen) or (last_seen < question.last_activity_at):
248 QuestionViewAction(question, request.user, ip=request.META['REMOTE_ADDR']).save()
249 last_seen_in_question[question.id] = datetime.datetime.now()
250 request.session['last_seen_in_question'] = last_seen_in_question
252 def match_question_slug(id, slug):
253 slug_words = slug.split('-')
254 qs = Question.objects.filter(title__istartswith=slug_words[0])
257 if slug == urlquote(slugify(q.title)):
262 def answer_redirect(request, answer):
263 pc = AnswerPaginatorContext()
265 sort = pc.sort(request)
267 if sort == _('oldest'):
268 filter = Q(added_at__lt=answer.added_at)
269 elif sort == _('newest'):
270 filter = Q(added_at__gt=answer.added_at)
271 elif sort == _('votes'):
272 filter = Q(score__gt=answer.score) | Q(score=answer.score, added_at__lt=answer.added_at)
276 count = answer.question.answers.filter(Q(marked=True) | filter).exclude(state_string="(deleted)").count()
277 pagesize = pc.pagesize(request)
279 page = count / pagesize
287 return HttpResponsePermanentRedirect("%s?%s=%s#%s" % (
288 answer.question.get_absolute_url(), _('page'), page, answer.id))
290 @decorators.render("question.html", 'questions')
291 def question(request, id, slug='', answer=None):
293 question = Question.objects.get(id=id)
296 question = match_question_slug(id, slug)
297 if question is not None:
298 return HttpResponseRedirect(question.get_absolute_url())
302 if question.nis.deleted and not request.user.can_view_deleted_post(question):
305 if request.GET.get('type', None) == 'rss':
306 return RssAnswerFeed(request, question, include_comments=request.GET.get('comments', None) == 'yes')(request)
309 answer = get_object_or_404(Answer, id=answer)
311 if (question.nis.deleted and not request.user.can_view_deleted_post(question)) or answer.question != question:
315 return HttpResponsePermanentRedirect(question.get_absolute_url())
317 return answer_redirect(request, answer)
319 if settings.FORCE_SINGLE_URL and (slug != slugify(question.title)):
320 return HttpResponsePermanentRedirect(question.get_absolute_url())
323 answer_form = AnswerForm(request.POST, user=request.user)
325 answer_form = AnswerForm(user=request.user)
327 answers = request.user.get_visible_answers(question)
329 update_question_view_times(request, question)
331 if request.user.is_authenticated():
333 subscription = QuestionSubscription.objects.get(question=question, user=request.user)
339 return pagination.paginated(request, ('answers', AnswerPaginatorContext()), {
340 "question" : question,
341 "answer" : answer_form,
343 "similar_questions" : question.get_related_questions(),
344 "subscription": subscription,
348 REVISION_TEMPLATE = template.loader.get_template('node/revision.html')
350 def revisions(request, id):
351 post = get_object_or_404(Node, id=id).leaf
352 revisions = list(post.revisions.order_by('revised_at'))
355 for i, revision in enumerate(revisions):
356 rev_ctx.append(dict(inst=revision, html=template.loader.get_template('node/revision.html').render(template.Context({
357 'title': revision.title,
358 'html': revision.html,
359 'tags': revision.tagname_list(),
363 rev_ctx[i]['diff'] = mark_safe(htmldiff(rev_ctx[i-1]['html'], rev_ctx[i]['html']))
365 rev_ctx[i]['diff'] = mark_safe(rev_ctx[i]['html'])
367 if not (revision.summary):
368 rev_ctx[i]['summary'] = _('Revision n. %(rev_number)d') % {'rev_number': revision.revision}
370 rev_ctx[i]['summary'] = revision.summary
374 return render_to_response('revisions.html', {
376 'revisions': rev_ctx,
377 }, context_instance=RequestContext(request))