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.models.question import question_view
33 #refactor - move these numbers somewhere?
38 DEFAULT_PAGE_SIZE = 60
40 QUESTIONS_PAGE_SIZE = 30
42 ANSWERS_PAGE_SIZE = 10
44 #system to display main content
45 def _get_tags_cache_json():#service routine used by views requiring tag list in the javascript space
46 """returns list of all tags in json format
47 no caching yet, actually
49 tags = Tag.objects.filter(deleted=False).all()
52 dic = {'n': tag.name, 'c': tag.used_count}
54 tags = simplejson.dumps(tags_list)
57 @decorators.render('index.html')
59 return question_list(request, Question.objects.all(), sort='active', base_path=reverse('questions'))
61 @decorators.render('questions.html', 'unanswered')
62 def unanswered(request):
63 return question_list(request, Question.objects.filter(accepted_answer=None),
64 _('Open questions without an accepted answer'))
66 @decorators.render('questions.html', 'questions')
67 def questions(request):
68 return question_list(request, Question.objects.all())
70 @decorators.render('questions.html')
71 def tag(request, tag):
72 return question_list(request, Question.objects.filter(tags__name=unquote(tag)),
73 mark_safe(_('Questions tagged <span class="tag">%(tag)s</span>') % {'tag': tag}))
75 @decorators.list('questions', QUESTIONS_PAGE_SIZE)
76 def question_list(request, initial, list_description=_('questions'), sort=None, base_path=None):
77 pagesize = request.utils.page_size(QUESTIONS_PAGE_SIZE)
78 page = int(request.GET.get('page', 1))
80 questions = initial.filter(deleted=False)
82 if request.user.is_authenticated():
83 questions = questions.filter(
84 ~Q(tags__id__in=request.user.marked_tags.filter(user_selections__reason='bad')))
88 sort = request.utils.sort_method('latest')
90 request.utils.set_sort_method(sort)
92 view_dic = {"latest":"-added_at", "active":"-last_activity_at", "hottest":"-answer_count", "mostvoted":"-score" }
94 questions=questions.order_by(view_dic.get(sort, '-added_at'))
97 "questions" : questions,
98 "questions_count" : questions.count(),
99 "tags_autocomplete" : _get_tags_cache_json(),
100 "list_description": list_description,
101 "base_path" : base_path,
106 if request.method == "GET" and "q" in request.GET:
107 keywords = request.GET.get("q")
108 search_type = request.GET.get("t")
111 return HttpResponseRedirect(reverse(index))
112 if search_type == 'tag':
113 return HttpResponseRedirect(reverse('tags') + '?q=%s' % (keywords.strip()))
114 elif search_type == "user":
115 return HttpResponseRedirect(reverse('users') + '?q=%s' % (keywords.strip()))
116 elif search_type == "question":
117 return question_search(request, keywords)
119 return render_to_response("search.html", context_instance=RequestContext(request))
121 @decorators.render('questions.html')
122 def question_search(request, keywords):
123 def question_search(keywords, orderby):
124 return Question.objects.filter(Q(title__icontains=keywords) | Q(html__icontains=keywords))
126 from forum.modules import get_handler
128 question_search = get_handler('question_search', question_search)
129 initial = question_search(keywords)
131 return question_list(request, initial, _("questions matching '%(keywords)s'") % {'keywords': keywords},
132 base_path="%s?t=question&q=%s" % (reverse('search'), django_urlquote(keywords)), sort=False)
135 def tags(request):#view showing a listing of available tags - plain list
138 sortby = request.GET.get('sort', 'used')
140 page = int(request.GET.get('page', '1'))
144 if request.method == "GET":
145 stag = request.GET.get("q", "").strip()
147 objects_list = Paginator(Tag.objects.filter(deleted=False).exclude(used_count=0).extra(where=['name like %s'], params=['%' + stag + '%']), DEFAULT_PAGE_SIZE)
150 objects_list = Paginator(Tag.objects.all().filter(deleted=False).exclude(used_count=0).order_by("name"), DEFAULT_PAGE_SIZE)
152 objects_list = Paginator(Tag.objects.all().filter(deleted=False).exclude(used_count=0).order_by("-used_count"), DEFAULT_PAGE_SIZE)
155 tags = objects_list.page(page)
156 except (EmptyPage, InvalidPage):
157 tags = objects_list.page(objects_list.num_pages)
159 return render_to_response('tags.html', {
165 'is_paginated' : is_paginated,
166 'pages': objects_list.num_pages,
168 'has_previous': tags.has_previous(),
169 'has_next': tags.has_next(),
170 'previous': tags.previous_page_number(),
171 'next': tags.next_page_number(),
172 'base_url' : reverse('tags') + '?sort=%s&' % sortby
174 }, context_instance=RequestContext(request))
176 def get_answer_sort_order(request):
177 view_dic = {"latest":"-added_at", "oldest":"added_at", "votes":"-score" }
179 view_id = request.GET.get('sort', request.session.get('answer_sort_order', None))
181 if view_id is None or not view_id in view_dic:
184 if view_id != request.session.get('answer_sort_order', None):
185 request.session['answer_sort_order'] = view_id
187 return (view_id, view_dic[view_id])
189 def update_question_view_times(request, question):
190 if not 'last_seen_in_question' in request.session:
191 request.session['last_seen_in_question'] = {}
193 last_seen = request.session['last_seen_in_question'].get(question.id,None)
195 if (not last_seen) or last_seen < question.last_activity_at:
196 question_view.send(sender=update_question_view_times, instance=question, user=request.user)
197 request.session['last_seen_in_question'][question.id] = datetime.datetime.now()
199 request.session['last_seen_in_question'][question.id] = datetime.datetime.now()
201 def match_question_slug(slug):
202 slug_words = slug.split('-')
203 qs = Question.objects.filter(title__istartswith=slug_words[0])
206 if slug == urlquote(slugify(q.title)):
211 def question(request, id, slug):
213 question = Question.objects.get(id=id)
215 question = match_question_slug(slug)
216 if question is not None:
217 return HttpResponsePermanentRedirect(question.get_absolute_url())
221 if slug != urlquote(slugify(question.title)):
222 return HttpResponsePermanentRedirect(question.get_absolute_url())
224 page = int(request.GET.get('page', 1))
225 view_id, order_by = get_answer_sort_order(request)
227 if question.deleted and not request.user.can_view_deleted_post(question):
230 answer_form = AnswerForm(question)
231 answers = request.user.get_visible_answers(question)
233 if answers is not None:
234 answers = [a for a in answers.order_by("-accepted", order_by)
235 if not a.deleted or a.author == request.user]
237 objects_list = Paginator(answers, ANSWERS_PAGE_SIZE)
238 page_objects = objects_list.page(page)
240 update_question_view_times(request, question)
242 if request.user.is_authenticated():
244 subscription = QuestionSubscription.objects.get(question=question, user=request.user)
250 return render_to_response('question.html', {
251 "question" : question,
252 "answer" : answer_form,
253 "answers" : page_objects.object_list,
254 "tags" : question.tags.all(),
256 "similar_questions" : question.get_related_questions(),
257 "subscription": subscription,
259 'is_paginated' : True,
260 'pages': objects_list.num_pages,
262 'has_previous': page_objects.has_previous(),
263 'has_next': page_objects.has_next(),
264 'previous': page_objects.previous_page_number(),
265 'next': page_objects.next_page_number(),
266 'base_url' : request.path + '?sort=%s&' % view_id,
267 'extend_url' : "#sort-top"
269 }, context_instance=RequestContext(request))
272 REVISION_TEMPLATE = template.loader.get_template('node/revision.html')
274 def revisions(request, id):
275 post = get_object_or_404(Node, id=id).leaf
276 revisions = list(post.revisions.order_by('revised_at'))
280 for i, revision in enumerate(revisions):
281 rev_ctx.append(dict(inst=revision, html=REVISION_TEMPLATE.render(template.Context({
282 'title': revision.title,
283 'html': revision.html,
284 'tags': revision.tagname_list(),
288 rev_ctx[i]['diff'] = mark_safe(htmldiff(rev_ctx[i-1]['html'], rev_ctx[i]['html']))
290 rev_ctx[i]['diff'] = mark_safe(rev_ctx[i]['html'])
292 if not (revision.summary):
293 rev_ctx[i]['summary'] = _('Revision n. %(rev_number)d') % {'rev_number': revision.revision}
295 rev_ctx[i]['summary'] = revision.summary
297 return render_to_response('revisions_question.html', {
299 'revisions': rev_ctx,
300 }, context_instance=RequestContext(request))