Inheritance: extends Tracker
コード例 #1
0
 public function test_response_ShouldSend400ResponseCode_IfInvalidRequestParameterIsGiven()
 {
     $url = $this->tracker->getUrlTrackPageView('Test');
     $url .= '&cid=' . str_pad('1', 16, '1');
     $this->assertResponseCode(200, $url);
     $this->assertResponseCode(400, $url . '1');
     // has to be 16 char, but is 17 now
 }
コード例 #2
0
 public function test_response_ShouldContainBulkTrackingApiResponse()
 {
     $this->tracker->doTrackPageView('Test');
     $this->tracker->doTrackPageView('Test');
     // test skipping invalid site errors
     $this->tracker->setIdSite(5);
     $this->tracker->doTrackPageView('Test');
     $this->tracker->setIdSite(1);
     $this->tracker->doTrackPageView('Test');
     // another invalid one to further test the invalid request indices in the result
     $this->tracker->setIdSite(7);
     $this->tracker->doTrackPageView('Test');
     $response = $this->tracker->doBulkTrack();
     $this->assertEquals('{"status":"success","tracked":3,"invalid":2,"invalid_indices":[2,4]}', $response);
 }
コード例 #3
0
 /**
  * Returns the base URL for the piwik server.
  */
 protected function getBaseUrl()
 {
     if (!empty($this->baseApiUrl)) {
         return $this->baseApiUrl;
     }
     return parent::getBaseUrl();
 }
コード例 #4
0
ファイル: PiwikTracker.php プロジェクト: nomoto-ubicast/piwik
 /**
  * Builds a PiwikTracker object, used to track visits, pages and Goal conversions 
  * for a specific website, by using the Piwik Tracking API.
  * 
  * @param int $idSite Id site to be tracked
  * @param string $apiUrl "http://example.org/piwik/" or "http://piwik.example.org/"
  * 						 If set, will overwrite PiwikTracker::$URL
  */
 function __construct($idSite, $apiUrl = false)
 {
     $this->cookieSupport = true;
     $this->userAgent = false;
     $this->localHour = false;
     $this->localMinute = false;
     $this->localSecond = false;
     $this->hasCookies = false;
     $this->plugins = false;
     $this->visitorCustomVar = false;
     $this->pageCustomVar = false;
     $this->customData = false;
     $this->forcedDatetime = false;
     $this->token_auth = false;
     $this->attributionInfo = false;
     $this->ecommerceLastOrderTimestamp = false;
     $this->ecommerceItems = array();
     $this->requestCookie = '';
     $this->idSite = $idSite;
     $this->urlReferrer = @$_SERVER['HTTP_REFERER'];
     $this->pageUrl = self::getCurrentUrl();
     $this->ip = @$_SERVER['REMOTE_ADDR'];
     $this->acceptLanguage = @$_SERVER['HTTP_ACCEPT_LANGUAGE'];
     $this->userAgent = @$_SERVER['HTTP_USER_AGENT'];
     if (!empty($apiUrl)) {
         self::$URL = $apiUrl;
     }
     $this->setNewVisitorId();
     // Allow debug while blocking the request
     $this->requestTimeout = 600;
     $this->doBulkRequests = false;
     $this->storedTrackingActions = array();
 }
コード例 #5
0
 public function __construct()
 {
     $this->url = ConfigQuery::read('hookpiwikanalytics_url', false);
     $this->website_id = ConfigQuery::read('hookpiwikanalytics_website_id', false);
     \PiwikTracker::$URL = $this->url;
     $this->tracker = new \PiwikTracker($this->website_id);
 }
