Add sites to Piwik automatically

anhkiet

Newbie
Joined
Aug 18, 2012
Messages
17
Reaction score
14
I will try something I have not done before. I will release personal scripts that I use to help others who cannot program. If this is too time consuming due to support, I will stop it. This first release is a hook for adding sites to piwik (1.8.4) passively. When it encounters a domain that it can't match to what's in the database, it adds it automagically. I tried to post example, but the damn thing won't let me because it contains URLs. Essentially it looks at the URL to see if it knows about the site, and if it does not, it adds it to Piwik.

[remove]Originally I wanted to post the code here, but I thought it would be inconvenient for me to update/document the changes in the future, so I've put it on a new blog I setup[/remove], I guess I'll add the code here because I can't link out. What a frustrating experience. You can see the blog post URL if you run this in your address bar, be sure the javascript: portion does not get stripped out:

Code:
javascript: a=[];a.push('mutedsignals');a.push(['c','o','m'].join(''));a.unshift('www');a.join('.')+['','software','automatically-add-websites-in-piwik',''].join('/')

Anyway, this should theoretically work with the existing tracking code but it is not guaranteed to be backward compatible. I recommend saving this file to track.php and test it out separately, I've put sample javascript tracking code in my blog post if you are so inclined. I might put all of this on github for ease of maintainability in the future if anyone is interested.

PHP:
// Put this into your piwik.php

function getId($url) {
  $token = 'SET YOUR TOKEN HERE'; // IMPORTANT, DON'T FORGET
  Piwik_FrontController::getInstance()->init();
 
  $parts = parse_url(strtolower($url));
  $name = $parts['host'];
  $url = "$parts[scheme]://$parts[host]";
 
  $request = new Piwik_API_Request("
    method=SitesManager.getSitesIdFromSiteUrl
    &url=$url
    &format=PHP
    &token_auth=$token");
  $result = $request->process();
  $ids = unserialize($result);
 
  if (count($ids) === 1) {
    return $ids[0]['idsite'];
  } else if (count($ids) < 1) {
    $request = new Piwik_API_Request("
      method=SitesManager.addSite
      &siteName=$name
      &urls=$url
      &timezone=America/Los_Angeles
      &format=PHP
      &token_auth=$token");
    $result = $request->process();
    return unserialize($result);
  }
}
 
// ... later in the file, after all the other require_once ...
 
require_once PIWIK_INCLUDE_PATH .'/core/API/Request.php';
require_once PIWIK_INCLUDE_PATH .'/core/Loader.php';
 
// ... then before the tracking code, the last if block ...
 
$_GET['idsite'] = getId($_GET['url']);
 
Back
Top