]> git.openstreetmap.org Git - osqa.git/blob - forum/views/meta.py
Merge pull request #46 from udacity/subfolder_fixes
[osqa.git] / forum / views / meta.py
1 import os
2 from itertools import groupby
3
4 from django.shortcuts import render_to_response
5 from django.template import RequestContext
6 from django.http import HttpResponseRedirect, HttpResponse
7 from django.views.static import serve
8 from django.views.decorators.cache import cache_page
9 from django.utils.translation import ugettext as _
10 from django.utils.safestring import mark_safe
11
12 from django.contrib import messages
13
14 from forum import settings
15 from forum.views.decorators import login_required
16 from forum.forms import FeedbackForm
17 from forum.modules import decorate
18 from forum.forms import get_next_url
19 from forum.models import Badge, Award, User, Page
20 from forum.http_responses import HttpResponseNotFound, HttpResponseIntServerError
21 from forum.utils.mail import send_template_email
22 from forum.templatetags.extra_filters import or_preview
23
24 import decorators
25 import logging, traceback
26
27 def favicon(request):
28     return HttpResponseRedirect(str(settings.APP_FAVICON))
29
30 def custom_css(request):
31     return HttpResponse(or_preview(settings.CUSTOM_CSS, request), mimetype="text/css")
32
33 def static(request, title, content):
34     return render_to_response('static.html', {'content' : content, 'title': title},
35                               context_instance=RequestContext(request))
36
37 def media(request, skin, path):
38     response = serve(request, "%s/media/%s" % (skin, path),
39                  document_root=os.path.join(os.path.dirname(os.path.dirname(__file__)), 'skins').replace('\\', '/'))
40     content_type = response.get('Content-Type', '')
41     if ('charset=' not in content_type):
42         if (content_type.startswith('text') or content_type=='application/x-javascript'):
43             content_type += '; charset=utf-8'
44             response['Content-Type'] = content_type
45     return response
46
47
48 def markdown_help(request):
49     return render_to_response('markdown_help.html', context_instance=RequestContext(request))
50
51 @cache_page(60 * 60 * 24 * 30) #30 days
52 def opensearch(request):
53     return render_to_response('opensearch.html', {'settings' : settings}, context_instance=RequestContext(request))
54
55
56 def feedback(request):
57     if request.method == "POST":
58         form = FeedbackForm(request.user, data=request.POST)
59         if form.is_valid():
60             context = {
61                  'user': request.user,
62                  'email': request.user.is_authenticated() and request.user.email or form.cleaned_data.get('email', None),
63                  'message': form.cleaned_data['message'],
64                  'name': request.user.is_authenticated() and request.user.username or form.cleaned_data.get('name', None),
65                  'ip': request.META['REMOTE_ADDR'],
66             }
67
68             recipients = User.objects.filter(is_superuser=True)
69             send_template_email(recipients, "notifications/feedback.html", context)
70
71             msg = _('Thanks for the feedback!')
72             messages.info(request, msg)
73             return HttpResponseRedirect(get_next_url(request))
74     else:
75         form = FeedbackForm(request.user, initial={'next':get_next_url(request)})
76
77     return render_to_response('feedback.html', {'form': form}, context_instance=RequestContext(request))
78
79 feedback.CANCEL_MESSAGE=_('We look forward to hearing your feedback! Please, give it next time :)')
80
81 def privacy(request):
82     return render_to_response('privacy.html', context_instance=RequestContext(request))
83
84 @decorate.withfn(login_required)
85 def logout(request):
86     return render_to_response('logout.html', {
87     'next' : get_next_url(request),
88     }, context_instance=RequestContext(request))
89
90 @decorators.render('badges.html', 'badges', _('badges'), weight=300)
91 def badges(request):
92     from forum.badges.base import BadgesMeta
93     badges = sorted([Badge.objects.get(id=id) for id in BadgesMeta.by_id.keys()], lambda b1, b2: cmp(b1.name, b2.name))
94
95     if request.user.is_authenticated():
96         my_badges = Award.objects.filter(user=request.user).values_list('badge_id', flat=True).distinct()
97     else:
98         my_badges = []
99
100     return {
101         'badges' : badges,
102         'mybadges' : my_badges,
103     }
104
105 def badge(request, id, slug):
106     badge = Badge.objects.get(id=id)
107     awards = list(Award.objects.filter(badge=badge).order_by('user', 'awarded_at'))
108     award_count = len(awards)
109
110     awards = sorted([dict(count=len(list(g)), user=k) for k, g in groupby(awards, lambda a: a.user)],
111                     lambda c1, c2: c2['count'] - c1['count'])
112
113     return render_to_response('badge.html', {
114     'award_count': award_count,
115     'awards' : awards,
116     'badge' : badge,
117     }, context_instance=RequestContext(request))
118
119 def page(request):
120     path = request.path[1:]
121
122     if path in settings.STATIC_PAGE_REGISTRY:
123         try:
124             page = Page.objects.get(id=settings.STATIC_PAGE_REGISTRY[path])
125
126             if (not page.published) and (not request.user.is_superuser):
127                 return HttpResponseNotFound(request)
128         except:
129             return HttpResponseNotFound(request)
130     else:
131         return HttpResponseNotFound(request)
132
133     template = page.extra.get('template', 'default')
134     sidebar = page.extra.get('sidebar', '')
135
136     if template == 'default':
137         base = 'base_content.html'
138     elif template == 'sidebar':
139         base = 'base.html'
140
141         sidebar_render = page.extra.get('render', 'markdown')
142
143         if sidebar_render == 'markdown':
144             sidebar = page._as_markdown(sidebar)
145         elif sidebar_render == 'html':
146             sidebar = mark_safe(sidebar)
147
148     else:
149         return HttpResponse(page.body, mimetype=page.extra.get('mimetype', 'text/html'))
150
151     render = page.extra.get('render', 'markdown')
152
153     if render == 'markdown':
154         body = page.as_markdown()
155     elif render == 'html':
156         body = mark_safe(page.body)
157     else:
158         body = page.body
159
160     return render_to_response('page.html', {
161     'page' : page,
162     'body' : body,
163     'sidebar': sidebar,
164     'base': base,
165     }, context_instance=RequestContext(request))
166
167
168 def error_handler(request):
169
170     stacktrace = "".join(["\t\t%s\n" % l for l in traceback.format_exc().split("\n")])
171
172     try:
173         log_msg = """
174         error executing request:
175         PATH: %(path)s
176         USER: %(user)s
177         METHOD: %(method)s
178         POST PARAMETERS:
179         %(post)s
180         GET PARAMETERS:
181         %(get)s
182         HTTP HEADERS:
183         %(headers)s
184         COOKIES:
185         %(cookies)s
186         EXCEPTION INFO:
187         %(stacktrace)s
188         """ % {
189             'path': request.path,
190             'user': request.user.is_authenticated() and ("%s (%s)" % (request.user.username, request.user.id)) or "<anonymous>",
191             'method': request.method,
192             'post': request.POST and "".join(["\t\t%s: %s\n" % (k, v) for k, v in request.POST.items()]) or "None",
193             'get': request.GET and "".join(["\t\t%s: %s\n" % (k, v) for k, v in request.GET.items()]) or "None",
194             'cookies': request.COOKIES and "".join(["\t\t%s: %s\n" % (k, v) for k, v in request.COOKIES.items()]) or "None",
195             'headers': request.META and "".join(["\t\t%s: %s\n" % (k, v) for k, v in request.META.items()]) or "None",
196             'stacktrace': stacktrace
197         }
198     except:
199         log_msg = "error executing request:\n%s" % stacktrace
200
201
202     logging.error(log_msg)
203     return HttpResponseIntServerError(request)