コード例 #6
0
 /**
  * Builds a PiwikTracker object, used to track visits, pages and Goal conversions 
  * for a specific website, by using the Piwik Tracking API.
  * 
  * @param int $idSite Id site to be tracked
  * @param string $apiUrl "http://example.org/piwik/" or "http://piwik.example.org/"
  * 						 If set, will overwrite PiwikTracker::$URL
  */
 function __construct($idSite, $apiUrl = false)
 {
     $this->cookieSupport = true;
     $this->userAgent = false;
     $this->localHour = false;
     $this->localMinute = false;
     $this->localSecond = false;
     $this->hasCookies = false;
     $this->plugins = false;
     $this->visitorCustomVar = false;
     $this->pageCustomVar = false;
     $this->customData = false;
     $this->forcedDatetime = false;
     $this->token_auth = false;
     $this->attributionInfo = false;
     $this->ecommerceLastOrderTimestamp = false;
     $this->ecommerceItems = array();
     $this->requestCookie = '';
     $this->idSite = $idSite;
     $this->urlReferrer = @$_SERVER['HTTP_REFERER'];
     $this->pageUrl = self::getCurrentUrl();
     $this->ip = @$_SERVER['REMOTE_ADDR'];
     $this->acceptLanguage = @$_SERVER['HTTP_ACCEPT_LANGUAGE'];
     $this->userAgent = @$_SERVER['HTTP_USER_AGENT'];
     if (!empty($apiUrl)) {
         self::$URL = $apiUrl;
     }
     $this->visitorId = substr(md5(uniqid(rand(), true)), 0, self::LENGTH_VISITOR_ID);
 }
コード例 #7
0
 private function doTrackNumberOfRequests($numRequests, $inBulk = true)
 {
     $inBulk && $this->tracker->enableBulkTracking();
     for ($i = 0; $i < $numRequests; $i++) {
         $response = $this->tracker->doTrackPageView('Test');
     }
     if ($inBulk) {
         $response = $this->tracker->doBulkTrack();
     }
     return $response;
 }
コード例 #8
0
 private static function settingInvalidVisitorIdShouldThrow(PiwikTracker $t)
 {
     try {
         $t->setVisitorId('test');
         $this->fail('should throw');
     } catch (Exception $e) {
         //OK
     }
     try {
         $t->setVisitorId('61e8');
         $this->fail('should throw');
     } catch (Exception $e) {
         //OK
     }
     try {
         $t->setVisitorId('61e8cc2d51fea26dabcabcabc');
         $this->fail('should throw');
     } catch (Exception $e) {
         //OK
     }
 }
コード例 #9
0
 public function test_response_ShouldContainBulkTrackingApiResponse()
 {
     $this->tracker->doTrackPageView('Test');
     $this->tracker->doTrackPageView('Test');
     // test skipping invalid site errors
     $this->tracker->setIdSite(5);
     $this->tracker->doTrackPageView('Test');
     $response = $this->tracker->doBulkTrack();
     $this->assertEquals('{"status":"success","tracked":2,"invalid":1}', $response);
 }
コード例 #10
0
	/**
	 * 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;
    	$this->localHour = false;
    	$this->localMinute = false;
    	$this->localSecond = false;
    	$this->hasCookies = false;
    	$this->plugins = false;
    	$this->customData = false;
    	$this->forcedDatetime = false;

    	$this->idSite = $idSite;
    	$this->urlReferer = @$_SERVER['HTTP_REFERER'];
    	$this->pageUrl = self::getCurrentUrl();
    	$this->ip = @$_SERVER['REMOTE_ADDR'];
    	$this->acceptLanguage = @$_SERVER['HTTP_ACCEPT_LANGUAGE'];
    	$this->userAgent = @$_SERVER['HTTP_USER_AGENT'];
    	if(!empty($apiUrl)) {
    		self::$URL = $apiUrl;
    	}
    }
コード例 #11
0
ファイル: Aplicativo.php プロジェクト: netinhoteixeira/pudim
 /**
  * Inicia a análise de tráfego.
  */
 private function iniciarAnaliseTrafego()
 {
     if ($this->_configuracao->get($this->_servidor . '.piwik_id')) {
         require_once implode(DIRECTORY_SEPARATOR, [__DIR__, '..', '..', '..', '..', 'library', 'PiwikTracker.php']);
         $piwikTracker = new \PiwikTracker($this->_configuracao->get($this->_servidor . '.piwik_id'), $this->_configuracao->get($this->_servidor . '.piwik_url'));
         if ($this->_configuracao->get($this->_servidor . '.piwik_token_auth')) {
             $piwikTracker->setTokenAuth($this->_configuracao->get($this->_servidor . '.piwik_token_auth'));
         }
         if (isset($_SERVER['HTTP_REFERER'])) {
             $piwikTracker->setReferrer($_SERVER['HTTP_REFERER']);
         }
         // detecta o endereço da internet do cliente
         if (isset($_SERVER['HTTP_CLIENT_IP'])) {
             $piwikTracker->setIp($_SERVER['HTTP_CLIENT_IP']);
         } else {
             if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                 $piwikTracker->setIp($_SERVER['HTTP_X_FORWARDED_FOR']);
             } else {
                 if (isset($_SERVER['HTTP_X_FORWARDED'])) {
                     $piwikTracker->setIp($_SERVER['HTTP_X_FORWARDED']);
                 } else {
                     if (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
                         $piwikTracker->setIp($_SERVER['HTTP_FORWARDED_FOR']);
                     } else {
                         if (isset($_SERVER['HTTP_FORWARDED'])) {
                             $piwikTracker->setIp($_SERVER['HTTP_FORWARDED']);
                         } else {
                             if (isset($_SERVER['REMOTE_ADDR'])) {
                                 $piwikTracker->setIp($_SERVER['REMOTE_ADDR']);
                             } else {
                                 $piwikTracker->setIp('DESCONHECIDO');
                             }
                         }
                     }
                 }
             }
         }
         $piwikTracker->setUserAgent($_SERVER['HTTP_USER_AGENT']);
         if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
             $idioma = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
             $piwikTracker->setBrowserLanguage($idioma[0]);
             unset($idioma);
         }
         if ($this->postExists('localTime')) {
             $piwikTracker->setLocalTime($this->post('localTime'));
         }
         if ($this->postExists('screenWidth') && $this->postExists('screenHeight')) {
             $piwikTracker->setResolution($this->post('screenWidth'), $this->post('screenHeight'));
         }
         if ($this->postExists('position')) {
             $posicao = $this->post('position');
             $piwikTracker->setLongitude($posicao['longitude']);
             $piwikTracker->setLatitude($posicao['latitude']);
             unset($posicao);
         }
     } else {
         $piwikTracker = null;
     }
     return $piwikTracker;
 }
