Extension talk:Google Analytics Integration

From MediaWiki.org
Jump to: navigation, search

Contents

[edit] NOTE - Please install new version

Please install the latest version! As seen below - The initial release of the extension was not returning 'true' properly, which causes errors in MW 1.11+ and halts further processing on the specified Hook in every version! (not cool) Tim LaquaTalk | contribs@15:23, 26 August 2007 (UTC)

[edit] I installed this extension on my MW 1.11(Alpha). Got Following error.

(Note I have removed my hosting a/c name and put XXXXX instead for obvious reason.)

MediaWiki internal error.

Original exception: exception 'MWException' with message 'Detected bug 
in an extension! Hook googleAnalyticsHook failed to return a value; should 
return true to continue hook processing or false to abort.' in /home/XXXXX/public_html/wiki/includes/Hooks.php:133
Stack trace:
#0 /home/XXXXX/public_html/wiki/skins/MonoBook.php(225): wfRunHooks()
#1 /home/XXXXX/public_html/wiki/includes/SkinTemplate.php(463): MonoBookTemplate->execute('MonoBookTemplat...', Array)
#2 /home/XXXXX/public_html/wiki/includes/OutputPage.php(683): SkinTemplate->outputPage()
#3 /home/XXXXX/public_html/wiki/includes/Wiki.php(301): OutputPage->output(Object(OutputPage))
#4 /home/XXXXX/public_html/wiki/index.php(90): MediaWiki->finalCleanup()
#5 {main}

Exception caught inside exception handler: exception 'MWException' 
with message 'Detected bug in an extension! Hook googleAnalyticsHook failed 
to return a value; should return true to continue hook processing or false to abort.'
in /home/XXXXX/public_html/wiki/includes/Hooks.php:133
Stack trace:
#0 /home/XXXXX/public_html/wiki/skins/MonoBook.php(225): wfRunHooks()
#1 /home/XXXXX/public_html/wiki/includes/SkinTemplate.php(463): 
   MonoBookTemplate->execute('MonoBookTemplat...', Array)
#2 /home/XXXXX/public_html/wiki/includes/OutputPage.php(683): SkinTemplate->outputPage()
#3 /home/XXXXX/public_html/wiki/includes/Exception.php(86): OutputPage->output(Object(OutputPage))
#4 /home/XXXXX/public_html/wiki/includes/Exception.php(111): MWException->reportHTML()
#5 /home/XXXXX/public_html/wiki/includes/Exception.php(191): MWException->report()
#6 /home/XXXXX/public_html/wiki/includes/Exception.php(225): wfReportException()
#7 [internal function]: wfExceptionHandler()
#8 {main}

-Gautam

Thx! The posted code should be working now. Tim LaquaTalk | contribs@02:47, 20 August 2007 (UTC)

[edit] runonloadhook

Tim, thanks for making this great extension. If you look at the code of any page in MW, you'll see near the end:

<script type="text/javascript">if (window.runOnloadHook) runOnloadHook();</script>

Wouldnt using this hook (if possible) be a better way because GA advises to use the code just before the body tag? This hook is about just before the body tag. --Kenny5 19:11, 2 September 2007 (UTC)

If you run this extension on 1.11alpha+, you'll notice that the GA code actually shows up BELOW that script line. I added a new hook to the core (SkinAfterBottomScripts) specifically designed for JS-powered analytics engines. I talked to the guys over at Google regarding the tag placement and they said that as long as Google is receiving data, the tag placement is fine. There are certain locations where the script will not be executed properly and that's why they say put it at the bottom. Either way, if you get data in your GA reports, you're good - and once 1.11 comes out, the extension utilizes the new hook that puts the script tag at the absolute bottom of the page. Tim LaquaTalk | contribs@19:26, 2 September 2007 (UTC)
Ah I see, great then. I'll wait for the upgrades then. Thanks for all your research in this. And I just checked and am getting the data even with my 1.9.3 (should have mentioned before) so this is great. This extension is great, I didnt have to alter the internal files in any way (which is always the goal). thanks again --Kenny5 19:35, 2 September 2007 (UTC)

