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
8 from django.core.paginator import Paginator, EmptyPage, InvalidPage
9 from django.template import RequestContext
10 from django.utils.html import *
11 from django.utils import simplejson
12 from django.db.models import Q
13 from django.utils.translation import ugettext as _
14 from django.template.defaultfilters import slugify
15 from django.core.urlresolvers import reverse
16 from django.utils.datastructures import SortedDict
17 from django.views.decorators.cache import cache_page
18 from django.utils.http import urlquote as django_urlquote
19 from django.template.defaultfilters import slugify
20 from django.utils.safestring import mark_safe
22 from forum.utils.html import sanitize_html
23 from markdown2 import Markdown
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 markdowner = Markdown(html4tags=True)
46 #system to display main content
47 def _get_tags_cache_json():#service routine used by views requiring tag list in the javascript space
48 """returns list of all tags in json format
49 no caching yet, actually
51 tags = Tag.objects.filter(deleted=False).all()
54 dic = {'n': tag.name, 'c': tag.used_count}
56 tags = simplejson.dumps(tags_list)
59 @decorators.render('index.html')
61 return question_list(request, Question.objects.all(), sort='latest', base_path=reverse('questions'))
63 @decorators.render('questions.html', 'unanswered')
64 def unanswered(request):
65 return question_list(request, Question.objects.filter(answer_accepted=False),
66 _('Open questions without an accepted answer'))
68 @decorators.render('questions.html', 'questions')
69 def questions(request):
70 return question_list(request, Question.objects.all())
72 @decorators.render('questions.html')
73 def tag(request, tag):
74 return question_list(request, Question.objects.filter(tags__name=unquote(tag)),
75 mark_safe(_('Questions tagged <span class="tag">%(tag)s</span>') % {'tag': tag}))
77 @decorators.list('questions', QUESTIONS_PAGE_SIZE)
78 def question_list(request, initial, list_description=_('questions'), sort=None, base_path=None):
79 pagesize = request.utils.page_size(QUESTIONS_PAGE_SIZE)
80 page = int(request.GET.get('page', 1))
82 questions = initial.filter(deleted=False)
84 if request.user.is_authenticated():
85 questions = questions.filter(
86 ~Q(tags__id__in=request.user.marked_tags.filter(user_selections__reason='bad')))
89 sort = request.utils.sort_method('latest')
91 request.utils.set_sort_method(sort)
93 view_dic = {"latest":"-added_at", "active":"-last_activity_at", "hottest":"-answer_count", "mostvoted":"-score" }
95 questions=questions.order_by(view_dic.get(sort, '-added_at'))
98 "questions" : questions,
99 "questions_count" : questions.count(),
100 "tags_autocomplete" : _get_tags_cache_json(),
101 "list_description": list_description,
102 "base_path" : base_path,
107 if request.method == "GET" and "q" in request.GET:
108 keywords = request.GET.get("q")
109 search_type = request.GET.get("t")
112 return HttpResponseRedirect(reverse(index))
113 if search_type == 'tag':
114 return HttpResponseRedirect(reverse('tags') + '?q=%s' % (keywords.strip()))
115 elif search_type == "user":
116 return HttpResponseRedirect(reverse('users') + '?q=%s' % (keywords.strip()))
117 elif search_type == "question":
118 return question_search(request, keywords)
120 return render_to_response("search.html", context_instance=RequestContext(request))
122 @decorators.render('questions.html')
123 def question_search(request, keywords):
124 def question_search(keywords, orderby):
125 return Question.objects.filter(Q(title__icontains=keywords) | Q(html__icontains=keywords))
127 from forum.modules import get_handler
129 question_search = get_handler('question_search', question_search)
130 initial = question_search(keywords)
132 return question_list(request, initial, _("questions matching '%(keywords)s'") % {'keywords': keywords},
133 base_path="%s?t=question&q=%s" % (reverse('search'), django_urlquote(keywords)))
136 def tags(request):#view showing a listing of available tags - plain list
139 sortby = request.GET.get('sort', 'used')
141 page = int(request.GET.get('page', '1'))
145 if request.method == "GET":
146 stag = request.GET.get("q", "").strip()
148 objects_list = Paginator(Tag.objects.filter(deleted=False).exclude(used_count=0).extra(where=['name like %s'], params=['%' + stag + '%']), DEFAULT_PAGE_SIZE)
151 objects_list = Paginator(Tag.objects.all().filter(deleted=False).exclude(used_count=0).order_by("name"), DEFAULT_PAGE_SIZE)
153 objects_list = Paginator(Tag.objects.all().filter(deleted=False).exclude(used_count=0).order_by("-used_count"), DEFAULT_PAGE_SIZE)
156 tags = objects_list.page(page)
157 except (EmptyPage, InvalidPage):
158 tags = objects_list.page(objects_list.num_pages)
160 return render_to_response('tags.html', {
166 'is_paginated' : is_paginated,
167 'pages': objects_list.num_pages,
169 'has_previous': tags.has_previous(),
170 'has_next': tags.has_next(),
171 'previous': tags.previous_page_number(),
172 'next': tags.next_page_number(),
173 'base_url' : reverse('tags') + '?sort=%s&' % sortby
175 }, context_instance=RequestContext(request))
177 def get_answer_sort_order(request):
178 view_dic = {"latest":"-added_at", "oldest":"added_at", "votes":"-score" }
180 view_id = request.GET.get('sort', request.session.get('answer_sort_order', None))
182 if view_id is None or not view_id in view_dic:
185 if view_id != request.session.get('answer_sort_order', None):
186 request.session['answer_sort_order'] = view_id
188 return (view_id, view_dic[view_id])
190 def update_question_view_times(request, question):
191 if not 'question_view_times' in request.session:
192 request.session['question_view_times'] = {}
194 last_seen = request.session['question_view_times'].get(question.id,None)
195 updated_when, updated_who = question.get_last_update_info()
197 if not last_seen or last_seen < updated_when:
198 question.view_count = question.view_count + 1
199 question_view.send(sender=update_question_view_times, instance=question, user=request.user)
201 request.session['question_view_times'][question.id] = datetime.datetime.now()
203 def question(request, id, slug):
204 question = get_object_or_404(Question, id=id)
206 if slug != urlquote(slugify(question.title)):
207 return HttpResponseRedirect(question.get_absolute_url())
209 page = int(request.GET.get('page', 1))
210 view_id, order_by = get_answer_sort_order(request)
212 if question.deleted and not request.user.can_view_deleted_post(question):
215 answer_form = AnswerForm(question,request.user)
216 answers = request.user.get_visible_answers(question)
218 if answers is not None:
219 answers = [a for a in answers.order_by("-accepted", order_by)
220 if not a.deleted or a.author == request.user]
222 objects_list = Paginator(answers, ANSWERS_PAGE_SIZE)
223 page_objects = objects_list.page(page)
225 update_question_view_times(request, question)
227 if request.user.is_authenticated():
229 subscription = QuestionSubscription.objects.get(question=question, user=request.user)
235 return render_to_response('question.html', {
236 "question" : question,
237 "answer" : answer_form,
238 "answers" : page_objects.object_list,
239 "tags" : question.tags.all(),
241 "similar_questions" : question.get_related_questions(),
242 "subscription": subscription,
244 'is_paginated' : True,
245 'pages': objects_list.num_pages,
247 'has_previous': page_objects.has_previous(),
248 'has_next': page_objects.has_next(),
249 'previous': page_objects.previous_page_number(),
250 'next': page_objects.next_page_number(),
251 'base_url' : request.path + '?sort=%s&' % view_id,
252 'extend_url' : "#sort-top"
254 }, context_instance=RequestContext(request))
257 QUESTION_REVISION_TEMPLATE = ('<h1>%(title)s</h1>\n'
258 '<div class="text">%(html)s</div>\n'
259 '<div class="tags">%(tags)s</div>')
260 def question_revisions(request, id):
261 post = get_object_or_404(Question, id=id)
262 revisions = list(post.revisions.all())
264 for i, revision in enumerate(revisions):
265 revision.html = QUESTION_REVISION_TEMPLATE % {
266 'title': revision.title,
267 'html': sanitize_html(markdowner.convert(revision.text)),
268 'tags': ' '.join(['<a class="post-tag">%s</a>' % tag
269 for tag in revision.tagnames.split(' ')]),
272 revisions[i].diff = htmldiff(revisions[i-1].html, revision.html)
274 revisions[i].diff = QUESTION_REVISION_TEMPLATE % {
275 'title': revisions[0].title,
276 'html': sanitize_html(markdowner.convert(revisions[0].text)),
277 'tags': ' '.join(['<a class="post-tag">%s</a>' % tag
278 for tag in revisions[0].tagnames.split(' ')]),
280 revisions[i].summary = _('initial version')
281 return render_to_response('revisions_question.html', {
283 'revisions': revisions,
284 }, context_instance=RequestContext(request))
286 ANSWER_REVISION_TEMPLATE = ('<div class="text">%(html)s</div>')
287 def answer_revisions(request, id):
288 post = get_object_or_404(Answer, id=id)
289 revisions = list(post.revisions.all())
291 for i, revision in enumerate(revisions):
292 revision.html = ANSWER_REVISION_TEMPLATE % {
293 'html': sanitize_html(markdowner.convert(revision.text))
296 revisions[i].diff = htmldiff(revisions[i-1].html, revision.html)
298 revisions[i].diff = revisions[i].text
299 revisions[i].summary = _('initial version')
300 return render_to_response('revisions_answer.html', {
302 'revisions': revisions,
303 }, context_instance=RequestContext(request))