コード例 #12
0
function Piwik_getUrlTrackGoal($idSite, $idGoal, $revenue = false)
{
    $tracker = new PiwikTracker($idSite);
    return $tracker->getUrlTrackGoal($idGoal, $revenue);
}
コード例 #13
0
<?php

Route::get('/piwiktracker/js', function () {
    $js = PiwikTracker::getJs();
    if (false === $js) {
        // We failed to get the javascript code
        return App::abort(500);
    }
    return Response::make($js, 200, ['Content-Type' => 'application/javascript']);
});
Route::get('/piwiktracker/php', function () {
    $gif = PiwikTracker::proxy();
    if (false === $gif) {
        // We failed to call the piwik tracker
        return App::abort(500);
    }
    return Response::make($gif, 200, ['Content-Type' => 'image/gif']);
});
<?php
// Script that creates 100 websites, then outputs a IMG that records a pageview in each website
// Used initially to test how to handle cookies for this use case (see http://dev.piwik.org/trac/ticket/409)
exit;

define('PIWIK_INCLUDE_PATH', '..');
define('PIWIK_ENABLE_DISPATCH', false);
define('PIWIK_ENABLE_ERROR_HANDLER', false);
define('PIWIK_ENABLE_SESSION_START', false);
require_once PIWIK_INCLUDE_PATH . "/index.php";
require_once PIWIK_INCLUDE_PATH . "/core/API/Request.php";
require_once PIWIK_INCLUDE_PATH . "/libs/PiwikTracker/PiwikTracker.php";

Piwik_FrontController::getInstance()->init();
Piwik::setUserIsSuperUser();
$count = 100;
for($i = 0; $i <= $count; $i++)
{
	$id = Piwik_SitesManager_API::getInstance()->addSite(Piwik_Common::getRandomString(), 'http://piwik.org');
    $t = new PiwikTracker($id, 'http://localhost/trunk/piwik.php');
    echo $id . " <img width=100 height=10 border=1 src='".$t->getUrlTrackPageView('title') ."'><br/>";
}

