]> git.openstreetmap.org Git - osqa.git/blob - forum/views/meta.py
OSQA-720, changing the WMD markdown editor, applying patches that resolve issues...
[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 django.views.decorators.cache import cache_page
11 from forum.views.decorators import login_required
12 from forum.forms import FeedbackForm
13 from django.core.urlresolvers import reverse
14 from django.utils.translation import ugettext as _
15 from django.db.models import Count
16 from forum.forms import get_next_url
17 from forum.models import Badge, Award, User, Page
18 from forum.badges.base import BadgesMeta
19 from forum.http_responses import HttpResponseNotFound, HttpResponseIntServerError
20 from forum import settings
21 from forum.utils.mail import send_template_email
22 from django.utils.safestring import mark_safe
23 from forum.templatetags.extra_filters import or_preview
24 import decorators
25 import re, sys, 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['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             request.user.message_set.create(message=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     badges = sorted([Badge.objects.get(id=id) for id in BadgesMeta.by_id.keys()], lambda b1, b2: cmp(b1.name, b2.name))
93
94     if request.user.is_authenticated():
95         my_badges = Award.objects.filter(user=request.user).values('badge_id').distinct()
96     else:
97         my_badges = []
98
99     return {
100         'badges' : badges,
101         'mybadges' : my_badges,
102     }
103
104 def badge(request, id, slug):
105     badge = Badge.objects.get(id=id)
106     awards = list(Award.objects.filter(badge=badge).order_by('user', 'awarded_at'))
107     award_count = len(awards)
108
109     awards = sorted([dict(count=len(list(g)), user=k) for k, g in groupby(awards, lambda a: a.user)],
110                     lambda c1, c2: c2['count'] - c1['count'])
111
112     return render_to_response('badge.html', {
113     'award_count': award_count,
114     'awards' : awards,
115     'badge' : badge,
116     }, context_instance=RequestContext(request))
117
118 def page(request):
119     path = request.path[1:]
120
121     if path in settings.STATIC_PAGE_REGISTRY:
122         try:
123             page = Page.objects.get(id=settings.STATIC_PAGE_REGISTRY[path])
124
125             if (not page.published) and (not request.user.is_superuser):
126                 return HttpResponseNotFound(request)
127         except:
128             return HttpResponseNotFound(request)
129     else:
130         return HttpResponseNotFound(request)
131
132     template = page.extra.get('template', 'default')
133     sidebar = page.extra.get('sidebar', '')
134
135     if template == 'default':
136         base = 'base_content.html'
137     elif template == 'sidebar':
138         base = 'base.html'
139
140         sidebar_render = page.extra.get('render', 'markdown')
141
142         if sidebar_render == 'markdown':
143             sidebar = page._as_markdown(sidebar)
144         elif sidebar_render == 'html':
145             sidebar = mark_safe(sidebar)
146
147     else:
148         return HttpResponse(page.body, mimetype=page.extra.get('mimetype', 'text/html'))
149
150     render = page.extra.get('render', 'markdown')
151
152     if render == 'markdown':
153         body = page.as_markdown()
154     elif render == 'html':
155         body = mark_safe(page.body)
156     else:
157         body = page.body
158
159     return render_to_response('page.html', {
160     'page' : page,
161     'body' : body,
162     'sidebar': sidebar,
163     'base': base,
164     }, context_instance=RequestContext(request))
165
166
167 def error_handler(request):
168
169     stacktrace = "".join(["\t\t%s\n" % l for l in traceback.format_exc().split("\n")])
170
171     try:
172         log_msg = """
173         error executing request:
174         PATH: %(path)s
175         USER: %(user)s
176         METHOD: %(method)s
177         POST PARAMETERS:
178         %(post)s
179         GET PARAMETERS:
180         %(get)s
181         HTTP HEADERS:
182         %(headers)s
183         COOKIES:
184         %(cookies)s
185         EXCEPTION INFO:
186         %(stacktrace)s
187         """ % {
188             'path': request.path,
189             'user': request.user.is_authenticated() and ("%s (%s)" % (request.user.username, request.user.id)) or "<anonymous>",
190             'method': request.method,
191             'post': request.POST and "".join(["\t\t%s: %s\n" % (k, v) for k, v in request.POST.items()]) or "None",
192             'get': request.GET and "".join(["\t\t%s: %s\n" % (k, v) for k, v in request.GET.items()]) or "None",
193             'cookies': request.COOKIES and "".join(["\t\t%s: %s\n" % (k, v) for k, v in request.COOKIES.items()]) or "None",
194             'headers': request.META and "".join(["\t\t%s: %s\n" % (k, v) for k, v in request.META.items()]) or "None",
195             'stacktrace': stacktrace
196         }
197     except:
198         log_msg = "error executing request:\n%s" % stacktrace
199
200
201     logging.error(log_msg)
202     return HttpResponseIntServerError(request)