nouvelle version qui ajout le code javascript que lorsque le content type est: text...
[auf_django_piwik.git] / auf / django / piwik / middleware.py
CommitLineData
567ee8ed
OL
1# -*- coding: utf-8 -*-
2
3import re
b9d57605
OL
4
5from django.conf import settings
6
0745a8be
OL
7try:
8 import auf.django.references.models as ref
9 REFERENCES_CHARGEES = True
10except:
11 REFERENCES_CHARGEES = False
12
13
35774ef6
OL
14from settings import PIWIK_TOKEN, PIWIK_HOST, PIWIK_HTTPFORCE,\
15 PIWIK_TRACKCODE, PIWIK_EXCLUDE_REFERER
567ee8ed 16
0745a8be 17
567ee8ed
OL
18ire_body = re.compile(re.escape('</body>'), re.IGNORECASE)
19
20
21class 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 """
c1e1a58a 28 if PIWIK_TOKEN is None or response.get('Content-Type', '') != 'text/html':
567ee8ed
OL
29 return response
30
35774ef6
OL
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
3af9d19f 39 if request.is_secure() and not PIWIK_HTTPFORCE:
567ee8ed
OL
40 protocol = "https"
41 else:
42 protocol = "http"
43
a05180a4 44 implantation = ""
4d85f0b5
OL
45 user = getattr(request, 'user', None)
46 if user and REFERENCES_CHARGEES and user.is_authenticated():
f461bf4f
OL
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
0745a8be 53
567ee8ed
OL
54 track = PIWIK_TRACKCODE % {
55 'host': PIWIK_HOST,
56 'token': PIWIK_TOKEN,
57 'protocol': protocol,
b9d57605 58 'static': settings.STATIC_URL,
35774ef6 59 'referer': referer,
0745a8be 60 'implantation': implantation,
567ee8ed 61 }
567ee8ed
OL
62 content = response.content
63 content_with_trackcode = ire_body.sub('%s</body>' % track, content)
64 response.content = content_with_trackcode
65 return response