コード例 #15
0
 /**
  * Returns a PiwikTracker object that you can then use to track pages or goals.
  *
  * @param         $idSite
  * @param         $dateTime
  * @param boolean $defaultInit If set to true, the tracker object will have default IP, user agent, time, resolution, etc.
  *
  * @return PiwikTracker
  */
 public static function getTracker($idSite, $dateTime, $defaultInit = true, $useLocal = false)
 {
     if ($useLocal) {
         require_once PIWIK_INCLUDE_PATH . '/tests/LocalTracker.php';
         $t = new Piwik_LocalTracker($idSite, self::getTrackerUrl());
     } else {
         $t = new PiwikTracker($idSite, self::getTrackerUrl());
     }
     $t->setForceVisitDateTime($dateTime);
     if ($defaultInit) {
         $t->setIp('156.5.3.2');
         // Optional tracking
         $t->setUserAgent("Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.2.6) Gecko/20100625 Firefox/3.6.6 (.NET CLR 3.5.30729)");
         $t->setBrowserLanguage('fr');
         $t->setLocalTime('12:34:06');
         $t->setResolution(1024, 768);
         $t->setBrowserHasCookies(true);
         $t->setPlugins($flash = true, $java = true, $director = false);
     }
     return $t;
 }
コード例 #16
0
function saveInPiwik($logHash)
{
    echo $logHash["ip"] . " " . $logHash["status"] . " " . $logHash["utcdatetime"] . " " . $logHash["path"] . " (" . $logHash["agent"] . ")... ";
    global $idSite, $webUrl, $piwikUrl, $tokenAuth;
    $t = new PiwikTracker($idSite, $piwikUrl);
    $t->setUserAgent($logHash["agent"]);
    $t->setTokenAuth($tokenAuth);
    $t->setIp($logHash["ip"]);
    $t->setForceVisitDateTime($logHash["utcdatetime"]);
    $t->setUrlReferrer($logHash["referer"]);
    $t->setUrl($webUrl . $logHash["path"]);
    $HTTPResult = false;
    $HTTPFailCount = 0;
    do {
        $HTTPResult = $t->doTrackPageView(basename($logHash["path"]));
        if (!$HTTPResult) {
            $HTTPFailCount++;
            echo "FAIL\n";
            echo "Unable to save (via HTTP) last log entry for the {$HTTPFailCount} time, retrying in a few seconds...\n";
            sleep($HTTPFailCount);
        } else {
            echo "SUCCESS\n";
        }
    } while (!$HTTPResult);
}
コード例 #17
0
ファイル: class_piwik.php プロジェクト: a2call/commsy
   private function _getInfosForBeforeBodyEndAsHTMLPHP () {
   	$retour = LF.'<!-- PIWIK tracking via PHP - BEGIN -->'.LF;

   	$tracking_array = array();
   	
   	// opt-out
   	if ( !empty($_COOKIE['CommSyAGBPiwik'])
   			and $_COOKIE['CommSyAGBPiwik'] == 1
   	   ) {
   		$retour .= '<!-- don\'t track - opt-out is activated -->'.LF;
   	}
   	// track
   	else {
   	   if ( $this->_environment->inServer() ) {
   		   $info_array = $this->_getInfosForTracking($this->_environment->getServerItem());
   		   if ( !empty($info_array) ) {
   			   $tracking_array[] = $info_array;
   		   }
   	   } else {
   	      $info_array = $this->_getInfosForTracking($this->_environment->getServerItem());
   		   if ( !empty($info_array) ) {
   			   $tracking_array[] = $info_array;
   	   	}
   	      $info_array = $this->_getInfosForTracking($this->_environment->getCurrentPortalItem());
   		   if ( !empty($info_array) ) {
   			   $tracking_array[] = $info_array;
   		   }
   	   }
   	}
   	
   	if ( !empty($tracking_array) ) {
   		
   		// site title
   		$title = '';
   		$current_context_item = $this->_environment->getCurrentContextItem();
   		if ( !empty($current_context_item) ) {
   			if ( !$current_context_item->isServer()
   				  and !$current_context_item->isPortal()
   				) {
   				$current_portal = $current_context_item->getContextItem();
   				if ( !empty($current_portal) ) {
   					$title .= $current_portal->getTitle().' > ';
   				}
   			}
   			$title .= $current_context_item->getTitle().' > ';
   			$title .= $this->_environment->getCurrentModule().' > ';
   			$title .= $this->_environment->getCurrentFunction();
   			if ( !empty($_GET['iid'])) {
   				$title .= ' > '.$_GET['iid'];
   			}
   		}
   		
   		// tracking
   		include_once('plugins/'.$this->_identifier.'/PiwikTracker.php');
   		foreach ($tracking_array as $site_array) {
   			if ( !empty($site_array['server_url'])
   				  and !empty($site_array['site_id'])
   				) {
   				if ( empty($site_array['server_https'])
   				     or $site_array['server_https'] == 'commsy'
   					) {
   					$c_commsy_domain = $this->_environment->getConfiguration('c_commsy_domain');
   					if ( stristr($c_commsy_domain,'https') ) {
   						$http = 'https';
   					} else {
   						$http = 'http';
   					}
   					unset($c_commsy_domain);
   				} else {
   					$http = $site_array['server_https'];
   				}
   				$t = new PiwikTracker($site_array['site_id'],$http.'://'.$site_array['server_url'].'/piwik.php');
   				$t->setRequestTimeout($this->_timeout_ms); // in milliseconds - to avoid long waiting time, when piwik server is gone or network is down
   				
   				// proxy
   				if ( $this->_environment->getConfiguration('c_proxy_ip') ) {
   					$proxy = $this->_environment->getConfiguration('c_proxy_ip');
   		   		if ( $this->_environment->getConfiguration('c_proxy_port') ) {
  		   				$proxy .= ':'.$this->_environment->getConfiguration('c_proxy_port');
      				}
      				$t->setProxy($proxy);
     				}
   				
   				$result = $t->doTrackPageView($title);
   	         $retour .= '<!-- tracking '.$site_array['site_id'].' -->'.LF;
   			   if ( empty($result) ) {
   			   	$retour .= '   <!-- don\'t receive result from tracking for site '.$site_array['site_id'].' -->'.LF;
   				}
   			}
   		}
   	}
   	
   	$retour .= '<!-- PIWIK tracking via PHP - END -->'.LF;
   	return $retour;
   }
