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
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
34 class QuestionListPaginatorContext(pagination.PaginatorContext):
35 def __init__(self, id='QUESTIONS_LIST', prefix='', default_pagesize=30):
36 super (QuestionListPaginatorContext, self).__init__(id, sort_methods=(
37 (_('active'), pagination.SimpleSort(_('active'), '-last_activity_at', _("most recently updated questions"))),
38 (_('newest'), pagination.SimpleSort(_('newest'), '-added_at', _("most recently asked questions"))),
39 (_('hottest'), pagination.SimpleSort(_('hottest'), '-extra_count', _("hottest questions"))),
40 (_('mostvoted'), pagination.SimpleSort(_('most voted'), '-score', _("most voted questions"))),
41 ), pagesizes=(15, 30, 50), default_pagesize=default_pagesize, prefix=prefix)
43 class AnswerPaginatorContext(pagination.PaginatorContext):
44 def __init__(self, id='ANSWER_LIST', prefix='', default_pagesize=10):
45 super (AnswerPaginatorContext, self).__init__(id, sort_methods=(
46 (_('oldest'), pagination.SimpleSort(_('oldest answers'), ('-marked', 'added_at'), _("oldest answers will be shown first"))),
47 (_('newest'), pagination.SimpleSort(_('newest answers'), ('-marked', '-added_at'), _("newest answers will be shown first"))),
48 (_('votes'), pagination.SimpleSort(_('popular answers'), ('-marked', '-score', 'added_at'), _("most voted answers will be shown first"))),
49 ), default_sort=_('votes'), sticky_sort = True, pagesizes=(5, 10, 20), default_pagesize=default_pagesize, prefix=prefix)
51 class TagPaginatorContext(pagination.PaginatorContext):
53 super (TagPaginatorContext, self).__init__('TAG_LIST', sort_methods=(
54 (_('name'), pagination.SimpleSort(_('by name'), 'name', _("sorted alphabetically"))),
55 (_('used'), pagination.SimpleSort(_('by popularity'), '-used_count', _("sorted by frequency of tag use"))),
56 ), default_sort=_('used'), pagesizes=(30, 60, 120))
60 return RssQuestionFeed(
62 Question.objects.filter_state(deleted=False).order_by('-last_activity_at'),
63 settings.APP_TITLE + _(' - ')+ _('latest questions'),
64 settings.APP_DESCRIPTION)(request)
67 @decorators.render('index.html')
69 return question_list(request,
70 Question.objects.all(),
71 sort=request.utils.set_sort_method('active'),
72 base_path=reverse('questions'),
73 feed_url=reverse('latest_questions_feed'))
75 @decorators.render('questions.html', 'unanswered', _('unanswered'), weight=400)
76 def unanswered(request):
77 return question_list(request,
78 Question.objects.filter(extra_ref=None),
79 _('open questions without an accepted answer'),
80 request.utils.set_sort_method('active'),
82 _("Unanswered Questions"))
84 @decorators.render('questions.html', 'questions', _('questions'), weight=0)
85 def questions(request):
86 return question_list(request, Question.objects.all(), _('questions'), request.utils.set_sort_method('active'))
88 @decorators.render('questions.html')
89 def tag(request, tag):
90 return question_list(request,
91 Question.objects.filter(tags__name=unquote(tag)),
92 mark_safe(_('questions tagged <span class="tag">%(tag)s</span>') % {'tag': tag}),
93 request.utils.set_sort_method('active'),
95 mark_safe(_('Questions Tagged With %(tag)s') % {'tag': tag}),
98 @decorators.render('questions.html', 'questions', tabbed=False)
99 def user_questions(request, mode, user, slug):
100 user = get_object_or_404(User, id=user)
102 if mode == _('asked-by'):
103 questions = Question.objects.filter(author=user)
104 description = _("Questions asked by %s")
105 elif mode == _('answered-by'):
106 questions = Question.objects.filter(children__author=user, children__node_type='answer').distinct()
107 description = _("Questions answered by %s")
108 elif mode == _('subscribed-by'):
109 if not (request.user.is_superuser or request.user == user):
110 return HttpResponseUnauthorized(request)
111 questions = user.subscriptions
113 if request.user == user:
114 description = _("Questions you subscribed %s")
116 description = _("Questions subscribed by %s")
121 return question_list(request, questions,
122 mark_safe(description % hyperlink(user.get_profile_url(), user.username)),
123 request.utils.set_sort_method('active'),
124 page_title=description % user.username)
126 def question_list(request, initial,
127 list_description=_('questions'),
130 page_title=_("All Questions"),
131 allowIgnoreTags=True,
133 paginator_context=None):
135 questions = initial.filter_state(deleted=False)
137 if request.user.is_authenticated() and allowIgnoreTags:
138 questions = questions.filter(~Q(tags__id__in = request.user.marked_tags.filter(user_selections__reason = 'bad')))
140 if page_title is None:
141 page_title = _("Questions")
143 if request.GET.get('type', None) == 'rss':
144 questions = questions.order_by('-added_at')
145 return RssQuestionFeed(request, questions, page_title, list_description)(request)
148 if request.GET.get("q"):
149 keywords = request.GET.get("q").strip()
151 answer_count = Answer.objects.filter_state(deleted=False).filter(parent__in=questions).count()
152 answer_description = _("answers")
155 req_params = "&".join(["%s=%s" % (k, v) for k, v in request.GET.items() if not k in (_('page'), _('pagesize'), _('sort'))])
157 req_params = '&' + req_params
159 feed_url = mark_safe(request.path + "?type=rss" + req_params)
161 return pagination.paginated(request, ('questions', paginator_context or QuestionListPaginatorContext()), {
162 "questions" : questions,
163 "questions_count" : questions.count(),
164 "answer_count" : answer_count,
165 "keywords" : keywords,
166 "list_description": list_description,
167 "answer_description": answer_description,
168 "base_path" : base_path,
169 "page_title" : page_title,
171 'feed_url': feed_url,
176 if request.method == "GET" and "q" in request.GET:
177 keywords = request.GET.get("q")
178 search_type = request.GET.get("t")
181 return HttpResponseRedirect(reverse(index))
182 if search_type == 'tag':
183 return HttpResponseRedirect(reverse('tags') + '?q=%s' % urlquote(keywords.strip()))
184 elif search_type == "user":
185 return HttpResponseRedirect(reverse('users') + '?q=%s' % urlquote(keywords.strip()))
186 elif search_type == "question":
187 return question_search(request, keywords)
189 return render_to_response("search.html", context_instance=RequestContext(request))
191 @decorators.render('questions.html')
192 def question_search(request, keywords):
193 can_rank, initial = Question.objects.search(keywords)
196 paginator_context = QuestionListPaginatorContext()
197 paginator_context.sort_methods[_('ranking')] = pagination.SimpleSort(_('relevance'), '-ranking', _("most relevant questions"))
198 paginator_context.force_sort = _('ranking')
200 paginator_context = None
202 return question_list(request, initial,
203 _("questions matching '%(keywords)s'") % {'keywords': keywords},
205 "%s?t=question&q=%s" % (reverse('search'),django_urlquote(keywords)),
206 _("questions matching '%(keywords)s'") % {'keywords': keywords},
207 paginator_context=paginator_context)
210 @decorators.render('tags.html', 'tags', _('tags'), weight=100)
213 tags = Tag.active.all()
215 if request.method == "GET":
216 stag = request.GET.get("q", "").strip()
218 tags = tags.filter(name__contains=stag)
220 return pagination.paginated(request, ('tags', TagPaginatorContext()), {
226 def update_question_view_times(request, question):
227 if not 'last_seen_in_question' in request.session:
228 request.session['last_seen_in_question'] = {}
230 last_seen = request.session['last_seen_in_question'].get(question.id, None)
232 if (not last_seen) or last_seen < question.last_activity_at:
233 QuestionViewAction(question, request.user, ip=request.META['REMOTE_ADDR']).save()
234 request.session['last_seen_in_question'][question.id] = datetime.datetime.now()
236 request.session['last_seen_in_question'][question.id] = datetime.datetime.now()
238 def match_question_slug(slug):
239 slug_words = slug.split('-')
240 qs = Question.objects.filter(title__istartswith=slug_words[0])
243 if slug == urlquote(slugify(q.title)):
248 def answer_redirect(request, answer):
249 pc = AnswerPaginatorContext()
251 sort = pc.sort(request)
253 if sort == _('oldest'):
254 filter = Q(added_at__lt=answer.added_at)
255 elif sort == _('newest'):
256 filter = Q(added_at__gt=answer.added_at)
257 elif sort == _('votes'):
258 filter = Q(score__gt=answer.score) | Q(score=answer.score, added_at__lt=answer.added_at)
262 count = answer.question.answers.filter(Q(marked=True) | filter).count()
263 pagesize = pc.pagesize(request)
265 page = count / pagesize
273 return HttpResponsePermanentRedirect("%s?%s=%s#%s" % (
274 answer.question.get_absolute_url(), _('page'), page, answer.id))
276 @decorators.render("question.html", 'questions')
277 def question(request, id, slug=None, answer=None):
279 question = Question.objects.get(id=id)
282 question = match_question_slug(slug)
283 if question is not None:
284 return HttpResponseRedirect(question.get_absolute_url())
288 if question.nis.deleted and not request.user.can_view_deleted_post(question):
291 if request.GET.get('type', None) == 'rss':
292 return RssAnswerFeed(request, question, include_comments=request.GET.get('comments', None) == 'yes')(request)
295 answer = get_object_or_404(Answer, id=answer)
297 if (question.nis.deleted and not request.user.can_view_deleted_post(question)) or answer.question != question:
301 return HttpResponsePermanentRedirect(question.get_absolute_url())
303 return answer_redirect(request, answer)
305 if (not slug) or (slug != urlquote(slugify(question.title))):
306 return HttpResponsePermanentRedirect(question.get_absolute_url())
309 answer_form = AnswerForm(question, request.POST)
311 answer_form = AnswerForm(question)
313 answers = request.user.get_visible_answers(question)
315 update_question_view_times(request, question)
317 if request.user.is_authenticated():
319 subscription = QuestionSubscription.objects.get(question=question, user=request.user)
325 return pagination.paginated(request, ('answers', AnswerPaginatorContext()), {
326 "question" : question,
327 "answer" : answer_form,
329 "similar_questions" : question.get_related_questions(),
330 "subscription": subscription,
334 REVISION_TEMPLATE = template.loader.get_template('node/revision.html')
336 def revisions(request, id):
337 post = get_object_or_404(Node, id=id).leaf
338 revisions = list(post.revisions.order_by('revised_at'))
341 for i, revision in enumerate(revisions):
342 rev_ctx.append(dict(inst=revision, html=template.loader.get_template('node/revision.html').render(template.Context({
343 'title': revision.title,
344 'html': revision.html,
345 'tags': revision.tagname_list(),
349 rev_ctx[i]['diff'] = mark_safe(htmldiff(rev_ctx[i-1]['html'], rev_ctx[i]['html']))
351 rev_ctx[i]['diff'] = mark_safe(rev_ctx[i]['html'])
353 if not (revision.summary):
354 rev_ctx[i]['summary'] = _('Revision n. %(rev_number)d') % {'rev_number': revision.revision}
356 rev_ctx[i]['summary'] = revision.summary
360 return render_to_response('revisions.html', {
362 'revisions': rev_ctx,
363 }, context_instance=RequestContext(request))