RSS

Piwik: simplified automatic deployment

Saturday, 31 July 2010

I'm using the excellent Piwik analytics tool on a number of sites hosted on a central CMS platform. The problem I found was that the JavaScript snippet required to track each user has a unique ID in it that identifies the the site. This was going to be a pain, so I modified the code to allow the each visit to use the site ID if it was present, or alternatively, work out the site ID from the URL. 

The code below is replacing the function __construct() in the file piwik/core/Tracker/Visit.php:

function __construct()
{

        $idsite = Piwik_Common::getRequestVar('idsite', 0, 'int', $this->request);

        // No idsite passed in, so try and get from URL
        if($idsite <= 0)
        {
                $host = '';
                // get host name from URL
                $url = Piwik_Common::getRequestVar('url');
                preg_match('@^(?:http://)?([^/]+)@i', $url, $urlmatches);
                $host = "http://" . str_ireplace('www.', '', $urlmatches[1]);
                if ($host != '')
                {      
                        // If no site ID, lets look up URL...
                        $idsiteRow = Piwik_Tracker::getDatabase()->fetch("
                                                SELECT idsite
                                                FROM piwik_site 
                                                WHERE main_url = ?
                                                LIMIT 1",
                                                array($host)
                        );
                        if ($idsiteRow && count($idsiteRow) > 0)
                        {      
                                $idsite = $idsiteRow['idsite'];
                        }
                }
        }

        if($idsite <= 0)
        {      
                throw new Exception("The 'idsite' is invalid");
        }
        $this->idsite = $idsite;

}

Doing some basic performance testing, the code above only adds on extra DB call which in my circumstances is acceptable. But, if you really wanted, you could add some caching as well to improve speed.



This entry was written by Karl Kopp, posted on Saturday, 31 July 2010 Bookmark the permalink. Follow any comments here with the RSS feed for this post. You can post a comment.

Post a comment

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact me so we can take care of it!

Visit my friends!

A few highly recommended friends...

About

Some semi-interesting ramblings from a technology geek (me, Karl Kopp) about some future adventures...