addpiwik.py

#!/usr/bin/env python

import os
import sys

# as per XHTML all tags have to be all lowercase you only need case
# insensitive regular expression matching if # you are not using
# XHTML or NOT strictly using lowercase HTML tags
use_bodyregex = False

# ------------------------------------------------------------------------
__author__ = "Markus Stumpf <mailto:srv-src-extfilter-piwik@maexotic.de>"
__source__ = "http://software.maexotic.de/piwik/addpiwik/"
__version__ = "1.0"
__license__ = """Copyright (c) 2010 Markus Stumpf. All rights reserved.
See http://software.maexotic.de/license/license.txt for
the full text of the license."""

# ------------------------------------------------------------------------
# this is the PIWIK tracker Javascript code snippet
PIWIK_TRACKER = """
<!-- Piwik Tag -->
<script type="text/javascript">
var pkBaseURL = (("https:" == document.location.protocol) ? "https://{$PIWIK_URL}" : "http://{$PIWIK_URL}");
document.write(unescape("%3Cscript src='" + pkBaseURL + "piwik.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var piwikTracker = Piwik.getTracker(pkBaseURL + "piwik.php", {$PIWIK_IDSITE});
piwikTracker.trackPageView();
piwikTracker.enableLinkTracking();
} catch( err ) {}
</script>
<!-- End Piwik Tag -->
</body>"""
# ------------------------------------------------------------------------
# HTML code snippet for errors
ERROR_NOENV = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
  <title>Error: '%s' not set</title></head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta http-equiv="Content-Language" content="en" />
  <meta name="generator" content="%s" />
  <meta name="author" content="%s" />
<body>
  <h1>Error: '%s' not set</h1>
  <p>%s - version: %s</p>
  <p>Environment variable '%s' not set.</p>
</body>
</html>
"""

# ------------------------------------------------------------------------
piwik_idsite = os.environ.get("PIWIK_IDSITE")
if piwik_idsite is None:
    m = "PIWIK_IDSITE"
    sys.stdout.write(ERROR_NOENV % \
	(m, sys.argv[0], __source__, m, sys.argv[0], __version__, m))
    sys.exit(1)

piwik_url = os.environ.get("PIWIK_URL")
if piwik_url is None:
    m = "PIWIK_URL"
    sys.stdout.write(ERROR_NOENV % \
	(m, sys.argv[0], __source__, m, sys.argv[0], __version__, m))
    sys.exit(1)

# put IDSITE and PIWIK_URL in the Javascript snippet
piwik_tracker = PIWIK_TRACKER.replace("{$PIWIK_URL}", piwik_url)
piwik_tracker = piwik_tracker.replace("{$PIWIK_IDSITE}", piwik_idsite)

if use_bodyregex:
    import re
    PAT_BODY = re.compile("</body>", re.IGNORECASE)

for l in sys.stdin.readlines():
    if use_bodyregex:
        l = PAT_BODY.sub(piwik_tracker, l)
    else:
        l = l.replace("</body>", piwik_tracker)
    sys.stdout.write(l)

sys.stdout.flush()
sys.exit(0)