Friday, October 17, 2008

Google Analytics

How to add Google Analytics script into MediaWiki engine? Or how I've wrote my first MediaWiki extension. The first idea was to patch skins and add analytics script before </body> tag. Of course, it isn't nice to patch all skins and keep these files coherent in future. Next idea was to patch Skin::bottomScripts() or Skin::outputPage(). Finally, I've decided to write extension which use one of standard hooks to add additional JavaScript code in result page generated by MediaWiki.

Finally:
MediaWiki extension to add Google Analytics script in each wiki page.

Check product home page.

Create file /extensions/AvbGoogleAnalytics/AvbGoogleAnalytics.php

This is extension body written on PHP.

<?php

if( !defined( 'MEDIAWIKI' ) ) die( -1 );

// Add hook on SkinAfterBottomScripts.
$wgHooks['SkinAfterBottomScripts'][] = 'onSkinAfterBottomScripts_AddAvbGoogleAnalyticsScript';


// returns Google Analytics tracker script
function getAvbGoogleAnalyticsScript($analytics_id)
{
$s = "\n<!-- avb: AvbGoogleAnalytics -->\n"
. "<script type=\"text/javascript\">\n"
. "var gaJsHost = ((\"https:\" == document.location.protocol) ? \"https://ssl.\" : \"http://www.\");\n"
. "document.write(unescape(\"%3Cscript src='\" + gaJsHost + \"google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E\"));\n"
. "</script>\n"
. "<script type=\"text/javascript\">\n"
. "var pageTracker = _gat._getTracker(\"" . $analytics_id . "\");\n"
. "pageTracker._trackPageview();\n"
. "</script>\n"
. "<h6>avb:2</h6>\n";

return $s;
}

// Event 'SkinAfterBottomScripts': At the end of Skin::bottomScripts()
// $skin: Skin object
// &$text: bottomScripts Text
// Append to $text to add additional text/scripts after the stock bottom scripts.
// Documentation: \mediawiki-1.13.0\docs\hooks.txt
function onSkinAfterBottomScripts_AddAvbGoogleAnalyticsScript($skin, &$text)
{

// Change "YOUR-ANALYTICS-ID" to your actual analytics id
// (analytics id is string like "UA-1223032-7")
$text .= getAvbGoogleAnalyticsScript("YOUR-ANALYTICS-ID");
return true;
}

?>

And the final step - add the line below at the end of your LocalSettings.php

require_once("extensions/AvbGoogleAnalytics/AvbGoogleAnalytics.php");


Full article is here.

No comments: