Tracks a page view
public doTrackPageView ( string $documentTitle ) : mixed | ||
$documentTitle | string | Page title as it will appear in the Actions > Page titles report |
return | mixed | Response string or true if using bulk requests. |
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); }
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; }
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); }
protected function trackMusicPlaying(PiwikTracker $vis) { $vis->setUrl('http://example.org/webradio'); $vis->setGenerationTime(333); self::checkResponse($vis->doTrackPageView('Welcome!')); $this->moveTimeForward($vis, 1); $this->setMusicEventCustomVar($vis); self::checkResponse($vis->doTrackEvent('Music', 'play', 'La fiancée de l\'eau')); $this->moveTimeForward($vis, 2); $this->setMusicEventCustomVar($vis); self::checkResponse($vis->doTrackEvent('Music', 'play25%', 'La fiancée de l\'eau')); $this->moveTimeForward($vis, 3); $this->setMusicEventCustomVar($vis); self::checkResponse($vis->doTrackEvent('Music', 'play50%', 'La fiancée de l\'eau')); $this->moveTimeForward($vis, 4); $this->setMusicEventCustomVar($vis); self::checkResponse($vis->doTrackEvent('Music', 'play75%', 'La fiancée de l\'eau')); $this->moveTimeForward($vis, 4.5); $this->setMusicEventCustomVar($vis); self::checkResponse($vis->doTrackEvent('Music', 'playEnd', 'La fiancée de l\'eau')); }
private function trackPageview(\PiwikTracker $tracker, $userId, $url) { $tracker->setUrl('http://www.example.org' . $url); $tracker->setUserId($userId); $tracker->doTrackPageView($url); }
<?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';
public function test_response_ShouldBeEmpty_IfImageIsDisabled() { $this->tracker->disableSendImageResponse(); $response = $this->tracker->doTrackPageView('Test'); $this->assertSame('', $response); }
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'); } } }
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); }
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;
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; }
<?php include '../../includes/config.php'; require_once '../../includes/PiwikTracker.php'; PiwikTracker::$URL = get_page_url('stats', $CONF) . '/piwik.php'; $fileURL = $_GET['file']; $file_db = $db->select('uploads', "url=? LIMIT 1", array($fileURL)); $file_path = $CONF['upload_dir'] . $file_db['filename']; $temp_path = sys_get_temp_dir() . "\\" . $file_db['filename']; if (file_exists($file_path) && $file_db) { $t = new PiwikTracker($idSite = 1); $t->setUserAgent($_SERVER['HTTP_USER_AGENT']); $t->setUrlReferrer($_SERVER['HTTP_REFERER']); $t->setUrl($url = get_page_url('u', $CONF) . '/' . $fileURL); $t->doTrackPageView('Teknik Upload - ' . $fileURL); if ($file_db['hash'] != "") { $crypt = new Cryptography(); $result = $crypt->Decrypt($CONF['key'], $file_db['hash'], $file_path, $temp_path, $file_db['cipher']); if ($result) { $file_path = $temp_path; } } $file_type = $file_db['type']; $pattern = "/^((image)|(text)|(audio)|(video))\\/(.*)\$/"; if (!preg_match($pattern, $file_type)) { header("Content-Disposition: attachment; filename=\"" . $file_db['filename'] . "\""); header("Pragma: public"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header('Content-Type: ' . $file_type); header('Content-Length: ' . $file_db['filesize']); set_time_limit(0);
private function trackPageview(\PiwikTracker $tracker, $userId, $url = null) { if (null !== $url) { $tracker->setUrl('http://www.example.org' . $url); } $tracker->setUserId($userId); $title = $url ?: 'test'; $tracker->doTrackPageView($title); }
public function setupAction() { $form = new ViMbAdmin_Form_Admin_Edit(); $form->removeElement('active'); $form->removeElement('super'); $form->removeElement('welcome_email'); if ($this->getAuth()->getIdentity()) { $this->addMessage(_('You are already logged in.'), ViMbAdmin_Message::INFO); $this->_redirect('domain/list'); } if ($this->_options['securitysalt'] == '') { $charSet = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; $randomSalt = substr(str_shuffle("{$charSet}{$charSet}"), 0, 31); // please note this is not UTF-8 compatible $this->view->saltSet = false; $this->view->randomSalt = $randomSalt; $form->getElement('salt')->setValue($randomSalt); } elseif (!AdminTable::isEmpty()) { $this->addMessage(_("Admins already exist in the system."), ViMbAdmin_Message::INFO); $this->_redirect('auth/login'); } 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."), ViMbAdmin_Message::INFO); } else { $admin = new Admin(); $admin['username'] = $form->getValue('username'); $admin->setPassword($form->getValue('password'), $this->_options['securitysalt'], false); $admin->super = true; $admin->active = true; $admin->save(); try { $mailer = new Zend_Mail(); $mailer->setSubject(_('ViMbAdmin :: Your New Administrator Account')); $mailer->addTo($admin['username']); $mailer->setFrom($this->_options['server']['email']['address'], $this->_options['server']['email']['name']); $this->view->username = $admin['username']; $this->view->password = $form->getValue('password'); $mailer->setBodyText($this->view->render('admin/email/new_admin.phtml')); $mailer->send(); } catch (Exception $e) { } $this->addMessage(_('Your administrator account has been added. Please log in below.'), ViMbAdmin_Message::SUCCESS); } // Try and track new installs to see if it is worthwhile continueing development include_once APPLICATION_PATH . '/../public/PiwikTracker.php'; if (class_exists('PiwikTracker')) { if ($_SERVER['HTTPS'] == 'on') { PiwikTracker::$URL = 'https://stats.opensolutions.ie/'; } else { PiwikTracker::$URL = 'http://stats.opensolutions.ie/'; } $piwikTracker = new PiwikTracker($idSite = 5); $piwikTracker->doTrackPageView('Nes Install Completed'); $piwikTracker->doTrackGoal($idGoal = 1, $revenue = 0); } $this->_helper->viewRenderer->setNoRender(true); $this->_redirect('auth/login'); } } $this->view->form = $form; }
{ mylog("Uncaught exception: " . $exception->getMessage()); } set_exception_handler('exception_handler'); require_once "Mail.php"; require_once "config.php"; //define("PIWIK_ENABLE_TRACKING"); //$_GET["idsite"] = "3"; //require_once "../piwik/piwik.php"; //echo($_GET["idsite"]); // -- Piwik Tracking API init -- require_once "../PiwikTracker.php"; PiwikTracker::$URL = 'http://toplessproductions.com/static/piwik/'; $t = new PiwikTracker($idSite = 3); $t->setCustomVariable(1, 'Force IP', $_SERVER['REMOTE_ADDR']); $t->doTrackPageView('email by web'); $from = "<*****@*****.**>"; $to = $_POST["to"]; $subject = $_POST["subject"]; $body = $_POST["message"]; $secret = $_POST["secret"]; $replyto = $_POST["replyto"]; if ($secret != $SECRET) { log("Wrong secret"); die("..."); } $host = "ssl://smtp.gmail.com"; $port = "465"; $username = "******"; $password = $PW; $headers = array('From' => $from, 'To' => $to, 'Subject' => $subject, 'Reply-To' => $replyto);
/** * Sends the keyword and destination URL to Piwik * * @param bool $return The value to return. Defaults to false with doesn't enable the filter * @param string $keyword The requested keyword * @return bool */ function itfs_piwik_log_request($return, $keyword) { // Get current configuration from database $piwik_config = yourls_get_option('piwik_config'); // Let's check if the user wants to log bots if ($piwik_config[remove_bots]) { if (itfs_piwik_is_bot()) { return $return; } } try { // Need to use a file_exists check as require only produces a fatal compilation error if (!file_exists(dirname(__FILE__) . '/libs/Piwik/PiwikTracker.php')) { throw new Exception("Error can't load PiwikTracker.php"); } else { // Piwik Tracking API init require_once dirname(__FILE__) . '/libs/Piwik/PiwikTracker.php'; PiwikTracker::$URL = $piwik_config[piwik_url]; } } catch (Exception $e) { error_log("ITFS_PIWIK: " . $e->getMessage(), 0); return $return; } // Use this to get the destination $destination = yourls_get_keyword_longurl($keyword); // Only log a request if we have a destination and the proper Piwik settings if ($destination == false) { error_log("ITFS_PIWIK: Missing parameters prevented me from logging the request with Piwik", 0); error_log("ITFS_PIWIK: Parameters we have: " . $keyword . ', ' . $destination, 0); return $return; } //Useful for hosts using one Piwik installation with multiple YOURLS installation $domain_landed = $_SERVER['HTTP_HOST']; $page_url = "http://" . $domain_landed . "/" . $keyword; try { $pt = new PiwikTracker($piwik_config[site_id]); // This will be the entry page in Piwik $pt->setUrl($page_url); // This will fail silently if the token is not valid or if the user doesn't have admin rights if (!empty($piwik_config[token])) { $pt->setTokenAuth($piwik_config[token]); } // This shows up in the visitor logs and identify the source of the data $pt->setCustomVariable(1, 'App', 'Piwik plugin for YOURLS', 'visit'); // Some useful variables $pt->setCustomVariable(2, 'Domain landed', $domain_landed, 'page'); $pt->setCustomVariable(3, 'Keyword', $keyword, 'page'); // User defined custom variable if (!empty($piwik_config[customvar_name]) && !empty($piwik_config[customvar_value])) { $pt->setCustomVariable(4, $piwik_config[customvar_name], $piwik_config[customvar_value], $piwik_config[customvar_scope]); } // Track the visit in Piwik $title = yourls_get_keyword_title($keyword); @$pt->doTrackPageView($title); // The destination URL will show up as an outlink @$pt->doTrackAction($destination, 'link'); } catch (Exception $e) { error_log("ITFS_PIWIK: Error when trying to log the request with Piwik. " . $e->getMessage(), 0); return $return; } if ($piwik_config[disable_stats]) { //error_log("ITFS_PIWIK: NOT logging locally", 0); return; } else { //error_log("ITFS_PIWIK: Logging locally", 0); return $return; } }
function piwik_analytics($aid, $purl, $name, $go, $html = 1) { require_once dirname(__FILE__) . '/lib/PiwikTracker.php'; global $blog_settings; if (empty($go)) { $go = $_SERVER['PHP_SELF']; } PiwikTracker::$URL = $blog_settings->get('piwik_url'); $screen_resolution = "1280x800"; if (!isset($_SESSION[iterate]) && $html) { if (!isset($_COOKIE["piwik_user_resolution"])) { //means cookie is not found set it using Javascript $_SESSION[iterate] = 1; ?> <script language="javascript"><!-- writeCookie(); function writeCookie() { var the_cookie = "piwik_user_resolution="+ screen.width +"x"+ screen.height; document.cookie=the_cookie location ='<?php echo $go; ?> '; } //--></script> <?php } else { $screen_resolution = $_COOKIE["piwik_user_resolution"]; } } else { $screen_resolution = $_COOKIE["users_resolution"]; } $screen_resolution = preg_split('x', $screen_resolution); $t = new PiwikTracker($idSite = $aid, $blog_settings->get('piwik_url')); // Optional tracking $t->setUserAgent($_SERVER['HTTP_USER_AGENT']); $t->setBrowserLanguage(substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2)); $t->setLocalTime(date("H:i:s")); $t->setResolution($screen_resolution[0], $screen_resolution[1]); // Mandatory $t->setUrl($url = $purl); $t->doTrackPageView($name); }
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); } }