4 from urllib import unquote
5 from django.conf import settings as django_settings
6 from django.shortcuts import render_to_response, get_object_or_404
7 from django.http import HttpResponseRedirect, HttpResponse, HttpResponseForbidden, 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
24 from forum.utils.diff import textDiff as htmldiff
25 from forum.forms import *
26 from forum.models import *
27 from forum.const import *
28 from forum.utils.forms import get_next_url
29 from forum.actions import QuestionViewAction
30 from forum.modules.decorators import decoratable
34 #refactor - move these numbers somewhere?
39 DEFAULT_PAGE_SIZE = 60
41 QUESTIONS_PAGE_SIZE = 30
43 ANSWERS_PAGE_SIZE = 10
45 @decorators.render('index.html')
47 return question_list(request, Question.objects.all(), sort='active', base_path=reverse('questions'))
49 @decorators.render('questions.html', 'unanswered')
50 def unanswered(request):
51 return question_list(request, Question.objects.filter(extra_ref=None),
52 _('Open questions without an accepted answer'))
54 @decorators.render('questions.html', 'questions')
55 def questions(request):
56 return question_list(request, Question.objects.all())
58 @decorators.render('questions.html')
59 def tag(request, tag):
60 return question_list(request, Question.objects.filter(tags__name=unquote(tag)),
61 mark_safe(_('Questions tagged <span class="tag">%(tag)s</span>') % {'tag': tag}))
63 @decorators.list('questions', QUESTIONS_PAGE_SIZE)
64 def question_list(request, initial, list_description=_('questions'), sort=None, base_path=None):
65 questions = initial.filter(deleted=None, in_moderation=None)
67 if request.user.is_authenticated():
68 questions = questions.filter(
69 ~Q(tags__id__in=request.user.marked_tags.filter(user_selections__reason='bad')))
73 sort = request.utils.sort_method('latest')
75 request.utils.set_sort_method(sort)
77 view_dic = {"latest":"-added_at", "active":"-last_activity_at", "hottest":"-extra_count", "mostvoted":"-score" }
79 questions=questions.order_by(view_dic.get(sort, '-added_at'))
82 "questions" : questions,
83 "questions_count" : questions.count(),
84 #"tags_autocomplete" : _get_tags_cache_json(),
85 "list_description": list_description,
86 "base_path" : base_path,
91 if request.method == "GET" and "q" in request.GET:
92 keywords = request.GET.get("q")
93 search_type = request.GET.get("t")
96 return HttpResponseRedirect(reverse(index))
97 if search_type == 'tag':
98 return HttpResponseRedirect(reverse('tags') + '?q=%s' % (keywords.strip()))
99 elif search_type == "user":
100 return HttpResponseRedirect(reverse('users') + '?q=%s' % (keywords.strip()))
101 elif search_type == "question":
102 return question_search(request, keywords)
104 return render_to_response("search.html", context_instance=RequestContext(request))
107 def do_question_search(keywords):
108 return Question.objects.filter(Q(title__icontains=keywords) | Q(body__icontains=keywords))
110 @decorators.render('questions.html')
111 def question_search(request, keywords):
112 initial = do_question_search(keywords)
114 return question_list(request, initial, _("questions matching '%(keywords)s'") % {'keywords': keywords},
115 base_path="%s?t=question&q=%s" % (reverse('search'), django_urlquote(keywords)), sort=False)
118 def tags(request):#view showing a listing of available tags - plain list
121 sortby = request.GET.get('sort', 'used')
123 page = int(request.GET.get('page', '1'))
127 if request.method == "GET":
128 stag = request.GET.get("q", "").strip()
130 objects_list = Paginator(Tag.objects.filter(deleted=False).exclude(used_count=0).extra(where=['name like %s'], params=['%' + stag + '%']), DEFAULT_PAGE_SIZE)
133 objects_list = Paginator(Tag.objects.all().filter(deleted=False).exclude(used_count=0).order_by("name"), DEFAULT_PAGE_SIZE)
135 objects_list = Paginator(Tag.objects.all().filter(deleted=False).exclude(used_count=0).order_by("-used_count"), DEFAULT_PAGE_SIZE)
138 tags = objects_list.page(page)
139 except (EmptyPage, InvalidPage):
140 tags = objects_list.page(objects_list.num_pages)
142 return render_to_response('tags.html', {
148 'is_paginated' : is_paginated,
149 'pages': objects_list.num_pages,
151 'has_previous': tags.has_previous(),
152 'has_next': tags.has_next(),
153 'previous': tags.previous_page_number(),
154 'next': tags.next_page_number(),
155 'base_url' : reverse('tags') + '?sort=%s&' % sortby
157 }, context_instance=RequestContext(request))
159 def get_answer_sort_order(request):
160 view_dic = {"latest":"-added_at", "oldest":"added_at", "votes":"-score" }
162 view_id = request.GET.get('sort', request.session.get('answer_sort_order', None))
164 if view_id is None or not view_id in view_dic:
167 if view_id != request.session.get('answer_sort_order', None):
168 request.session['answer_sort_order'] = view_id
170 return (view_id, view_dic[view_id])
172 def update_question_view_times(request, question):
173 if not 'last_seen_in_question' in request.session:
174 request.session['last_seen_in_question'] = {}
176 last_seen = request.session['last_seen_in_question'].get(question.id,None)
178 if (not last_seen) or last_seen < question.last_activity_at:
179 QuestionViewAction(question, request.user).save()
180 request.session['last_seen_in_question'][question.id] = datetime.datetime.now()
182 request.session['last_seen_in_question'][question.id] = datetime.datetime.now()
184 def match_question_slug(slug):
185 slug_words = slug.split('-')
186 qs = Question.objects.filter(node_type="question", title__istartswith=slug_words[0])
189 if slug == urlquote(slugify(q.title)):
194 def question(request, id, slug):
196 question = Question.objects.get(node_type="question", id=id)
198 question = match_question_slug(slug)
199 if question is not None:
200 return HttpResponsePermanentRedirect(question.get_absolute_url())
204 if slug != urlquote(slugify(question.title)):
205 return HttpResponsePermanentRedirect(question.get_absolute_url())
207 page = int(request.GET.get('page', 1))
208 view_id, order_by = get_answer_sort_order(request)
210 if question.deleted and not request.user.can_view_deleted_post(question):
213 answer_form = AnswerForm(question)
214 answers = request.user.get_visible_answers(question)
216 if answers is not None:
217 answers = [a for a in answers.order_by("-marked", order_by)
218 if not a.deleted or a.author == request.user]
220 objects_list = Paginator(answers, ANSWERS_PAGE_SIZE)
221 page_objects = objects_list.page(page)
223 update_question_view_times(request, question)
225 if request.user.is_authenticated():
227 subscription = QuestionSubscription.objects.get(question=question, user=request.user)
233 return render_to_response('question.html', {
234 "question" : question,
235 "answer" : answer_form,
236 "answers" : page_objects.object_list,
238 "similar_questions" : question.get_related_questions(),
239 "subscription": subscription,
241 'is_paginated' : True,
242 'pages': objects_list.num_pages,
244 'has_previous': page_objects.has_previous(),
245 'has_next': page_objects.has_next(),
246 'previous': page_objects.previous_page_number(),
247 'next': page_objects.next_page_number(),
248 'base_url' : request.path + '?sort=%s&' % view_id,
249 'extend_url' : "#sort-top"
251 }, context_instance=RequestContext(request))
254 REVISION_TEMPLATE = template.loader.get_template('node/revision.html')
256 def revisions(request, id):
257 post = get_object_or_404(Node, id=id).leaf
258 revisions = list(post.revisions.order_by('revised_at'))
262 for i, revision in enumerate(revisions):
263 rev_ctx.append(dict(inst=revision, html=REVISION_TEMPLATE.render(template.Context({
264 'title': revision.title,
265 'html': revision.html,
266 'tags': revision.tagname_list(),
270 rev_ctx[i]['diff'] = mark_safe(htmldiff(rev_ctx[i-1]['html'], rev_ctx[i]['html']))
272 rev_ctx[i]['diff'] = mark_safe(rev_ctx[i]['html'])
274 if not (revision.summary):
275 rev_ctx[i]['summary'] = _('Revision n. %(rev_number)d') % {'rev_number': revision.revision}
277 rev_ctx[i]['summary'] = revision.summary
279 return render_to_response('revisions.html', {
281 'revisions': rev_ctx,
282 }, context_instance=RequestContext(request))