Skip to content

Commit

Permalink
Fixes #1446
Browse files Browse the repository at this point in the history
 * refreshed whole tracking code page. Refactored code to reuse in Installation and in the piwik.org docs at http://piwik.org/docs/tracking-api/ (upcoming)
 * inviting externals devs to submit the Tracking API Client in their languages (currently in PHP, could be in Perl, python, java etc)
 * Comments in PiwikTracker
 * Removed unused admin UI strings
  • Loading branch information
matt committed Jul 8, 2010
1 parent 3436f55 commit 1de54c3
Show file tree
Hide file tree
Showing 11 changed files with 398 additions and 130 deletions.
222 changes: 154 additions & 68 deletions core/Tracker/PiwikTracker.php
Expand Up @@ -3,17 +3,34 @@
* Piwik - Open source web analytics
*
* Client to record visits, page views, Goals, in a Piwik server.
* For more information, see http://piwik.org/XXXXXXXXXX
* For more information, see http://piwik.org/docs/tracking-api/
*
* Note: Piwik Cookies are not forwarded in the request and from the response
*
* @license released under BSD License http://www.opensource.org/licenses/bsd-license.php
* @version $Id$
* @link http://piwik.org/docs/tracking-api/
*/
class PiwikTracker
{
static public $API_URL = 'http://localhost/trunk/piwik.php';
/**
* Piwik base URL, for example http://example.org/piwik/
* Must be set before using the class by calling
* PiwikTracker::$url = 'http://yourwebsite.org/piwik/';
*
* @var string
*/
static public $URL = '';

const VERSION = 1;

/**
* Builds a PiwikTracker object, used to track visits, pages and Goal conversions
* for a specific website, by using the Piwik Tracking API.
*
* @param $idSite Id site to be tracked
* @param $apiUrl If set, will overwrite PiwikTracker::$url
*/
function __construct( $idSite, $apiUrl = false )
{
$this->userAgent = false;
Expand All @@ -32,83 +49,57 @@ function __construct( $idSite, $apiUrl = false )
$this->acceptLanguage = @$_SERVER['HTTP_ACCEPT_LANGUAGE'];
$this->userAgent = @$_SERVER['HTTP_USER_AGENT'];
if(!empty($apiUrl)) {
self::$API_URL = $apiUrl;
self::$URL = $apiUrl;
}
}

protected function sendRequest($url)
{
if(function_exists('stream_context_create')) {
$timeout = 600; // Allow debug while blocking the request
$stream_options = array(
'http' => array(
'user_agent' => $this->userAgent,
'header' => "Accept-Language: " . $this->acceptLanguage . "\r\n" .
"Cookie: \r\n",
'timeout' => $timeout, // PHP 5.2.1
)
);
$ctx = stream_context_create($stream_options);
}
$response = @file_get_contents($url, 0, $ctx);
return $response;
}

/**
* Tracks a page view
*
* @param $documentTitle string Page view name as it will appear in Piwik reports
* @return string Response
*/
public function doTrackPageView( $documentTitle )
{
$url = $this->getUrlTrackPageView($documentTitle);
return $this->sendRequest($url);
}

public function doTrackAction($actionUrl, $actionType)
{
// Referer could be udpated to be the current URL temporarily (mimic JS behavior)
$url = $this->getUrlTrackAction($actionUrl, $actionType);
return $this->sendRequest($url);
}

/**
* Tracks a Goal
*
* @param $idGoal int Id Goal to record a conversion
* @param $revenue int Revenue for this conversion
* @return string Response
*/
public function doTrackGoal($idGoal, $revenue = false)
{
$url = $this->getUrlTrackGoal($idGoal, $revenue);
return $this->sendRequest($url);
}

public function getUrlTrackPageView( $documentTitle = false )
{
$url = $this->getRequest( $this->idSite );
if(!empty($documentTitle)) {
$url .= '&action_name=' . urlencode($documentTitle);
}
return $url;
}

public function getUrlTrackAction($actionUrl, $actionType)
{
$url = $this->getRequest( $this->idSite );
$url .= '&'.$actionType.'=' . $actionUrl .
'&redirect=0';

return $url;
}

public function getUrlTrackGoal($idGoal, $revenue = false)
/**
* Tracks a download or outlink
*
* @param $actionUrl URL of the download or outlink
* @param $actionType Type of the action: 'download' or 'link'
* @return string Response
*/
public function doTrackAction($actionUrl, $actionType)
{
$url = $this->getRequest( $this->idSite );
$url .= '&idgoal=' . $idGoal;
if(!empty($revenue)) {
$url .= '&revenue=' . $revenue;
}
return $url;
// Referer could be udpated to be the current URL temporarily (to mimic JS behavior)
$url = $this->getUrlTrackAction($actionUrl, $actionType);
return $this->sendRequest($url);
}

public function setUrl( $url )
public function setUrl( $url )
{
$this->pageUrl = $url;
}
public function setIp($ip)

public function setUrlReferer( $url )
{
$this->ip = $ip;
$this->urlReferer = $url;
}

public function setCustomData( $data )
Expand All @@ -126,11 +117,6 @@ public function setUserAgent($userAgent)
$this->userAgent = $userAgent;
}