コード例 #18
0
ファイル: AuthController.php プロジェクト: Danny-P/ViMbAdmin
 public function setupAction()
 {
     if ($this->getD2EM()->getRepository('\\Entities\\Admin')->getCount() != 0) {
         $this->addMessage(_("Admins already exist in the system."), OSS_Message::INFO);
         $this->_redirect('auth/login');
     }
     if ($this->getAuth()->getIdentity()) {
         $this->addMessage(_('You are already logged in.'), OSS_Message::INFO);
         $this->_redirect('domain/list');
     }
     $this->view->form = $form = new ViMbAdmin_Form_Admin_AddEdit();
     $form->removeElement('active');
     $form->removeElement('super');
     $form->removeElement('welcome_email');
     if (!isset($this->_options['securitysalt']) || strlen($this->_options['securitysalt']) != 64) {
         $this->view->saltSet = false;
         $randomSalt = $this->view->randomSalt = OSS_String::salt(64);
         $form->getElement('salt')->setValue($randomSalt);
         $this->view->rememberSalt = OSS_String::salt(64);
         $this->view->passwordSalt = OSS_String::salt(64);
     } else {
         $this->view->saltSet = true;
         if ($this->getRequest()->isPost() && $form->isValid($_POST)) {
             if ($form->getElement('salt')->getValue() != $this->_options['securitysalt']) {
                 $this->addMessage(_("Incorrect security salt provided. Please copy and paste it from the <code>application.ini</code> file."), OSS_Message::INFO);
             } else {
                 $admin = new \Entities\Admin();
                 $admin->setUsername($form->getValue('username'));
                 $admin->setPassword(OSS_Auth_Password::hash($form->getValue('password'), $this->_options['resources']['auth']['oss']));
                 $admin->setSuper(true);
                 $admin->setActive(true);
                 $admin->setCreated(new \DateTime());
                 $admin->setModified(new \DateTime());
                 $this->getD2EM()->persist($admin);
                 // we need to populate the Doctine migration table
                 $dbversion = new \Entities\DatabaseVersion();
                 $dbversion->setVersion(ViMbAdmin_Version::DBVERSION);
                 $dbversion->setName(ViMbAdmin_Version::DBVERSION_NAME);
                 $dbversion->setAppliedOn(new \DateTime());
                 $this->getD2EM()->persist($dbversion);
                 $this->getD2EM()->flush();
                 try {
                     $mailer = $this->getMailer();
                     $mailer->setSubject(_('ViMbAdmin :: Your New Administrator Account'));
                     $mailer->addTo($admin->getUsername());
                     $mailer->setFrom($this->_options['server']['email']['address'], $this->_options['server']['email']['name']);
                     $this->view->username = $admin->getUsername();
                     $this->view->password = $form->getValue('password');
                     $mailer->setBodyText($this->view->render('admin/email/new_admin.phtml'));
                     $mailer->send();
                 } catch (Zend_Mail_Exception $e) {
                     $this->addMessage(_('Could not send welcome email to the new administrator. 
                         Please ensure you have configured a mail relay server in your <code>application.ini</code>.'), OSS_Message::ALERT);
                 }
                 $this->addMessage(_('Your administrator account has been added. Please log in below.'), OSS_Message::SUCCESS);
             }
             if (!(isset($this->_options['skipInstallPingback']) && $this->_options['skipInstallPingback'])) {
                 try {
                     // Try and track new installs to see if it is worthwhile continuing development
                     include_once APPLICATION_PATH . '/../public/PiwikTracker.php';
                     if (class_exists('PiwikTracker')) {
                         if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
                             PiwikTracker::$URL = 'https://stats.opensolutions.ie/';
                         } else {
                             PiwikTracker::$URL = 'http://stats.opensolutions.ie/';
                         }
                         $piwikTracker = new PiwikTracker($idSite = 5);
                         $piwikTracker->doTrackPageView('New V3 Install Completed');
                         $piwikTracker->doTrackGoal($idGoal = 2, $revenue = 1);
                     }
                 } catch (Exception $e) {
                 }
             }
             $this->_redirect('auth/login');
         }
     }
 }
コード例 #19
0
<?php

// -- Piwik Tracking API init --
require_once "../../libs/PiwikTracker/PiwikTracker.php";
PiwikTracker::$URL = 'http://localhost/piwik-master/';
// Example 1: Tracks a pageview for Website id = {$IDSITE}
$trackingURL = Piwik_getUrlTrackPageView($idSite = 16, $customTitle = 'This title will appear in the report Actions > Page titles');
?>
<html>
<body>
<!-- Piwik -->
<script type="text/javascript">
    var _paq = _paq || [];
    (function() {
        var u=(("https:" == document.location.protocol) ? "https" : "http") + "://localhost/piwik-master/";
        _paq.push(["setTrackerUrl", u+"piwik.php"]);
        _paq.push(["setSiteId", "16"]);
        var d=document, g=d.createElement("script"), s=d.getElementsByTagName("script")[0]; g.type="text/javascript";
        g.defer=true; g.async=true; g.src=u+"js/piwik.js"; s.parentNode.insertBefore(g,s);
    })();
</script>
<!-- End Piwik Code -->

This page loads a Simple Tracker request to Piwik website id=1

<?php 
echo '<img src="' . htmlentities($trackingURL) . '" alt="" />';
?>
</body>
</html>
コード例 #20
0
ファイル: Tracker.php プロジェクト: FluentDevelopment/piwik
 public static function disconnectCachedDbConnection()
 {
     // code redundancy w/ above is on purpose; above disconnectDatabase depends on method that can potentially be overridden
     if (!is_null(self::$db)) {
         self::$db->disconnect();
         self::$db = null;
     }
 }
 /**
  * Test setting/getting the first party cookie via the PHP Tracking Client
  * @param $t
  */
 private function testFirstPartyCookies(PiwikTracker $t)
 {
     $domainHash = $this->getFirstPartyCookieDomainHash();
     $idCookieName = '_pk_id_1_' . $domainHash;
     $refCookieName = '_pk_ref_1_' . $domainHash;
     $customVarCookieName = '_pk_cvar_1_' . $domainHash;
     $viewts = '1302307497';
     $uuid = 'ca0afe7b6b692ff5';
     $_COOKIE[$idCookieName] = $uuid . '.1302307497.1.' . $viewts . '.1302307497';
     $_COOKIE[$refCookieName] = '["YEAH","RIGHT!",1302307497,"http://referrer.example.org/page/sub?query=test&test2=test3"]';
     $_COOKIE[$customVarCookieName] = '{"1":["VAR 1 set, var 2 not set","yes"],"3":["var 3 set","yes!!!!"]}';
     // test loading 'id' cookie
     self::assertContains("_viewts=" . $viewts, $t->getUrlTrackPageView());
     self::assertEquals($uuid, $t->getVisitorId());
     self::assertEquals($t->getAttributionInfo(), $_COOKIE[$refCookieName]);
     self::assertEquals(array("VAR 1 set, var 2 not set", "yes"), $t->getCustomVariable(1));
     self::assertFalse($t->getCustomVariable(2));
     self::assertEquals(array("var 3 set", "yes!!!!"), $t->getCustomVariable(3));
     self::assertFalse($t->getCustomVariable(4));
     self::assertFalse($t->getCustomVariable(5));
     self::assertFalse($t->getCustomVariable(6));
     self::assertFalse($t->getCustomVariable(-1));
     unset($_COOKIE[$idCookieName]);
     unset($_COOKIE[$refCookieName]);
     unset($_COOKIE[$customVarCookieName]);
 }
コード例 #22
0
<?php

// Example file to demonstrate PiwikTracker.php
// See http://piwik.org/docs/tracking-api/
require_once '../../libs/PiwikTracker/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);
echo 'done';
コード例 #23
0
ファイル: index.php プロジェクト: Ricain/Spic
if ($size == false) {
    header("HTTP/1.0 404 Not Found");
    include __DIR__ . "/private/page/404.page.php";
    exit;
}
$allowed = array("image/gif", "image/jpeg", "image/png");
$supported = false;
foreach ($allowed as $mime) {
    if (strcmp($mime, $size["mime"]) == 0) {
        $supported = true;
    }
}
if (!$supported) {
    header("HTTP/1.0 404 Not Found");
    include __DIR__ . "/private/page/404.page.php";
    exit;
}
if (!util_empty(conf_read("piwikurl")) && !util_empty(conf_read("piwiksiteid")) && !secu_isloged()) {
    include __DIR__ . "/private/api/PiwikTracker.php";
    PiwikTracker::$URL = conf_read("piwikurl");
    $piwikTracker = new PiwikTracker($idSite = intval(conf_read("piwiksiteid")));
    $piwikTracker->doTrackPageView($req . " (" . $size["mime"] . ")");
}
error_reporting(0);
ob_start();
ob_clean();
ob_start("ob_gzhandler");
header("Content-Type: " . $size["mime"]);
ob_end_flush();
readfile($file);
exit;
コード例 #24
0
ファイル: Tracker.php プロジェクト: Abine/piwik
 public static function disconnectDatabase()
 {
     if (isset(self::$db)) {
         self::$db->disconnect();
         self::$db = null;
     }
 }
コード例 #25
0
 private function doPingRequest(\PiwikTracker $tracker, $pingTime, $changeDimensionValues)
 {
     if ($changeDimensionValues) {
         $tracker->setUserAgent(self::CHANGED_USER_AGENT);
         $tracker->setBrowserLanguage(self::CHANGED_BROWSER_LANGUAGE);
         $tracker->setCountry(self::CHANGED_COUNTRY);
         $tracker->setRegion(self::CHANGED_REGION);
     }
     $tracker->setForceVisitDateTime($pingTime);
     $response = $tracker->doPing();
     Fixture::checkResponse($response);
     return $response;
 }
コード例 #26
0
ファイル: Common.php プロジェクト: bossrabbit/piwik
 /**
  * Converts a User ID string to the Visitor ID Binary representation.
  *
  * @param $userId
  * @return string
  */
 public static function convertUserIdToVisitorIdBin($userId)
 {
     require_once PIWIK_INCLUDE_PATH . '/libs/PiwikTracker/PiwikTracker.php';
     $userIdHashed = \PiwikTracker::getUserIdHashed($userId);
     return self::convertVisitorIdToBin($userIdHashed);
 }
コード例 #27
0
 /**
  * @ignore
  */
 protected function sendRequest($url, $method = 'GET', $data = null, $force = false)
 {
     self::$DEBUG_LAST_REQUESTED_URL = $url;
     // if doing a bulk request, store the url
     if ($this->doBulkRequests && !$force) {
         $this->storedTrackingActions[] = $url . (!empty($this->userAgent) ? '&ua=' . urlencode($this->userAgent) : '') . (!empty($this->acceptLanguage) ? '&lang=' . urlencode($this->acceptLanguage) : '');
         // Clear custom variables so they don't get copied over to other users in the bulk request
         $this->clearCustomVariables();
         $this->userAgent = false;
         $this->acceptLanguage = false;
         return true;
     }
     if (function_exists('curl_init') && function_exists('curl_exec')) {
         $options = array(CURLOPT_URL => $url, CURLOPT_USERAGENT => $this->userAgent, CURLOPT_HEADER => true, CURLOPT_TIMEOUT => $this->requestTimeout, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => array('Accept-Language: ' . $this->acceptLanguage));
         if (defined('PATH_TO_CERTIFICATES_FILE')) {
             $options[CURLOPT_CAINFO] = PATH_TO_CERTIFICATES_FILE;
         }
         switch ($method) {
             case 'POST':
                 $options[CURLOPT_POST] = TRUE;
                 break;
             default:
                 break;
         }
         // only supports JSON data
         if (!empty($data)) {
             $options[CURLOPT_HTTPHEADER][] = 'Content-Type: application/json';
             $options[CURLOPT_HTTPHEADER][] = 'Expect:';
             $options[CURLOPT_POSTFIELDS] = $data;
         }
         $ch = curl_init();
         curl_setopt_array($ch, $options);
         ob_start();
         $response = @curl_exec($ch);
         ob_end_clean();
         $content = '';
         if (!empty($response)) {
             list($header, $content) = explode("\r\n\r\n", $response, $limitCount = 2);
         }
     } else {
         if (function_exists('stream_context_create')) {
             $stream_options = array('http' => array('method' => $method, 'user_agent' => $this->userAgent, 'header' => "Accept-Language: " . $this->acceptLanguage . "\r\n", 'timeout' => $this->requestTimeout));
             // only supports JSON data
             if (!empty($data)) {
                 $stream_options['http']['header'] .= "Content-Type: application/json \r\n";
                 $stream_options['http']['content'] = $data;
             }
             $ctx = stream_context_create($stream_options);
             $response = file_get_contents($url, 0, $ctx);
             $content = $response;
         }
     }
     return $content;
 }
コード例 #28
0
 private function trackPageview(\PiwikTracker $tracker, $userId, $url)
 {
     $tracker->setUrl('http://www.example.org' . $url);
     $tracker->setUserId($userId);
     $tracker->doTrackPageView($url);
 }
コード例 #29
0
ファイル: Common.php プロジェクト: a4tunado/piwik
 /**
  * Converts a User ID string to the Visitor ID Binary representation.
  *
  * @param $userId
  * @return string
  */
 public static function convertUserIdToVisitorIdBin($userId)
 {
     $userIdHashed = \PiwikTracker::getUserIdHashed($userId);
     return self::convertVisitorIdToBin($userIdHashed);
 }
コード例 #30
-1
function track($campaign, $keyword)
{
    # Piwik URL
    PiwikTracker::$URL = $GLOBALS['config']['piwik_url'];
    # PiwikTracker
    $piwik = new PiwikTracker($GLOBALS['config']['idsite']);
    # required for setIP()
    $piwik->setTokenAuth($GLOBALS['config']['piwik_token']);
    # IP of the remote client
    $piwik->setIP($_SERVER['REMOTE_ADDR']);
    # User Agent String of the client
    $piwik->setUserAgent($_SERVER['HTTP_USER_AGENT']);
    # get the schema
    $schema = 'https://';
    if (empty($_SERVER['HTTPS']) or $_SERVER['HTTPS'] === 'off') {
        $schema = 'http://';
    }
    # set the tracked URL
    $piwik->setUrl($schema . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']);
    # referer
    $piwik->setUrlReferrer($_SERVER['HTTP_REFERER']);
    # set attribution info (keyword, campaign, et al)
    # http://developer.piwik.org/api-reference/PHP-Piwik-Tracker#setattributioninfo
    # 0 - campaign name
    # 1 - keyword
    # 2 - timestamp
    # 3 - referrer
    $att = json_encode(array($campaign, $keyword, time(), $_SERVER['HTTP_REFERER']));
    $piwik->setAttributionInfo($att);
    if (defined("DEBUG") and DEBUG) {
        header("X-Debug-Referred: from " . $_SERVER['HTTP_REFERER']);
        header("X-Debug-AttInfo: {$att}");
    }
    # do track the page view
    if (empty($keyword)) {
        $keyword = 'none';
    }
    $piwik->doTrackPageView("Reprint Tracker for: {$campaign} (keyword: {$keyword})");
    if (defined("DEBUG") and DEBUG) {
        header('X-Last-Piwik-Call: ' . $piwik::$DEBUG_LAST_REQUESTED_URL);
    }
}