]> git.openstreetmap.org Git - osqa.git/blobdiff - forum/views/meta.py
Improving the canned comments feature, now we can use Django style template syntax...
[osqa.git] / forum / views / meta.py
index 932c627a123d6b9637707395ccd3a6a86b96468a..8f924feb02e8589ef740dc5ae42e0e3134583e9e 100644 (file)
@@ -6,6 +6,9 @@ from django.template import RequestContext, loader
 from django.http import HttpResponseRedirect, HttpResponse, Http404
 from django.views.static import serve
 from forum import settings
 from django.http import HttpResponseRedirect, HttpResponse, Http404
 from django.views.static import serve
 from forum import settings
+from forum.modules import decorate
+from django.views.decorators.cache import cache_page
+from forum.views.decorators import login_required
 from forum.forms import FeedbackForm
 from django.core.urlresolvers import reverse
 from django.utils.translation import ugettext as _
 from forum.forms import FeedbackForm
 from django.core.urlresolvers import reverse
 from django.utils.translation import ugettext as _
@@ -13,11 +16,13 @@ from django.db.models import Count
 from forum.forms import get_next_url
 from forum.models import Badge, Award, User, Page
 from forum.badges.base import BadgesMeta
 from forum.forms import get_next_url
 from forum.models import Badge, Award, User, Page
 from forum.badges.base import BadgesMeta
+from forum.http_responses import HttpResponseNotFound, HttpResponseIntServerError
 from forum import settings
 from forum.utils.mail import send_template_email
 from django.utils.safestring import mark_safe
 from forum.templatetags.extra_filters import or_preview
 from forum import settings
 from forum.utils.mail import send_template_email
 from django.utils.safestring import mark_safe
 from forum.templatetags.extra_filters import or_preview
-import re
+import decorators
+import re, sys, logging, traceback
 
 def favicon(request):
     return HttpResponseRedirect(str(settings.APP_FAVICON))
 
 def favicon(request):
     return HttpResponseRedirect(str(settings.APP_FAVICON))
@@ -30,28 +35,35 @@ def static(request, title, content):
                               context_instance=RequestContext(request))
 
 def media(request, skin, path):
                               context_instance=RequestContext(request))
 
 def media(request, skin, path):
-    return serve(request, "%s/media/%s" % (skin, path),
+    response = serve(request, "%s/media/%s" % (skin, path),
                  document_root=os.path.join(os.path.dirname(os.path.dirname(__file__)), 'skins').replace('\\', '/'))
                  document_root=os.path.join(os.path.dirname(os.path.dirname(__file__)), 'skins').replace('\\', '/'))
+    content_type = response['Content-Type']
+    if ('charset=' not in content_type):
+        if (content_type.startswith('text') or content_type=='application/x-javascript'):
+            content_type += '; charset=utf-8'
+            response['Content-Type'] = content_type
+    return response
+
 
 def markdown_help(request):
     return render_to_response('markdown_help.html', context_instance=RequestContext(request))
 
 
 def markdown_help(request):
     return render_to_response('markdown_help.html', context_instance=RequestContext(request))
 
-
+@cache_page(60 * 60 * 24 * 30) #30 days
 def opensearch(request):
     return render_to_response('opensearch.html', {'settings' : settings}, context_instance=RequestContext(request))
 
 
 def feedback(request):
     if request.method == "POST":
 def opensearch(request):
     return render_to_response('opensearch.html', {'settings' : settings}, context_instance=RequestContext(request))
 
 
 def feedback(request):
     if request.method == "POST":
-        form = FeedbackForm(request.POST)
+        form = FeedbackForm(request.user, data=request.POST)
         if form.is_valid():
         if form.is_valid():
-            context = {'user': request.user}
-
-            if not request.user.is_authenticated:
-                context['email'] = form.cleaned_data.get('email', None)
-            context['message'] = form.cleaned_data['message']
-            context['name'] = form.cleaned_data.get('name', None)
-            context['ip'] = request.META['REMOTE_ADDR']
+            context = {
+                 'user': request.user,
+                 'email': request.user.is_authenticated() and request.user.email or form.cleaned_data.get('email', None),
+                 'message': form.cleaned_data['message'],
+                 'name': request.user.is_authenticated() and request.user.username or form.cleaned_data.get('name', None),
+                 'ip': request.META['REMOTE_ADDR'],
+            }
 
             recipients = User.objects.filter(is_superuser=True)
             send_template_email(recipients, "notifications/feedback.html", context)
 
             recipients = User.objects.filter(is_superuser=True)
             send_template_email(recipients, "notifications/feedback.html", context)
@@ -60,7 +72,7 @@ def feedback(request):
             request.user.message_set.create(message=msg)
             return HttpResponseRedirect(get_next_url(request))
     else:
             request.user.message_set.create(message=msg)
             return HttpResponseRedirect(get_next_url(request))
     else:
