]> git.openstreetmap.org Git - osqa.git/blob - forum/views/readers.py
changed these files to use blocktrans instead.
[osqa.git] / forum / views / readers.py
1 # encoding:utf-8   
2 import datetime
3 import logging
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
22
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.forms import get_next_url
28 from forum.actions import QuestionViewAction
29 from forum.modules.decorators import decoratable
30 import decorators
31
32 # used in index page
33 #refactor - move these numbers somewhere?
34 INDEX_PAGE_SIZE = 30
35 INDEX_AWARD_SIZE = 15
36 INDEX_TAGS_SIZE = 25
37 # used in tags list
38 DEFAULT_PAGE_SIZE = 60
39 # used in questions
40 QUESTIONS_PAGE_SIZE = 30
41 # used in answers
42 ANSWERS_PAGE_SIZE = 10
43
44 @decorators.render('index.html')
45 def index(request):
46     return question_list(request,
47                          Question.objects.all(),
48                          sort=request.utils.set_sort_method('active'),
49                          base_path=reverse('questions'))
50
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'),
57                          None,
58                          _("Unanswered questions"))
59
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'))
63
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'),
70                          None,
71                          mark_safe(_('questions tagged %(tag)s') % {'tag': tag}),
72                          False)
73
74 @decorators.list('questions', QUESTIONS_PAGE_SIZE)
75 def question_list(request, initial, list_description=_('questions'), sort=None, base_path=None, page_title=None,
76                   allowIgnoreTags=True):
77     questions = initial.filter_state(deleted=False)
78
79     if request.user.is_authenticated() and allowIgnoreTags:
80         questions = questions.filter(~Q(tags__id__in = request.user.marked_tags.filter(user_selections__reason = 'bad'))
81                                      )
82
83     if sort is not False:
84         if sort is None:
85             sort = request.utils.sort_method('latest')
86         else:
87             request.utils.set_sort_method(sort)
88
89         view_dic = {"latest":"-added_at", "active":"-last_activity_at", "hottest":"-extra_count", "mostvoted":"-score" }
90
91         questions=questions.order_by(view_dic.get(sort, '-added_at'))
92
93     if page_title is None:
94         page_title = _("Questions")
95
96     keywords =  ""
97     if request.GET.get("q"):
98         keywords = request.GET.get("q").strip()
99
100     answer_count = Answer.objects.filter_state(deleted=False).filter(parent__in=questions).count()
101     answer_description = _("answers")
102
103     return {
104     "questions" : questions,
105     "questions_count" : questions.count(),
106     "answer_count" : answer_count,
107     "keywords" : keywords,
108     #"tags_autocomplete" : _get_tags_cache_json(),
109     "list_description": list_description,
110     "answer_description": answer_description,
111     "base_path" : base_path,
112     "page_title" : page_title,
113     "tab" : "questions",
114     }
115
116
117 def search(request):
118     if request.method == "GET" and "q" in request.GET:
119         keywords = request.GET.get("q")
120         search_type = request.GET.get("t")
121
122         if not keywords:
123             return HttpResponseRedirect(reverse(index))
124         if search_type == 'tag':
125             return HttpResponseRedirect(reverse('tags') + '?q=%s' % urlquote(keywords.strip()))
126         elif search_type == "user":
127             return HttpResponseRedirect(reverse('users') + '?q=%s' % urlquote(keywords.strip()))
128         elif search_type == "question":
129             return question_search(request, keywords)
130     else:
131         return render_to_response("search.html", context_instance=RequestContext(request))
132
133 @decorators.render('questions.html')
134 def question_search(request, keywords):
135     initial = Question.objects.search(keywords)
136
137     return question_list(request, initial, _("questions matching '%(keywords)s'") % {'keywords': keywords},
138                          base_path="%s?t=question&q=%s" % (reverse('search'), django_urlquote(keywords)), sort=False)
139
140
141 def tags(request):#view showing a listing of available tags - plain list
142     stag = ""
143     is_paginated = True
144     sortby = request.GET.get('sort', 'used')
145     try:
146         page = int(request.GET.get('page', '1'))
147     except ValueError:
148         page = 1
149
150     if request.method == "GET":
151         stag = request.GET.get("q", "").strip()
152         if stag != '':
153             objects_list = Paginator(Tag.active.filter(name__contains=stag), DEFAULT_PAGE_SIZE)
154         else:
155             if sortby == "name":
156                 objects_list = Paginator(Tag.active.order_by("name"), DEFAULT_PAGE_SIZE)
157             else:
158                 objects_list = Paginator(Tag.active.order_by("-used_count"), DEFAULT_PAGE_SIZE)
159
160     try:
161         tags = objects_list.page(page)
162     except (EmptyPage, InvalidPage):
163         tags = objects_list.page(objects_list.num_pages)
164
165     return render_to_response('tags.html', {
166     "tags" : tags,
167     "stag" : stag,
168     "tab_id" : sortby,
169     "keywords" : stag,
170     "context" : {
171     'is_paginated' : is_paginated,
172     'pages': objects_list.num_pages,
173     'page': page,
174     'has_previous': tags.has_previous(),
175     'has_next': tags.has_next(),
176     'previous': tags.previous_page_number(),
177     'next': tags.next_page_number(),
178     'base_url' : reverse('tags') + '?sort=%s&' % sortby
179     }
180     }, context_instance=RequestContext(request))
181
182 def get_answer_sort_order(request):
183     view_dic = {"latest":"-added_at", "oldest":"added_at", "votes":"-score" }
184
185     view_id = request.GET.get('sort', request.session.get('answer_sort_order', None))
186
187     if view_id is None or not view_id in view_dic:
188         view_id = "votes"
189
190     if view_id != request.session.get('answer_sort_order', None):
191         request.session['answer_sort_order'] = view_id
192
193     return (view_id, view_dic[view_id])
194
195 def update_question_view_times(request, question):
196     if not 'last_seen_in_question' in request.session:
197         request.session['last_seen_in_question'] = {}
198
199     last_seen = request.session['last_seen_in_question'].get(question.id, None)
200
201     if (not last_seen) or last_seen < question.last_activity_at:
202         QuestionViewAction(question, request.user, ip=request.META['REMOTE_ADDR']).save()
203         request.session['last_seen_in_question'][question.id] = datetime.datetime.now()
204
205     request.session['last_seen_in_question'][question.id] = datetime.datetime.now()
206
207 def match_question_slug(slug):
208     slug_words = slug.split('-')
209     qs = Question.objects.filter(title__istartswith=slug_words[0])
210
211     for q in qs:
212         if slug == urlquote(slugify(q.title)):
213             return q
214
215     return None
216
217 def question(request, id, slug):
218     try:
219         question = Question.objects.get(id=id)
220     except:
221         if slug:
222             question = match_question_slug(slug)
223             if question is not None:
224                 return HttpResponsePermanentRedirect(question.get_absolute_url())
225
226         raise Http404()
227
228     page = int(request.GET.get('page', 1))
229     view_id, order_by = get_answer_sort_order(request)
230
231     if question.nis.deleted and not request.user.can_view_deleted_post(question):
232         raise Http404
233
234     if request.POST:
235         answer_form = AnswerForm(question, request.POST)
236     else:
237         answer_form = AnswerForm(question)
238
239     answers = request.user.get_visible_answers(question)
240
241     if answers is not None:
242         answers = [a for a in answers.order_by("-marked", order_by)
243                    if not a.nis.deleted or a.author == request.user]
244
245     objects_list = Paginator(answers, ANSWERS_PAGE_SIZE)
246     page_objects = objects_list.page(page)
247
248     update_question_view_times(request, question)
249
250     if request.user.is_authenticated():
251         try:
252             subscription = QuestionSubscription.objects.get(question=question, user=request.user)
253         except:
254             subscription = False
255     else:
256         subscription = False
257
258     return render_to_response('question.html', {
259     "question" : question,
260     "answer" : answer_form,
261     "answers" : page_objects.object_list,
262     "tab_id" : view_id,
263     "similar_questions" : question.get_related_questions(),
264     "subscription": subscription,
265     "context" : {
266     'is_paginated' : True,
267     'pages': objects_list.num_pages,
268     'page': page,
269     'has_previous': page_objects.has_previous(),
270     'has_next': page_objects.has_next(),
271     'previous': page_objects.previous_page_number(),
272     'next': page_objects.next_page_number(),
273     'base_url' : request.path + '?sort=%s&' % view_id,
274     'extend_url' : "#sort-top"
275     }
276     }, context_instance=RequestContext(request))
277
278
279 REVISION_TEMPLATE = template.loader.get_template('node/revision.html')
280
281 def revisions(request, id):
282     post = get_object_or_404(Node, id=id).leaf
283     revisions = list(post.revisions.order_by('revised_at'))
284
285     rev_ctx = []
286
287     for i, revision in enumerate(revisions):
288         rev_ctx.append(dict(inst=revision, html=REVISION_TEMPLATE.render(template.Context({
289         'title': revision.title,
290         'html': revision.html,
291         'tags': revision.tagname_list(),
292         }))))
293
294         if i > 0:
295             rev_ctx[i]['diff'] = mark_safe(htmldiff(rev_ctx[i-1]['html'], rev_ctx[i]['html']))
296         else:
297             rev_ctx[i]['diff'] = mark_safe(rev_ctx[i]['html'])
298
299         if not (revision.summary):
300             rev_ctx[i]['summary'] = _('Revision n. %(rev_number)d') % {'rev_number': revision.revision}
301         else:
302             rev_ctx[i]['summary'] = revision.summary
303
304     return render_to_response('revisions.html', {
305     'post': post,
306     'revisions': rev_ctx,
307     }, context_instance=RequestContext(request))
308
309
310