[edit] Bottom of page; older version

I installed this and the script is not at the bottom of the page--though fairly near it. I'm using version 1.8. Right now when I go to google analytics and click the "check status" button it says that the tracking code hasn't been detected. What I'm guessing is that the detection mechanism specifically is looking for this at the bottom of the page but that, regardless it is working. I hope!. Anyway, I'll verify by checking back with google analytics in a few days and see if they are gathering any datat. Then I'll report the results here. Thanks for the extension! --Matthew (76.27.82.88 04:33, 14 September 2007 (UTC))

Let me know if you don't receive any data within 48 hours of installing the extension. GA seems to be 2-3 days behind at all times. It should work even though it's not at the bottom, I talked to the GA guys when I wrote the extension.  ;-) Tim LaquaTalk | contribs@12:26, 15 September 2007 (UTC)

[edit] New GoogleAnalytics script

Changing this part of the code will incorporate the new GoogleAnalytics script:

$funcOutput = "<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(\"" . $googleAnalytics . "\")\n".
"pageTracker._initData();\n".
"pageTracker._trackPageview();\n".
"</script>\n";

--Jdj 02:21, 28 December 2007 (UTC)

Implemented support for the new ga.js script in r29077. Thx for the note, I wasn't aware they had a new script available. Also, check the code - f/ large string chunks like that, HEREDOC syntax is much cleaner.  ;-) Tim Laqua talk 22:05, 30 December 2007 (UTC)


[edit] Version 2 Compatibility?

A few days ago I upgraded to version 2 with my mediawiki 1.11.2 and my gumax skin. Google analytics says that it recognizes the code but it seems weird because my traffic has died. I know that one person registered this morning and two other people simply visited (I asked them to visit). Yet 5 hours later still no traffic. I know it's not the Google Analytics delay because my blog is showing healthy traffic.

Is there a compatibility issue with something? Any suggestions? [Ed D April 1, 2008] ...this is not an April Fools joke.

Do you define $wgGoogleAnalyticsAccount after the require_once( ... ) line? In previous versions, I didn't initalize that variable, so you could define your account number anywhere. Now, because the extensions initalizes $wgGoogleAnalyticsAccount to a blank string, you need to make sure that your assignment of $wgGoogleAnalyticsAccount is *after* the require_once( ... ) statement for this extension (as shown on the extension page). If that's not the issue, the only other thing I can think of is the GA delay (24-48 hours) and maybe your Blog is granted a higher priority or something due to either high traffic or high pagerank? I'm also not sure if there's any difference in stat lag based on what version of the GA script you're using. 2.0 of this extension is using the new GA script. I know there are people using this version on MW 1.11.2, so it's certainly not an incompatibility issue. Tim Laqua talk 11:48, 2 April 2008 (UTC)


[edit] Turns my Main Page into log file

When I try to use this extension, it turns my Main Page into a log file that looks like the code in the php file. I've put the two php files in the right folder and pasted the script into localsettings.php along with my GoogleAnalytics id but it just doesn't seem to want to work for me. I am using MediaWiki 1.12 and the cavendish theme.

Do you have an example URL I could take a look at? Tim Laqua talk 20:45, 6 July 2008 (UTC)

[edit] Same Problem for me

The code from the googleAnalytics.php-File is printed out instead of my Wiki-Site. And there is the response:
Warning: Cannot modify header information - headers already sent by (output started at /hp/ag/ac/li/www/georg/wiki/extensions/googleAnalytics/googleAnalytics.php:12) in /hp/ag/ac/li/www/georg/wiki/includes/WebResponse.php on line 10

This is usually caused by a bad download that has garbage at the top or bottom of the file (often a BOM). Try re-downloading the file and saving it - don't cut/paste the contents in to an editor (BOMs may result). Tim Laqua talk 20:45, 6 July 2008 (UTC)

