nouvelle version qui ajout le code javascript que lorsque le content type est: text...
[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 or response.get('Content-Type', '') != 'text/html':
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 implantation = ""
45 user = getattr(request, 'user', None)
46 if user and REFERENCES_CHARGEES and user.is_authenticated():
47 try:
48 employe = ref.Employe.objects.get(courriel=request.user.email)
49 imp_id = employe.implantation.id
50 implantation = "piwikTracker.setCustomVariable(1, 'implantation', '%s', 'visit');" % imp_id
51 except :
52 pass
53
54 track = PIWIK_TRACKCODE % {
55 'host': PIWIK_HOST,
56 'token': PIWIK_TOKEN,
57 'protocol': protocol,
58 'static': settings.STATIC_URL,
59 'referer': referer,
60 'implantation': implantation,
61 }
62 content = response.content
63 content_with_trackcode = ire_body.sub('%s</body>' % track, content)
64 response.content = content_with_trackcode
65 return response