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, 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.utils.forms import get_next_url
28 from forum.actions import QuestionViewAction
29 from forum.modules.decorators import decoratable
33 #refactor - move these numbers somewhere?
38 DEFAULT_PAGE_SIZE = 60
40 QUESTIONS_PAGE_SIZE = 30
42 ANSWERS_PAGE_SIZE = 10
44 @decorators.render('index.html')
46 return question_list(request,
47 Question.objects.all(),
48 sort=request.utils.set_sort_method('active'),
49 base_path=reverse('questions'))
51 @decorators.render('questions.html', 'unanswered')
52 def unanswered(request):
53 return question_list(request,
54 Question.objects.filter(extra_ref=None),
55 _('open questions without an accepted answer'),
56 request.utils.set_sort_method('active'),
58 _("Unanswered questions"))
60 @decorators.render('questions.html', 'questions')
61 def questions(request):
62 return question_list(request, Question.objects.all(), _('questions'), request.utils.set_sort_method('active'))
64 @decorators.render('questions.html')
65 def tag(request, tag):
66 return question_list(request,
67 Question.objects.filter(tags__name=unquote(tag)),
68 mark_safe(_('questions tagged <span class="tag">%(tag)s</span>') % {'tag': tag}),
69 request.utils.set_sort_method('active'),
71 mark_safe(_('questions tagged %(tag)s') % {'tag': tag}),
74 @decorators.list('questions', QUESTIONS_PAGE_SIZE)
75 def question_list(request, initial, list_description=_('questions'), sort=None, base_path=None, page_title=None, allowIgnoreTags=True):
76 questions = initial.filter(deleted=None, in_moderation=None)
78 if request.user.is_authenticated() and allowIgnoreTags:
79 questions = questions.filter(~Q(tags__id__in = request.user.marked_tags.filter(user_selections__reason = 'bad')))
83 sort = request.utils.sort_method('latest')
85 request.utils.set_sort_method(sort)
87 view_dic = {"latest":"-added_at", "active":"-last_activity_at", "hottest":"-extra_count", "mostvoted":"-score" }
89 questions=questions.order_by(view_dic.get(sort, '-added_at'))
91 if page_title is None:
92 page_title = _("Questions")
95 if request.GET.get("q"):
96 keywords = request.GET.get("q").strip()
98 answer_count = Answer.objects.filter(deleted=None, parent__in=questions).count()
99 answer_description = _("answers")
102 "questions" : questions,
103 "questions_count" : questions.count(),
104 "answer_count" : answer_count,
105 "keywords" : keywords,
106 #"tags_autocomplete" : _get_tags_cache_json(),
107 "list_description": list_description,
108 "answer_description": answer_description,
109 "base_path" : base_path,
110 "page_title" : page_title,
115 if request.method == "GET" and "q" in request.GET:
116 keywords = request.GET.get("q")
117 search_type = request.GET.get("t")
120 return HttpResponseRedirect(reverse(index))
121 if search_type == 'tag':
122 return HttpResponseRedirect(reverse('tags') + '?q=%s' % (keywords.strip()))
123 elif search_type == "user":
124 return HttpResponseRedirect(reverse('users') + '?q=%s' % (keywords.strip()))
125 elif search_type == "question":
126 return question_search(request, keywords)
128 return render_to_response("search.html", context_instance=RequestContext(request))
131 def do_question_search(keywords):
132 return Question.objects.filter(Q(title__icontains=keywords) | Q(body__icontains=keywords))
134 @decorators.render('questions.html')
135 def question_search(request, keywords):
136 initial = do_question_search(keywords)
138 return question_list(request, initial, _("questions matching '%(keywords)s'") % {'keywords': keywords},
139 base_path="%s?t=question&q=%s" % (reverse('search'), django_urlquote(keywords)), sort=False)
142 def tags(request):#view showing a listing of available tags - plain list
145 sortby = request.GET.get('sort', 'used')
147 page = int(request.GET.get('page', '1'))
151 if request.method == "GET":
152 stag = request.GET.get("q", "").strip()
154 objects_list = Paginator(Tag.objects.filter(deleted=False).exclude(used_count=0).extra(where=['name like %s'], params=['%' + stag + '%']), DEFAULT_PAGE_SIZE)
157 objects_list = Paginator(Tag.objects.all().filter(deleted=False).exclude(used_count=0).order_by("name"), DEFAULT_PAGE_SIZE)
159 objects_list = Paginator(Tag.objects.all().filter(deleted=False).exclude(used_count=0).order_by("-used_count"), DEFAULT_PAGE_SIZE)
162 tags = objects_list.page(page)
163 except (EmptyPage, InvalidPage):
164 tags = objects_list.page(objects_list.num_pages)
166 return render_to_response('tags.html', {
172 'is_paginated' : is_paginated,
173 'pages': objects_list.num_pages,
175 'has_previous': tags.has_previous(),
176 'has_next': tags.has_next(),
177 'previous': tags.previous_page_number(),
178 'next': tags.next_page_number(),
179 'base_url' : reverse('tags') + '?sort=%s&' % sortby
181 }, context_instance=RequestContext(request))
183 def get_answer_sort_order(request):
184 view_dic = {"latest":"-added_at", "oldest":"added_at", "votes":"-score" }
186 view_id = request.GET.get('sort', request.session.get('answer_sort_order', None))
188 if view_id is None or not view_id in view_dic:
191 if view_id != request.session.get('answer_sort_order', None):
192 request.session['answer_sort_order'] = view_id
194 return (view_id, view_dic[view_id])
196 def update_question_view_times(request, question):
197 if not 'last_seen_in_question' in request.session:
198 request.session['last_seen_in_question'] = {}
200 last_seen = request.session['last_seen_in_question'].get(question.id,None)
202 if (not last_seen) or last_seen < question.last_activity_at:
203 QuestionViewAction(question, request.user, ip=request.META['REMOTE_ADDR']).save()
204 request.session['last_seen_in_question'][question.id] = datetime.datetime.now()
206 request.session['last_seen_in_question'][question.id] = datetime.datetime.now()
208 def match_question_slug(slug):
209 slug_words = slug.split('-')
210 qs = Question.objects.filter(node_type="question", title__istartswith=slug_words[0])
213 if slug == urlquote(slugify(q.title)):
218 def question(request, id, slug):
220 question = Question.objects.get(node_type="question", id=id)
222 question = match_question_slug(slug)
223 if question is not None:
224 return HttpResponsePermanentRedirect(question.get_absolute_url())
228 if slug != urlquote(slugify(question.title)):
229 return HttpResponsePermanentRedirect(question.get_absolute_url())
231 page = int(request.GET.get('page', 1))
232 view_id, order_by = get_answer_sort_order(request)
234 if question.deleted and not request.user.can_view_deleted_post(question):
238 answer_form = AnswerForm(question, request.POST)
240 answer_form = AnswerForm(question)
242 answers = request.user.get_visible_answers(question)
244 if answers is not None:
245 answers = [a for a in answers.order_by("-marked", order_by)
246 if not a.deleted or a.author == request.user]
248 objects_list = Paginator(answers, ANSWERS_PAGE_SIZE)
249 page_objects = objects_list.page(page)
251 update_question_view_times(request, question)
253 if request.user.is_authenticated():
255 subscription = QuestionSubscription.objects.get(question=question, user=request.user)
261 return render_to_response('question.html', {
262 "question" : question,
263 "answer" : answer_form,
264 "answers" : page_objects.object_list,
266 "similar_questions" : question.get_related_questions(),
267 "subscription": subscription,
269 'is_paginated' : True,
270 'pages': objects_list.num_pages,
272 'has_previous': page_objects.has_previous(),
273 'has_next': page_objects.has_next(),
274 'previous': page_objects.previous_page_number(),
275 'next': page_objects.next_page_number(),
276 'base_url' : request.path + '?sort=%s&' % view_id,
277 'extend_url' : "#sort-top"
279 }, context_instance=RequestContext(request))
282 REVISION_TEMPLATE = template.loader.get_template('node/revision.html')
284 def revisions(request, id):
285 post = get_object_or_404(Node, id=id).leaf
286 revisions = list(post.revisions.order_by('revised_at'))
290 for i, revision in enumerate(revisions):
291 rev_ctx.append(dict(inst=revision, html=REVISION_TEMPLATE.render(template.Context({
292 'title': revision.title,
293 'html': revision.html,
294 'tags': revision.tagname_list(),
298 rev_ctx[i]['diff'] = mark_safe(htmldiff(rev_ctx[i-1]['html'], rev_ctx[i]['html']))
300 rev_ctx[i]['diff'] = mark_safe(rev_ctx[i]['html'])
302 if not (revision.summary):
303 rev_ctx[i]['summary'] = _('Revision n. %(rev_number)d') % {'rev_number': revision.revision}
305 rev_ctx[i]['summary'] = revision.summary
307 return render_to_response('revisions.html', {
309 'revisions': rev_ctx,
310 }, context_instance=RequestContext(request))