[edit] Mediawiki 12.0

I´ve got an unexpected error message with Mediawiki 12.0, having had any problems in the past with the installation of Google Analytics on other portals:

Warning: Unexpected character in input: '\' (ASCII=92) state=1 in 
/home/coastalz/public_html /benidormense/pool/extensions/googleAnalytics/googleAnalytics.php on line 2
Parse error: syntax error, unexpected T_STRING in 
/home/coastalz/public_html/benidormense/pool/extensions/googleAnalytics/googleAnalytics.php on line 2

Anybody any idea?? Could it be that it has to do anything with the fact that the domain actually is added on the server of another domain, thus being actually a subdomain?...

Thanks in advance for your comments, --Horst Salzwedel 20:32, 19 July 2008 (UTC)

[edit] No rendering at all

Hello Tim,

I just installed your extension, and it is well identified by my MW 1.11.

But I don't get the code in my page and I was wondering if the monoBook.php framework was not missing a call... I saw in the doc something like wfRunHooks(...) and you don't mention it.

I followed your installation process step by step.

Michel Cadennes

P.-S. Could you explain to me the meaning of this syntax : <<<GASCRIPT ? Opening Buffer ?

Edit :

I got the hook to work ! But remains a problem wirh global variables (in LocalSettings.php i.e. $wgGoogleAnalyticsAccount) which are not handled by the callback... Argh !

Edit 2 :

OK. It works finally... Wow ! But Some hints remain mysterious =:o)

[edit] Please tell me how ...

Michel - I have the same issue. Please tell me/everyone else how to resolve it.

Cheers, Hughie

[edit] Doesnt show on Google Analytics

I followed your installation process step by step. But it doesnt work. Does anyone have more information? Thanks.--Swessels 10:24, 30 July 2008 (UTC)

