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.forms import *
26 from forum.models import *
27 from forum.forms import get_next_url
28 from forum.actions import QuestionViewAction
29 from forum.http_responses import HttpResponseUnauthorized
30 from forum.feed import RssQuestionFeed
34 #refactor - move these numbers somewhere?
39 DEFAULT_PAGE_SIZE = 60
41 QUESTIONS_PAGE_SIZE = 30
43 ANSWERS_PAGE_SIZE = 10
46 return RssQuestionFeed(
47 Question.objects.filter_state(deleted=False).order_by('-last_activity_at'),
48 settings.APP_TITLE + _(' - ')+ _('latest questions'),
49 settings.APP_DESCRIPTION,
53 @decorators.render('index.html')
55 return question_list(request,
56 Question.objects.all(),
57 sort=request.utils.set_sort_method('active'),
58 base_path=reverse('questions'),
59 feed_url=reverse('latest_questions_feed'))
61 @decorators.render('questions.html', 'unanswered', _('unanswered'), weight=400)
62 def unanswered(request):
63 return question_list(request,
64 Question.objects.filter(extra_ref=None),
65 _('open questions without an accepted answer'),
66 request.utils.set_sort_method('active'),
68 _("Unanswered Questions"))
70 @decorators.render('questions.html', 'questions', _('questions'), weight=0)
71 def questions(request):
72 return question_list(request, Question.objects.all(), _('questions'), request.utils.set_sort_method('active'))
74 @decorators.render('questions.html')
75 def tag(request, tag):
76 return question_list(request,
77 Question.objects.filter(tags__name=unquote(tag)),
78 mark_safe(_('questions tagged <span class="tag">%(tag)s</span>') % {'tag': tag}),
79 request.utils.set_sort_method('active'),
81 mark_safe(_('Questions Tagged With %(tag)s') % {'tag': tag}),
84 @decorators.render('questions.html', 'questions', tabbed=False)
85 def user_questions(request, mode, user, slug):
86 user = get_object_or_404(User, id=user)
88 if mode == _('asked-by'):
89 questions = Question.objects.filter(author=user)
90 description = _("Questions asked by %s")
91 elif mode == _('answered-by'):
92 questions = Question.objects.filter(children__author=user, children__node_type='answer').distinct()
93 description = _("Questions answered by %s")
94 elif mode == _('subscribed-by'):
95 if not (request.user.is_superuser or request.user == user):
96 return HttpResponseUnauthorized(request)
97 questions = user.subscriptions
99 if request.user == user:
100 description = _("Questions you subscribed %s")
102 description = _("Questions subscribed by %s")
107 return question_list(request, questions,
108 mark_safe(description % hyperlink(user.get_profile_url(), user.username)),
109 request.utils.set_sort_method('active'),
110 page_title=description % user.username)
113 @decorators.list('questions', QUESTIONS_PAGE_SIZE)
114 def question_list(request, initial,
115 list_description=_('questions'),
118 page_title=_("All Questions"),
119 allowIgnoreTags=True,
122 questions = initial.filter_state(deleted=False)
124 if request.user.is_authenticated() and allowIgnoreTags:
125 questions = questions.filter(~Q(tags__id__in = request.user.marked_tags.filter(user_selections__reason = 'bad'))
128 if sort is not False:
130 sort = request.utils.sort_method('latest')
132 request.utils.set_sort_method(sort)
134 view_dic = {"latest":"-added_at", "active":"-last_activity_at", "hottest":"-extra_count", "mostvoted":"-score" }
136 questions=questions.order_by(view_dic.get(sort, '-added_at'))
138 if page_title is None:
139 page_title = _("Questions")
141 if request.GET.get('type', None) == 'rss':
142 return RssQuestionFeed(questions, page_title, list_description, request)(request)
145 if request.GET.get("q"):
146 keywords = request.GET.get("q").strip()
148 answer_count = Answer.objects.filter_state(deleted=False).filter(parent__in=questions).count()
149 answer_description = _("answers")
152 req_params = "&".join(["%s=%s" % (k, v) for k, v in request.GET.items() if not k in ('page', 'pagesize', 'sort')])
154 req_params = '&' + req_params
156 feed_url = mark_safe(request.path + "?type=rss" + req_params)
159 "questions" : questions,
160 "questions_count" : questions.count(),
161 "answer_count" : answer_count,
162 "keywords" : keywords,
163 "list_description": list_description,
164 "answer_description": answer_description,
165 "base_path" : base_path,
166 "page_title" : page_title,
168 'feed_url': feed_url,
173 if request.method == "GET" and "q" in request.GET:
174 keywords = request.GET.get("q")
175 search_type = request.GET.get("t")
178 return HttpResponseRedirect(reverse(index))
179 if search_type == 'tag':
180 return HttpResponseRedirect(reverse('tags') + '?q=%s' % urlquote(keywords.strip()))
181 elif search_type == "user":
182 return HttpResponseRedirect(reverse('users') + '?q=%s' % urlquote(keywords.strip()))
183 elif search_type == "question":
184 return question_search(request, keywords)
186 return render_to_response("search.html", context_instance=RequestContext(request))
188 @decorators.render('questions.html')
189 def question_search(request, keywords):
190 initial = Question.objects.search(keywords)
192 return question_list(request, initial,
193 _("questions matching '%(keywords)s'") % {'keywords': keywords},
195 "%s?t=question&q=%s" % (reverse('search'),django_urlquote(keywords)),
196 _("questions matching '%(keywords)s'") % {'keywords': keywords})
199 @decorators.render('tags.html', 'tags', _('tags'), weight=100)
203 sortby = request.GET.get('sort', 'used')
205 page = int(request.GET.get('page', '1'))
209 if request.method == "GET":
210 stag = request.GET.get("q", "").strip()
212 objects_list = Paginator(Tag.active.filter(name__contains=stag), DEFAULT_PAGE_SIZE)
215 objects_list = Paginator(Tag.active.order_by("name"), DEFAULT_PAGE_SIZE)
217 objects_list = Paginator(Tag.active.order_by("-used_count"), DEFAULT_PAGE_SIZE)
220 tags = objects_list.page(page)
221 except (EmptyPage, InvalidPage):
222 tags = objects_list.page(objects_list.num_pages)
230 'is_paginated' : is_paginated,
231 'pages': objects_list.num_pages,
233 'has_previous': tags.has_previous(),
234 'has_next': tags.has_next(),
235 'previous': tags.previous_page_number(),
236 'next': tags.next_page_number(),
237 'base_url' : reverse('tags') + '?sort=%s&' % sortby
241 def get_answer_sort_order(request):
242 view_dic = {"latest":"-added_at", "oldest":"added_at", "votes":"-score" }
244 view_id = request.GET.get('sort', request.session.get('answer_sort_order', None))
246 if view_id is None or not view_id in view_dic:
249 if view_id != request.session.get('answer_sort_order', None):
250 request.session['answer_sort_order'] = view_id
252 return (view_id, view_dic[view_id])
254 def update_question_view_times(request, question):
255 if not 'last_seen_in_question' in request.session:
256 request.session['last_seen_in_question'] = {}
258 last_seen = request.session['last_seen_in_question'].get(question.id, None)
260 if (not last_seen) or last_seen < question.last_activity_at:
261 QuestionViewAction(question, request.user, ip=request.META['REMOTE_ADDR']).save()
262 request.session['last_seen_in_question'][question.id] = datetime.datetime.now()
264 request.session['last_seen_in_question'][question.id] = datetime.datetime.now()
266 def match_question_slug(slug):
267 slug_words = slug.split('-')
268 qs = Question.objects.filter(title__istartswith=slug_words[0])
271 if slug == urlquote(slugify(q.title)):
276 def question(request, id, slug):
278 question = Question.objects.get(id=id)
281 question = match_question_slug(slug)
282 if question is not None:
283 return HttpResponsePermanentRedirect(question.get_absolute_url())
287 page = int(request.GET.get('page', 1))
288 view_id, order_by = get_answer_sort_order(request)
290 if question.nis.deleted and not request.user.can_view_deleted_post(question):
294 answer_form = AnswerForm(question, request.POST)
296 answer_form = AnswerForm(question)
298 answers = request.user.get_visible_answers(question)
300 if answers is not None:
301 answers = [a for a in answers.order_by("-marked", order_by)
302 if not a.nis.deleted or a.author == request.user]
304 objects_list = Paginator(answers, ANSWERS_PAGE_SIZE)
305 page_objects = objects_list.page(page)
307 update_question_view_times(request, question)
309 if request.user.is_authenticated():
311 subscription = QuestionSubscription.objects.get(question=question, user=request.user)
317 return render_to_response('question.html', {
318 "question" : question,
319 "answer" : answer_form,
320 "answers" : page_objects.object_list,
322 "similar_questions" : question.get_related_questions(),
323 "subscription": subscription,
325 'is_paginated' : True,
326 'pages': objects_list.num_pages,
328 'has_previous': page_objects.has_previous(),
329 'has_next': page_objects.has_next(),
330 'previous': page_objects.previous_page_number(),
331 'next': page_objects.next_page_number(),
332 'base_url' : request.path + '?sort=%s&' % view_id,
333 'extend_url' : "#sort-top"
335 }, context_instance=RequestContext(request))
338 REVISION_TEMPLATE = template.loader.get_template('node/revision.html')
340 def revisions(request, id):
341 post = get_object_or_404(Node, id=id).leaf
342 revisions = list(post.revisions.order_by('revised_at'))
346 for i, revision in enumerate(revisions):
347 rev_ctx.append(dict(inst=revision, html=REVISION_TEMPLATE.render(template.Context({
348 'title': revision.title,
349 'html': revision.html,
350 'tags': revision.tagname_list(),
354 rev_ctx[i]['diff'] = mark_safe(htmldiff(rev_ctx[i-1]['html'], rev_ctx[i]['html']))
356 rev_ctx[i]['diff'] = mark_safe(rev_ctx[i]['html'])
358 if not (revision.summary):
359 rev_ctx[i]['summary'] = _('Revision n. %(rev_number)d') % {'rev_number': revision.revision}
361 rev_ctx[i]['summary'] = revision.summary
363 return render_to_response('revisions.html', {
365 'revisions': rev_ctx,
366 }, context_instance=RequestContext(request))