-        form = FeedbackForm(initial={'next':get_next_url(request)})
+        form = FeedbackForm(request.user, initial={'next':get_next_url(request)})
 
     return render_to_response('feedback.html', {'form': form}, context_instance=RequestContext(request))
 
 
     return render_to_response('feedback.html', {'form': form}, context_instance=RequestContext(request))
 
@@ -69,23 +81,25 @@ feedback.CANCEL_MESSAGE=_('We look forward to hearing your feedback! Please, giv
 def privacy(request):
     return render_to_response('privacy.html', context_instance=RequestContext(request))
 
 def privacy(request):
     return render_to_response('privacy.html', context_instance=RequestContext(request))
 
+@decorate.withfn(login_required)
 def logout(request):
     return render_to_response('logout.html', {
     'next' : get_next_url(request),
     }, context_instance=RequestContext(request))
 
 def logout(request):
     return render_to_response('logout.html', {
     'next' : get_next_url(request),
     }, context_instance=RequestContext(request))
 
+@decorators.render('badges.html', 'badges', _('badges'), weight=300)
 def badges(request):
 def badges(request):
-    badges = [b.ondb for b in sorted(BadgesMeta.by_id.values(), lambda b1, b2: cmp(b1.name, b2.name))]
+    badges = sorted([Badge.objects.get(id=id) for id in BadgesMeta.by_id.keys()], lambda b1, b2: cmp(b1.name, b2.name))
 
     if request.user.is_authenticated():
         my_badges = Award.objects.filter(user=request.user).values('badge_id').distinct()
     else:
         my_badges = []
 
 
     if request.user.is_authenticated():
         my_badges = Award.objects.filter(user=request.user).values('badge_id').distinct()
     else:
         my_badges = []
 
-    return render_to_response('badges.html', {
-    'badges' : badges,
-    'mybadges' : my_badges,
-    }, context_instance=RequestContext(request))
+    return {
+        'badges' : badges,
+        'mybadges' : my_badges,
+    }
 
 def badge(request, id, slug):
     badge = Badge.objects.get(id=id)
 
 def badge(request, id, slug):
     badge = Badge.objects.get(id=id)
@@ -101,17 +115,19 @@ def badge(request, id, slug):
     'badge' : badge,
     }, context_instance=RequestContext(request))
 
     'badge' : badge,
     }, context_instance=RequestContext(request))
 
-def page(request, path):
+def page(request):
+    path = request.path[1:]
+
     if path in settings.STATIC_PAGE_REGISTRY:
         try:
             page = Page.objects.get(id=settings.STATIC_PAGE_REGISTRY[path])
 
             if (not page.published) and (not request.user.is_superuser):
     if path in settings.STATIC_PAGE_REGISTRY:
         try:
             page = Page.objects.get(id=settings.STATIC_PAGE_REGISTRY[path])
 
             if (not page.published) and (not request.user.is_superuser):
-                raise Http404
+                return HttpResponseNotFound(request)
         except:
         except:
-            raise Http404
+            return HttpResponseNotFound(request)
     else:
     else:
-        raise Http404
+        return HttpResponseNotFound(request)
 
     template = page.extra.get('template', 'default')
     sidebar = page.extra.get('sidebar', '')
 
     template = page.extra.get('template', 'default')
     sidebar = page.extra.get('sidebar', '')
@@ -148,3 +164,39 @@ def page(request, path):
     }, context_instance=RequestContext(request))
 
 
     }, context_instance=RequestContext(request))
 
 
+def error_handler(request):
+
+    stacktrace = "".join(["\t\t%s\n" % l for l in traceback.format_exc().split("\n")])
+
+    try:
+        log_msg = """
+        error executing request:
+        PATH: %(path)s
+        USER: %(user)s
+        METHOD: %(method)s
+        POST PARAMETERS:
+        %(post)s
+        GET PARAMETERS:
+        %(get)s
+        HTTP HEADERS:
+        %(headers)s
+        COOKIES:
+        %(cookies)s
+        EXCEPTION INFO:
+        %(stacktrace)s
+        """ % {
+            'path': request.path,
+            'user': request.user.is_authenticated() and ("%s (%s)" % (request.user.username, request.user.id)) or "<anonymous>",
+            'method': request.method,
+            'post': request.POST and "".join(["\t\t%s: %s\n" % (k, v) for k, v in request.POST.items()]) or "None",
+            'get': request.GET and "".join(["\t\t%s: %s\n" % (k, v) for k, v in request.GET.items()]) or "None",
+            'cookies': request.COOKIES and "".join(["\t\t%s: %s\n" % (k, v) for k, v in request.COOKIES.items()]) or "None",
+            'headers': request.META and "".join(["\t\t%s: %s\n" % (k, v) for k, v in request.META.items()]) or "None",
+            'stacktrace': stacktrace
+        }
+    except:
+        log_msg = "error executing request:\n%s" % stacktrace
+
+
+    logging.error(log_msg)
+    return HttpResponseIntServerError(request)