1.6
[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 try:
8 import auf.django.references.models as ref
9 REFERENCES_CHARGEES = True
10 except:
11 REFERENCES_CHARGEES = False
12
13
14 from settings import PIWIK_TOKEN, PIWIK_HOST, PIWIK_HTTPFORCE,\
15 PIWIK_TRACKCODE, PIWIK_EXCLUDE_REFERER
16
17
18 ire_body = re.compile(re.escape('</body>'), re.IGNORECASE)
19
20
21 class TrackMiddleware:
22
23 def process_response(self, request, response):
24 """
25 Trackcode injection avant le body s'il y a un token piwik dans la conf
26 locale.
27 """
28 if PIWIK_TOKEN is None:
29 return response
30
31 http_referer = request.META.get('HTTP_REFERER', "")
32 referer = http_referer
33
34 for excl in PIWIK_EXCLUDE_REFERER:
35 if excl in http_referer:
36 referer = ""
37 break
38
39 if request.is_secure() and not PIWIK_HTTPFORCE:
40 protocol = "https"
41 else:
42 protocol = "http"
43
44 user = getattr(request, 'user', None)
45 if user and REFERENCES_CHARGEES and user.is_authenticated():
46 try:
47 employe = ref.Employe.objects.get(courriel=request.user.email)
48 imp_id = employe.implantation.id
49 implantation = "piwikTracker.setCustomVariable(1, 'implantation', '%s', 'visit');" % imp_id
50 except :
51 pass
52 else:
53 implantation = ""
54
55 track = PIWIK_TRACKCODE % {
56 'host': PIWIK_HOST,
57 'token': PIWIK_TOKEN,
58 'protocol': protocol,
59 'static': settings.STATIC_URL,
60 'referer': referer,
61 'implantation': implantation,
62 }
63 content = response.content
64 content_with_trackcode = ire_body.sub('%s</body>' % track, content)
65 response.content = content_with_trackcode
66 return response