]> git.openstreetmap.org Git - osqa.git/blob - forum/views/readers.py
Fixed OSQA-150: "tags pages" and "unanswered questions" pages have proper titles...
[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.utils.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, Question.objects.all(), sort='active', base_path=reverse('questions'))
47
48 @decorators.render('questions.html', 'unanswered')
49 def unanswered(request):
50     return question_list(request, Question.objects.filter(extra_ref=None),
51                          _('Open questions without an accepted answer'),
52                          'active', None, _("Unanswered questions"))
53
54 @decorators.render('questions.html', 'questions')
55 def questions(request):
56     return question_list(request, Question.objects.all(), _('questions'), 'active')
57
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}),
62                         'active', None, mark_safe(_('Questions tagged %(tag)s') % {'tag': tag}))
63
64 @decorators.list('questions', QUESTIONS_PAGE_SIZE)
65 def question_list(request, initial, list_description=_('questions'), sort=None, base_path=None, page_title=None):
66     questions = initial.filter(deleted=None, in_moderation=None)
67
68     if request.user.is_authenticated():
69         questions = questions.filter(
70                 ~Q(tags__id__in=request.user.marked_tags.filter(user_selections__reason='bad')))
71
72     if sort is not False:
73         if sort is None:
74             sort = request.utils.sort_method('latest')
75         else:
76             request.utils.set_sort_method(sort)
77
78         view_dic = {"latest":"-added_at", "active":"-last_activity_at", "hottest":"-extra_count", "mostvoted":"-score" }
79
80         questions=questions.order_by(view_dic.get(sort, '-added_at'))
81
82     if page_title is None:
83         page_title = _("Questions")
84         
85     return {
86         "questions" : questions,
87         "questions_count" : questions.count(),
88         #"tags_autocomplete" : _get_tags_cache_json(),
89         "list_description": list_description,
90         "base_path" : base_path,
91         "page_title" : page_title,
92         }
93
94
95 def search(request):
96     if request.method == "GET" and "q" in request.GET:
97         keywords = request.GET.get("q")
98         search_type = request.GET.get("t")
99         
100         if not keywords:
101             return HttpResponseRedirect(reverse(index))
102         if search_type == 'tag':
103             return HttpResponseRedirect(reverse('tags') + '?q=%s' % (keywords.strip()))
104         elif search_type == "user":
105             return HttpResponseRedirect(reverse('users') + '?q=%s' % (keywords.strip()))
106         elif search_type == "question":
107             return question_search(request, keywords)
108     else:
109         return render_to_response("search.html", context_instance=RequestContext(request))
110
111 @decoratable
112 def do_question_search(keywords):
113     return Question.objects.filter(Q(title__icontains=keywords) | Q(body__icontains=keywords))
114
115 @decorators.render('questions.html')
116 def question_search(request, keywords):
117     initial = do_question_search(keywords)
118
119     return question_list(request, initial, _("questions matching '%(keywords)s'") % {'keywords': keywords},
120             base_path="%s?t=question&q=%s" % (reverse('search'), django_urlquote(keywords)), sort=False)
121     
122
123 def tags(request):#view showing a listing of available tags - plain list
124     stag = ""
125     is_paginated = True
126     sortby = request.GET.get('sort', 'used')
127     try:
128         page = int(request.GET.get('page', '1'))
129     except ValueError:
130         page = 1
131
132     if request.method == "GET":
133         stag = request.GET.get("q", "").strip()
134         if stag != '':
135             objects_list = Paginator(Tag.objects.filter(deleted=False).exclude(used_count=0).extra(where=['name like %s'], params=['%' + stag + '%']), DEFAULT_PAGE_SIZE)
136         else:
137             if sortby == "name":
138                 objects_list = Paginator(Tag.objects.all().filter(deleted=False).exclude(used_count=0).order_by("name"), DEFAULT_PAGE_SIZE)
139             else:
140                 objects_list = Paginator(Tag.objects.all().filter(deleted=False).exclude(used_count=0).order_by("-used_count"), DEFAULT_PAGE_SIZE)
141
142     try:
143         tags = objects_list.page(page)
144     except (EmptyPage, InvalidPage):
145         tags = objects_list.page(objects_list.num_pages)
146
147     return render_to_response('tags.html', {
148                                             "tags" : tags,
149                                             "stag" : stag,
150                                             "tab_id" : sortby,
151                                             "keywords" : stag,
152                                             "context" : {
153                                                 'is_paginated' : is_paginated,
154                                                 'pages': objects_list.num_pages,
155                                                 'page': page,
156                                                 'has_previous': tags.has_previous(),
157                                                 'has_next': tags.has_next(),
158                                                 'previous': tags.previous_page_number(),
159                                                 'next': tags.next_page_number(),
160                                                 'base_url' : reverse('tags') + '?sort=%s&' % sortby
161                                             }
162                                 }, context_instance=RequestContext(request))
163
164 def get_answer_sort_order(request):
165     view_dic = {"latest":"-added_at", "oldest":"added_at", "votes":"-score" }
166
167     view_id = request.GET.get('sort', request.session.get('answer_sort_order', None))
168
169     if view_id is None or not view_id in view_dic:
170         view_id = "votes"
171
172     if view_id != request.session.get('answer_sort_order', None):
173         request.session['answer_sort_order'] = view_id
174
175     return (view_id, view_dic[view_id])
176
177 def update_question_view_times(request, question):
178     if not 'last_seen_in_question' in request.session:
179         request.session['last_seen_in_question'] = {}
180
181     last_seen = request.session['last_seen_in_question'].get(question.id,None)
182
183     if (not last_seen) or last_seen < question.last_activity_at:
184         QuestionViewAction(question, request.user, ip=request.META['REMOTE_ADDR']).save()
185         request.session['last_seen_in_question'][question.id] = datetime.datetime.now()
186
187     request.session['last_seen_in_question'][question.id] = datetime.datetime.now()
188
189 def match_question_slug(slug):
190     slug_words = slug.split('-')
191     qs = Question.objects.filter(node_type="question", title__istartswith=slug_words[0])
192
193     for q in qs:
194         if slug == urlquote(slugify(q.title)):
195             return q
196
197     return None
198
199 def question(request, id, slug):
200     try:
201         question = Question.objects.get(node_type="question", id=id)
202     except:
203         question = match_question_slug(slug)
204         if question is not None:
205             return HttpResponsePermanentRedirect(question.get_absolute_url())
206         else:
207             raise Http404()
208
209     if slug != urlquote(slugify(question.title)):
210         return HttpResponsePermanentRedirect(question.get_absolute_url())
211
212     page = int(request.GET.get('page', 1))
213     view_id, order_by = get_answer_sort_order(request)
214
215     if question.deleted and not request.user.can_view_deleted_post(question):
216         raise Http404
217
218     answer_form = AnswerForm(question)
219     answers = request.user.get_visible_answers(question)
220
221     if answers is not None:
222         answers = [a for a in answers.order_by("-marked", order_by)
223                    if not a.deleted or a.author == request.user]
224
225     objects_list = Paginator(answers, ANSWERS_PAGE_SIZE)
226     page_objects = objects_list.page(page)
227
228     update_question_view_times(request, question)
229
230     if request.user.is_authenticated():
231         try:
232             subscription = QuestionSubscription.objects.get(question=question, user=request.user)
233         except:
234             subscription = False
235     else:
236         subscription = False
237
238     return render_to_response('question.html', {
239         "question" : question,
240         "answer" : answer_form,
241         "answers" : page_objects.object_list,
242         "tab_id" : view_id,
243         "similar_questions" : question.get_related_questions(),
244         "subscription": subscription,
245         "context" : {
246             'is_paginated' : True,
247             'pages': objects_list.num_pages,
248             'page': page,
249             'has_previous': page_objects.has_previous(),
250             'has_next': page_objects.has_next(),
251             'previous': page_objects.previous_page_number(),
252             'next': page_objects.next_page_number(),
253             'base_url' : request.path + '?sort=%s&' % view_id,
254             'extend_url' : "#sort-top"
255         }
256         }, context_instance=RequestContext(request))
257
258
259 REVISION_TEMPLATE = template.loader.get_template('node/revision.html')
260
261 def revisions(request, id):
262     post = get_object_or_404(Node, id=id).leaf
263     revisions = list(post.revisions.order_by('revised_at'))
264
265     rev_ctx = []
266
267     for i, revision in enumerate(revisions):
268         rev_ctx.append(dict(inst=revision, html=REVISION_TEMPLATE.render(template.Context({
269                 'title': revision.title,
270                 'html': revision.html,
271                 'tags': revision.tagname_list(),
272         }))))
273
274         if i > 0:
275             rev_ctx[i]['diff'] = mark_safe(htmldiff(rev_ctx[i-1]['html'], rev_ctx[i]['html']))
276         else:
277             rev_ctx[i]['diff'] = mark_safe(rev_ctx[i]['html'])
278
279         if not (revision.summary):
280             rev_ctx[i]['summary'] = _('Revision n. %(rev_number)d') % {'rev_number': revision.revision}
281         else:
282             rev_ctx[i]['summary'] = revision.summary
283             
284     return render_to_response('revisions.html', {
285                               'post': post,
286                               'revisions': rev_ctx,
287                               }, context_instance=RequestContext(request))
288
289
290