1.3
[auf_django_piwik.git] / auf / django / piwik / middleware.py
1 # -*- coding: utf-8 -*-
2
3 import re
4
5 from django.conf import settings
6
7 from settings import PIWIK_TOKEN, PIWIK_HOST, PIWIK_HTTPFORCE,\
8 PIWIK_TRACKCODE, PIWIK_EXCLUDE_REFERER
9
10 ire_body = re.compile(re.escape('</body>'), re.IGNORECASE)
11
12
13 class TrackMiddleware:
14
15 def process_response(self, request, response):
16 """
17 Trackcode injection avant le body s'il y a un token piwik dans la conf
18 locale.
19 """
20 if PIWIK_TOKEN is None:
21 return response
22
23 http_referer = request.META.get('HTTP_REFERER', "")
24 referer = http_referer
25
26 for excl in PIWIK_EXCLUDE_REFERER:
27 if excl in http_referer:
28 referer = ""
29 break
30
31 if request.is_secure() and not PIWIK_HTTPFORCE:
32 protocol = "https"
33 else:
34 protocol = "http"
35
36 track = PIWIK_TRACKCODE % {
37 'host': PIWIK_HOST,
38 'token': PIWIK_TOKEN,
39 'protocol': protocol,
40 'static': settings.STATIC_URL,
41 'referer': referer,
42 }
43 track += http_referer
44 content = response.content
45 content_with_trackcode = ire_body.sub('%s</body>' % track, content)
46 response.content = content_with_trackcode
47 return response