package Filters::GoogleAnalytics; ## Steven Evatt - 2007/10/29 ## modified by darcy w. christ 2008/04/21 use strict; use Apache2::Filter (); use Apache2::Const -compile => qw(OK OR_ALL); #qw(OK REDIRECT AUTH_REQUIRED DECLINED FORBIDDEN DECLINED SERVER_ERROR); #qw(OK OR_ALL); # NO_ARGS); use Apache2::Module (); use Apache2::CmdParms; use Apache2::RequestRec (); use Apache2::RequestUtil (); use APR::Table; #use constant BUFF_LEN => 1024; use constant BUFF_LEN => 8000; # There is perldoc at the end of this file. sub handler { my $f = shift; # get google analytics accountId #return Apache2::Const::DECLINED # unless $f->dir_config('AccountId'); my $AccountId = $f->r->dir_config('AccountId') || 0; my $LegacyCode = $f->r->dir_config('LegacyCode') || 0; #$f->dir_config('green'); # unset Content-Length but only on the first bucket per response. unless ($f->ctx) { $f->r->headers_out->unset('Content-Length'); $f->ctx(1); } # read from the incoming brigade while ($f->read(my $buffer, BUFF_LEN)) { # get the config for this module, # so we can access the directive's arguments my $cfg = Apache2::Module::get_config(__PACKAGE__, $f->r->server); # do the switch! my $google_in =""; my $google_out = ''; # check to see if we should use the legacy tracking code if($LegacyCode) { $google_out = < EOF } else { $google_out = < var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); EOF } chomp $google_out; if ($buffer =~ m||i) { unless ($buffer =~ m/($AccountId)/) { $buffer =~ s/$google_in/$google_out/i; } } $f->print($buffer); # write to the outgoing brigade } return Apache2::Const::OK; } ### 1;# ### =head1 NAME Filters::GoogleAnalytics =head1 SYNOPSIS The following is not Perl; it goes in your Apache vhost configuration. (for example, /etc/apache2/sites-enabled/000-default) PerlLoadModule Filters::GoogleAnalytics PerlOutputFilterHandler Filters::GoogleAnalytics PerlSetVar AccountId "" PerlSetVar LegacyCode 1 # (optional) PerlOutputFilterHandler Filters::GoogleAnalytics PerlSetVar AccountId "" PerlSetVar LegacyCode 1 # (optional) =head1 DESCRIPTION This filter inserts your Google Analytic Javascript tag before the tag if the page does not already contain the Google tag. This is an output filter for Apache2. It will NOT work with apache 1.3. You need to modify this .pm file to insert your google tag, and add a few lines to your apache configuration. See the L for a somewhat complete example. To use this module as shown, you will need: * Apache version 2 * Mod_perl version 2 =head1 Directives =over 12 =item C PerlSetVar AccountId "" PerlSetVar LegacyCode 1 Inserts your google tag just before the tag on the page. =back =head1 LICENSE GPL. =head1 AUTHOR Steven Evatt, darcy w. christ =head1 SEE ALSO Apache2::Filter mod_perl The excellent tutorial at http://perl.apache.org/docs/2.0/user/handlers/filters.html =cut