Pluf Framework

Pluf Framework Git Source Tree

Root/src/Pluf/Middleware/GoogleAnalytics.php

1<?php
2/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
3/*
4# ***** BEGIN LICENSE BLOCK *****
5# This file is part of Plume Framework, a simple PHP Application Framework.
6# Copyright (C) 2001-2007 Loic d'Anterroches and contributors.
7#
8# Plume Framework is free software; you can redistribute it and/or modify
9# it under the terms of the GNU Lesser General Public License as published by
10# the Free Software Foundation; either version 2.1 of the License, or
11# (at your option) any later version.
12#
13# Plume Framework is distributed in the hope that it will be useful,
14# but WITHOUT ANY WARRANTY; without even the implied warranty of
15# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16# GNU Lesser General Public License for more details.
17#
18# You should have received a copy of the GNU Lesser General Public License
19# along with this program; if not, write to the Free Software
20# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
21#
22# ***** END LICENSE BLOCK ***** */
23
24/**
25 * GoogleAnalytics middleware.
26 *
27 * Add the googleanalytics tracking code to the pages.
28 */
29class Pluf_Middleware_GoogleAnalytics
30{
31 /**
32 * Process the response of a view.
33 *
34 * If the status code and content type are allowed, add the
35 * tracking code.
36 *
37 * @param Pluf_HTTP_Request The request
38 * @param Pluf_HTTP_Response The response
39 * @return Pluf_HTTP_Response The response
40 */
41 function process_response($request, $response)
42 {
43 if (!Pluf::f('google_analytics_id', false)) {
44 return $response;
45 }
46 if (!in_array($response->status_code,
47 array(200, 201, 202, 203, 204, 205, 206, 404, 501))) {
48 return $response;
49 }
50 $ok = false;
51 $cts = array('text/html', 'text/html', 'application/xhtml+xml');
52 foreach ($cts as $ct) {
53 if (false !== strripos($response->headers['Content-Type'], $ct)) {
54 $ok = true;
55 break;
56 }
57 }
58 if ($ok == false) {
59 return $response;
60 }
61 $js = '<script type="text/javascript">
62var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
63document.write(unescape("%3Cscript src=\'" + gaJsHost + "google-analytics.com/ga.js\' type=\'text/javascript\'%3E%3C/script%3E"));
64</script>
65<script type="text/javascript"> try {
66var pageTracker = _gat._getTracker("'.Pluf::f('google_analytics_id').'");
67pageTracker._trackPageview(); } catch(err) {}
68</script>';
69 $response->content = str_replace('</body>', $js.'</body>', $response->content);
70 return $response;
71 }
72}
73

Archive Download this file

Branches

Tags