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