Have you waited a day? It might just take a little time to show up. Smaug Tournesol.png 17:11, 30 July 2008 (UTC)
Uh, yes :-) Its been almost a week now, still nothing.... --Swessels 06:35, 1 August 2008 (UTC)
I've looked at the source code for my index page, and there is nothing in that showing the google code, so it seems asif the code is not "pasted" into every page. The extension is installed, when I look at the Special page: Version.--Swessels 08:42, 4 August 2008 (UTC)
(continued at User_talk:Smaug#Doesnt_show_on_Google_Analytics) Smaug Tournesol.png 15:35, 7 August 2008 (UTC)

[edit] GA code not rendering? Do the require_once and then set the properties!

It doesn't work when you set the variables and then do the require_once. ~ Erik de Bruijn

[edit] Note: you may need to remove the pageTracker._initData(); line for Analytics to recognise the installation

I don't get Analytics to work. I did everything right, but I don't understand the line Note: you may need to remove the pageTracker._initData(); line for Analytics to recognise the installation. Can it be explaned a bit better? Where do I find this line? I think this is the thing I have to do, because that's the only thing that's left.

It seems to be my problem also. This line code pageTracker._initData(); is not available in both files googleAnalytics.i18n.php and googleAnalytics.php. Where should we delete this line? Thanks.

Yeah, that note is RIDICULOUS: what do "you may have to..." mean?? Either you have to or you don't have to, And if you have to remove that line, then why on earth is it there in the first place? Why don't the developers delete it so we don't need to delete it?? Why put there a line of code that one has to delete? It doesn't make any sense.

Yup, if anyone could expand on this that would be great! Since no such line exists in the download, perhaps we should be bold and delete that line from the install instructions? They could be simpler too btw! --Dmb 13:15, 7 September 2011 (UTC)

[edit] Error loading special pages

I get this when I click the special pages link in the tool bar:

Warning: MessageCache::require(/home/netcai5/public_html/wiki/extensions/googleAnalytics/googleAnalytics.i18n.php) [messagecache.require]: failed to open stream: No such file or directory in /home/netcai5/public_html/wiki/includes/MessageCache.php on line 813

Fatal error: MessageCache::require() [function.require]: Failed opening required '/home/netcai5/public_html/wiki/extensions/googleAnalytics/googleAnalytics.i18n.php' (include_path='/home/netcai5/public_html/wiki:/home/netcai5/public_html/wiki/includes:/home/netcai5/public_html/wiki/languages:.:/usr/lib/php:/usr/local/lib/php:/home/netcai5/php') in /home/netcai5/public_html/wiki/includes/MessageCache.php on line 813

I think everything is installed correctly as google is receiving data. Any ideas? my page is viewable at www netcairns com Judson --70.233.161.254 02:02, 29 November 2008 (UTC)

My guess is that you haven't downloaded the googleAnalytics.i18n.php file, which is also part of the extension. -- AttishOculus

[edit] Website-Overlay do not work

The script works fine, just the Website-Overlay function in google analytics interface is not avadible. is ist possible to change that? PHP 5.2.6, mw: 1.13.1. thanks --87.187.36.250 16:25, 28 March 2009 (UTC)

[edit] Feature Request

Kudos! This is a great tool and saved me countless hours. Thank you!

Is there a way we can exclude certain pages, such as the user Login page? Or the main page?

[edit] Just installed extension in v1.14

I just installed the extension in v1.14 at Debatrix and only had one problem. Line 59 of the .php file had to be removed. I see the code on my main page, so now I am waiting the 24-48hrs for some results to show up. I will try to post an update in the next couple of days when I see how it works.--Jake4d 06:17, 8 May 2009 (UTC) P.S. Thanks in advance for the great extension.

Just checked my account at Google Analytics and this extension is working beautifully. Thanks--Jake4d 02:19, 11 May 2009 (UTC)

[edit] Feature request: Option to exclude user accounts

Can the code be modified so if we want we can exclude user accounts too? I'm also interested in seeing traffic from the external internet visitors that doesnt include logged in users and editors who are often the most frequent users of the site. --Kenny5 18:43, 28 July 2009 (UTC)

[edit] Not working with PHP 5.3.0

This extension doesn't seem to work with the newest PHP version 5.3.0. I get an error message.

Can that be fixed? It would be a pity if I can't use this great extension anymore. --Plati123 11:42, 12 August 2009 (UTC)

likewise here - I get this on the Main Page of my wiki:
Warning: Parameter 1 to efGoogleAnalyticsHookText() expected to be a reference, value given in  /Users/roger/Sites/xxxxxx/legacy/w/includes/Hooks.php on line 117

Warning: Parameter 1 to efGoogleAnalyticsHookText() expected to be a reference, value given in  /Users/roger/Sites/xxxxxx/legacy/w/includes/Hooks.php on line 117
MediaWiki internal error.

Exception caught inside exception handler
I'm running a local copy on OS X 10.6.1 (Snow Leopard) with: MediaWiki 1.15.1 (r4), PHP 5.3.0 (apache2handler), MySQL 5.1.39 --Junap 15:25, 10 October 2009 (UTC)
To fix, edit googleAnalytics.php, and change line 23 from:
function efGoogleAnalyticsHookText(&$skin, &$text=) {
to
function efGoogleAnalyticsHookText($skin, &$text=) {

I had the same bug, same fix. Except it was line 35.--71.163.233.145 20:49, 8 March 2010 (UTC)
This fixed the problem for me also. Shaun Clarke 03:26, 25 June 2010 (UTC)
Fixed problem for me too. Just look for function efGoogleAnalyticsHookText and change the signature as specified above. --Slowpoison 23:01, 6 July 2010 (UTC)

The error message here was PHP Warning: Parameter 1 to efGoogleAnalyticsHookText() expected to be a reference, value given in .../mediawiki-1.17a/includes/Hooks.php on line 133 with the offending call made from "extensions/googleAnalytics/googleAnalytics.php" line 24 of 59. This is based on the most current version of MediaWiki. --Carlb 14:23, 4 July 2010 (UTC)

[edit] Not working with PHP 5.2.8 either (me thinks)

I have installed via instructions and the extensions shows up in my Version page, but no code shows up when I view source on any page.

You may want to tail -f /var/log/httpd/error_log to see what's going on. A completely-blank page (0 bytes) usually means there's a PHP Fatal error in the logs for that page, preventing any output from being generated. Without looking at the log file, that error could be anywhere. --Carlb 17:48, 4 July 2010 (UTC)

[edit] How do I use this to limit GA results to a single category?

Rather than create a namespace so that there's a common URL pattern across all designated articles, I want to track Google Analytics for a specific MediaWiki category — can I do it with this extension or another? Thanks in advance. --Torley 21:25, 22 September 2009 (UTC)

Probably not any extension. You'll have to change some code. --Choshi 13:27, 2 October 2009 (UTC)

[edit] New GA Tracking code

Any plan to update this to use the new asynchronous GA tracking code? See http://code.google.com/apis/analytics/docs/tracking/asyncTracking.html

RoyLeban 21:07, 20 December 2009 (UTC)

[edit] Using LocalSettings.php

Why do the instructions say to edit the source code rather than to set values in LocalSettings.php? Shouldn't both methods work? (I did it the way you said, just to make sure, but that means I have to edit the source each time I update the extension).

I agree this would be a good idea also. Shaun Clarke 03:26, 25 June 2010 (UTC) RoyLeban 21:10, 20 December 2009 (UTC)

[edit] Replace xxxxxxx-x with YOUR GoogleAnalytics UA number

Can't this be set in LocalSettings.php like other extension configuration?

Anyone know if any developers are tracking this discussion page? Seems a lot of questions go unanswered here... --Dmb 13:20, 7 September 2011 (UTC)

[edit] would it be slightly easier

would it be slightly easier if you allowed the user to specify the account # in their localsettings.php, instead of having to edit the googleAnalytics.php file? Thanks Bud0011 02:33, 23 February 2010 (UTC)

It is just that the instructions are misleading. "require_once( "$IP/extensions/googleAnalytics/googleAnalytics.php" ); $wgGoogleAnalyticsAccount = "UA-xxxxxxx-3";" works fine. The account must be set AFTER the require_once, however. G.Hagedorn 01:50, 16 November 2011 (UTC)

[edit] Question

We got this error when the extension crashed our wiki:

MediaWiki internal error.

Exception caught inside exception handler

We're using:

  • MediaWiki 1.15.1
  • PHP 5.3.1 (apache2handler)
  • MySQL 5.1.41

Appreciate any help. Thanks! Julia & Ted

Ah, we made the line 23 change above and it worked! -- Julia & Ted

[edit] Please verify "non-logged in" alternative files

Noticing that Extension:Google_Analytics_Integration#See also is offering alternate download of the extension files from sites.google.com. I'd feel more comfortable (and perhaps I'm not alone feeling insecure about this) if they were to be added to the svn instead. Thanks --SomaticJourney 06:20, 6 March 2010 (UTC)

Looks like it's not a function of WMF to check extensions or put them all on svn. I took a look at the sites.google script and it seems to be genuine. I'm testing it out. If it works, I vote to merge $wgGoogleAnalyticsIgnoreUsers in to the code. --SomaticJourney 07:43, 6 March 2010 (UTC)

[edit] Google has a new tracking code (when I checked on March 7, 2010)

I am using your development trunk r62858. Tracking wasn't working for me. Google analytics said that tracking was unknown. I noticed that the code this extension placed at the bottom of my main page did not match what google wanted me to insert manually. Here is your trunk r62858 code:

<script type="text/javascript">
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"));
</script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("{$wgGoogleAnalyticsAccount}");
pageTracker._initData();
pageTracker._trackPageview();
</script>

and here is the new google code:

<script type="text/javascript">
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"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-XXXXXXXX-X");
pageTracker._trackPageview();
} catch(err) {}</script>
try {

has been added

pageTracker._initData();

has been removed

} catch(err) {}

has been added

I made these changes in googleanalytics.php.

I also made the change to:

function efGoogleAnalyticsHookText($skin, &$text=) {

in googleanalytics.php as outlined earlier in this talk page(because I use php 5.3.0).

After that everything worked. --twinsenw

---(May 17,2010) -- Haides In my website, I need replace this code in googleAnalytics.php, then it worked. If you had enabled googleAnalytics extension, pls re-enable it in LocalSettings.php(comment it firstly)

                           
$funcOutput = <<<GASCRIPT
<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', '$wgGoogleAnalyticsAccount']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
GASCRIPT;

[edit] extension does not work

I created the /extensions/googleAnalytics/ folder, downloaded googleAnalytics.i18n.php & googleAnalytics.php into it, added require_once( "$IP/extensions/googleAnalytics/googleAnalytics.php" ); to the bottom of LocalSettings.php, set Account to my account #, AddASAC to false, IgnoreSysops to true, & IgnoreBots to true. The page says it should be working now, but instead URL/wiki/index.php/Main_Page says "MediaWiki internal error. Exception caught inside exception handler" and the Google Analytics Tracking Status says: "Tracking Not Installed (Last checked: Jul 14, 2010 12:59:58 AM ) The Google Analytics tracking code has not been detected on your website's home page. For Analytics to function, you or your web administrator must add the code to each page of your website." I have the Google Analytics Website URL for just the URL without the /wiki/ part, not sure that matters.

Probably, bug in PHP 5.3.3, see fix.
14 April 2011 - I installed the extension and it works! ~nels nelson my media wiki
I added the tracking code in googleAnalytics.php
The PHP bug was causing me problems, I fixed it (I had PHP 5.3.2).
The extension shows in Special:version
I then went to google and got the same message with a wierd date:
Tracking Not Installed Last checked: Dec 31, 1969 4:00:00 PM PST
"The Google Analytics tracking code has not been detected on your website's home page. For Analytics to function, you or your web administrator must add the code to each page of your website."
Any suggestions? Does it take a while to read my site? Bigbull 01:25, 16 September 2011 (UTC)

[edit] New async code

I change the code to the new async GA:

$funcOutput = <<<GASCRIPT
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXXX-X']);
_gaq.push(['_setDomainName', 'domain.com']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
GASCRIPT;


And change:

//$wgHooks['SkinAfterBottomScripts'][]  = 'efGoogleAnalyticsHookText';
$wgHooks['SkinAfterContent'][]  = 'efGoogleAnalyticsHookText';


And:

//function efGoogleAnalyticsHookText(&$skin, &$text='') {
function efGoogleAnalyticsHookText(&$text='') {


For render the code near the body.

Anyone can tell me how must do for render inmediately before body tag?

  • The new async code actually belongs at the top of the page just before closing head tag. Any plans to fix this extension to correct this? Gilluminate 17:45, 13 January 2011 (UTC)

[edit] Tracking for File Downloads

This extension works great for tracking wiki page views. However it doesn't seem to track direct file downloads. For example, it will track when someone goes to File:somefile.doc, but not when they click on Media:somefile.doc (which downloads the file directly). Is there any way to track this? --Gkullberg 16:57, 14 September 2010 (UTC)

[edit] Very simple extension for Google Analytics

File 'extensions/GoogleAnalytics.php':

<?php
global $wgGoogleAnalytics;
$wgGoogleAnalytics = false;

$wgHooks['ParserAfterTidy'][]  = 'efGoogleAnalytics';

function efGoogleAnalytics() {
        global $wgOut;
        global $wgGoogleAnalytics;

        if (!$wgGoogleAnalytics) {
                $funcOutput = <<<GASCRIPT
<script type="text/javascript">
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"));
</script>
<script type="text/javascript">
try{
var pageTracker = _gat._getTracker("UA-xxxxxx-x");
pageTracker._trackPageview();
} catch(err) {}
</script>
GASCRIPT;
                $wgOut->addScript($funcOutput);
                $wgGoogleAnalytics = true;
        }
        return true;
}
?>

Add in LocalSettings.php:

require_once($IP.'/extensions/GoogleAnalytics.php');

[edit] How to set the new asynchronous snippet before the head tag (mw < 1.17)

Thanks to RoanKattouw I've been able to set this extension to add the asynchronous snippet right before the head tag.

Before you find the new version of googleAnalytics/googleAnalytics.php

Modifications:

Let's hope this will be useful to others too :) --Mindrones 12:12, 8 November 2011 (UTC)

<?php
if ( !defined( 'MEDIAWIKI' ) ) {
        die( 'This file is a MediaWiki extension, it is not a valid entry point' );
}

$wgExtensionCredits['other'][] = array(
        'path'           => __FILE__,
        'name'           => 'Google Analytics Integration',
        'version'        => '2.0.2',
        'author'         => 'Tim Laqua',
        'descriptionmsg' => 'googleanalytics-desc',
        'url'            => 'http://www.mediawiki.org/wiki/Extension:Google_Analytics_Integration',
);

$wgExtensionMessagesFiles['googleAnalytics'] = dirname(__FILE__) . '/googleAnalytics.i18n.php';

$wgHooks['BeforePageDisplay'][]  = 'efGoogleAnalyticsHookText';
$wgHooks['ParserAfterTidy'][] = 'efGoogleAnalyticsASAC';

# registered account
$wgGoogleAnalyticsAccount = "UA-XXXXX-X";

# to be used in case we had AdSense as well and have linked accounts, to enable tracking set this to true
$wgGoogleAnalyticsAddASAC = false;
$wgGoogleAnalyticsIgnoreSysops = true;
$wgGoogleAnalyticsIgnoreBots = true;

function efGoogleAnalyticsASAC( &$parser, &$text ) {
        global $wgOut, $wgGoogleAnalyticsAccount, $wgGoogleAnalyticsAddASAC;

        if( !empty($wgGoogleAnalyticsAccount) && $wgGoogleAnalyticsAddASAC ) {
                $wgOut->addScript('<script type="text/javascript">window.google_analytics_uacct = "' . $wgGoogleAnalyticsAccount . '";</script>');
        }

        return true;
}

function efGoogleAnalyticsHookText( $out ) {
        $out->addScript( efAddGoogleAnalytics() );
        return true;
}

function efAddGoogleAnalytics() {
        global $wgGoogleAnalyticsAccount, $wgGoogleAnalyticsIgnoreSysops, $wgGoogleAnalyticsIgnoreBots, $wgUser;
        if (!$wgUser->isAllowed('bot') || !$wgGoogleAnalyticsIgnoreBots) {
                if (!$wgUser->isAllowed('protect') || !$wgGoogleAnalyticsIgnoreSysops) {
                        if ( !empty($wgGoogleAnalyticsAccount) ) {
                                $funcOutput = <<<GASCRIPT
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', '$wgGoogleAnalyticsAccount']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
GASCRIPT;
                        } else {
                                $funcOutput = "\n<!-- Set \$wgGoogleAnalyticsAccount to your account # provided by Google Analytics. -->";
                        }
                } else {
                        $funcOutput = "\n<!-- Google Analytics tracking is disabled for users with 'protect' rights (I.E. sysops) -->";
                }
        } else {
                $funcOutput = "\n<!-- Google Analytics tracking is disabled for bots -->";
        }

        return $funcOutput;
}

///Alias for efAddGoogleAnalytics - backwards compatibility.
function addGoogleAnalytics() { return efAddGoogleAnalytics(); }

Personal tools
Namespaces
Variants
Actions
Site
Support
Download
Development
Communication
Print/export
Toolbox