public function setForceVisitDateTime($dateTime)
{
$this->forcedDatetime = $dateTime;
}

public function setLocalTime($time)
{
list($hour, $minute, $second) = explode(':', $time);
Expand All @@ -145,11 +131,6 @@ public function setResolution($width, $height)
$this->height = $height;
}

public function setUrlReferer( $url )
{
$this->urlReferer = $url;
}

public function setBrowserHasCookies( $bool )
{
$this->hasCookies = $bool ;
Expand All @@ -169,10 +150,85 @@ public function setPlugins($flash = false, $java = false, $director = false, $qu
'&ag='.(int)$silverlight
;
}

// Note: this will only work when used in tests
public function setForceVisitDateTime($dateTime)
{
$this->forcedDatetime = $dateTime;
}

// Note: this will only work when used in tests
public function setIp($ip)
{
$this->ip = $ip;
}

/**
* @see doTrackPageView()
*/
public function getUrlTrackPageView( $documentTitle = false )
{
$url = $this->getRequest( $this->idSite );
if(!empty($documentTitle)) {
$url .= '&action_name=' . urlencode($documentTitle);
}
return $url;
}

/**
* @see doTrackGoal()
*/
public function getUrlTrackGoal($idGoal, $revenue = false)
{
$url = $this->getRequest( $this->idSite );
$url .= '&idgoal=' . $idGoal;
if(!empty($revenue)) {
$url .= '&revenue=' . $revenue;
}
return $url;
}

/**
* @see doTrackAction()
*/
public function getUrlTrackAction($actionUrl, $actionType)
{
$url = $this->getRequest( $this->idSite );
$url .= '&'.$actionType.'=' . $actionUrl .
'&redirect=0';

return $url;
}

protected function sendRequest($url)
{
if(function_exists('stream_context_create')) {
$timeout = 600; // Allow debug while blocking the request
$stream_options = array(
'http' => array(
'user_agent' => $this->userAgent,
'header' => "Accept-Language: " . $this->acceptLanguage . "\r\n" .
"Cookie: \r\n",
'timeout' => $timeout, // PHP 5.2.1
)
);
$ctx = stream_context_create($stream_options);
}
$response = @file_get_contents($url, 0, $ctx);
return $response;
}

protected function getRequest( $idSite )
{
$url = self::$API_URL .
if(empty(self::$URL))
{
throw new Exception('You must first set the Piwik Tracker URL by calling PiwikTracker::$URL = \'http://your-website.org/piwik/\';');
}
if(strpos(self::$URL, '/piwik.php') === false)
{
self::$URL .= '/piwik.php';
}
$url = self::$URL .
'?idsite=' . $idSite .
'&rec=1' .
'&apiv=' . self::VERSION .
Expand All @@ -198,6 +254,12 @@ protected function getRequest( $idSite )
return $url;
}

/**
* If current URL is "http://example.org/dir1/dir2/index.php?param1=value1&param2=value2"
* will return "/dir1/dir2/index.php"
*
* @return string
*/
static protected function getCurrentScriptName()
{
$url = '';
Expand All @@ -221,6 +283,13 @@ static protected function getCurrentScriptName()
return $url;
}


/**
* If the current URL is 'http://example.org/dir1/dir2/index.php?param1=value1&param2=value2"
* will return 'http'
*
* @return string 'https' or 'http'
*/
static protected function getCurrentScheme()
{
if(isset($_SERVER['HTTPS'])
Expand All @@ -231,6 +300,12 @@ static protected function getCurrentScheme()
return 'http';
}

/**
* If current URL is "http://example.org/dir1/dir2/index.php?param1=value1&param2=value2"
* will return "http://example.org"
*
* @return string
*/
static protected function getCurrentHost()
{
if(isset($_SERVER['HTTP_HOST'])) {
Expand All @@ -239,6 +314,12 @@ static protected function getCurrentHost()
return 'unknown';
}

/**
* If current URL is "http://example.org/dir1/dir2/index.php?param1=value1&param2=value2"
* will return "?param1=value1&param2=value2"
*
* @return string
*/
static protected function getCurrentQueryString()
{
$url = '';
Expand All @@ -250,6 +331,11 @@ static protected function getCurrentQueryString()
return $url;
}

/**
* Returns the current full URL (scheme, host, path and query string.
*
* @return string
*/
static protected function getCurrentUrl()
{
return self::getCurrentScheme() . '://'
Expand Down
4 changes: 3 additions & 1 deletion core/View.php
Expand Up @@ -105,7 +105,9 @@ public function __get($key)
}

/**
* Render view
* Renders the current view.
*
* @return string Generated template
*/
public function render()
{
Expand Down
6 changes: 2 additions & 4 deletions lang/en.php
Expand Up @@ -454,9 +454,6 @@
'Installation_DatabaseClientVersion' => 'Database client version',
'Installation_DatabaseCreation' => 'Database creation',
'Installation_PleaseFixTheFollowingErrors' => 'Please fix the following errors',
'Installation_JsTag' => 'JavaScript tag',
'Installation_JsTagHelp' => '<p>To count all visitors, you must insert the JavaScript code on all of your pages.</p><p>Your pages do not have to be made with PHP, Piwik will work on all kinds of pages (whether it is HTML, ASP, Perl or any other languages).</p><p>Here is the code you have to insert: (copy and paste on all your pages) </p>',
'Installation_JsTagHelpTitle' => 'How to insert the tag in your websites?',
'Installation_LargePiwikInstances' => 'Help for large Piwik instances',
'Installation_JsTagArchivingHelp' => 'For medium and high traffic websites, check out the <a target="_blank" href="http://piwik.org/docs/setup-auto-archiving/">How to setup auto archiving page</a> to make Piwik run really fast!',
'Installation_Congratulations' => 'Congratulations',
Expand Down Expand Up @@ -618,11 +615,12 @@
'SecurityInfo_Result' => 'Result',
'SitesManager_PluginDescription' => 'Websites Management in Piwik: Add a new Website, Edit an existing one, Show the Javascript code to include on your pages. All the actions are also available through the API.',
'SitesManager_Sites' => 'Websites',
'SitesManager_TrackingTags' => 'Tracking tags for %s',
'SitesManager_WebsitesManagement' => 'Websites Management',
'SitesManager_MainDescription' => 'Your Web Analytics reports need Websites! Add, update, delete Websites, and show the JavaScript to insert in your pages.',
'SitesManager_JsTrackingTag' => 'JavaScript Tracking Tag',
'SitesManager_JsTrackingTagHelp' => 'Here is the JavaScript Tracking tag to include on all your pages',
'SitesManager_ShowTrackingTag' => 'show tracking tag',
'SitesManager_ShowTrackingTag' => 'show tracking tags',
'SitesManager_NoWebsites' => 'You don\'t have any website to administrate.',
'SitesManager_AddSite' => 'Add a new website',
'SitesManager_AliasUrlHelp' => "It is recommended, but not required, to specify the various URLs, one per line, that your visitors use to access this website.\nAlias URLs for a website will not appear in the Referers > Websites report.\nNote that it is not necessary to specify the URLs with and without 'www' as Piwik automatically considers both.",
Expand Down
15 changes: 15 additions & 0 deletions misc/ExamplePiwikTracker.php
@@ -0,0 +1,15 @@
<?php
// Example file to demonstrate PiwikTracker.php
// See http://piwik.org/docs/tracking-api/
require_once '../core/Tracker/PiwikTracker.php';
PiwikTracker::$URL = 'http://localhost/trunk/';

$piwikTracker = new PiwikTracker( $idSite = 1 );
// You can manually set the Visitor details (resolution, time, plugins)
// See all other ->set* functions available in the PiwikTracker class
$piwikTracker->setResolution(1600, 1400);

// Sends Tracker request via http
$piwikTracker->doTrackPageView('Document title of current page view');
// You can also track Goal conversions
$piwikTracker->doTrackGoal($idGoal = 1, $revenue = 42);

0 comments on commit 1de54c3

Please sign in to comment.