diff options
-rw-r--r-- | core/Tracker.php | 89 | ||||
-rw-r--r-- | core/Tracker/Action.php | 95 | ||||
-rw-r--r-- | core/Tracker/GoalManager.php | 54 | ||||
-rw-r--r-- | core/Tracker/Request.php | 457 | ||||
-rw-r--r-- | core/Tracker/Visit.php | 502 | ||||
-rw-r--r-- | core/Tracker/VisitExcluded.php | 9 | ||||
-rw-r--r-- | piwik.php | 5 | ||||
-rw-r--r-- | plugins/DoNotTrack/DoNotTrack.php | 3 | ||||
-rw-r--r-- | plugins/UserSettings/functions.php | 2 | ||||
-rw-r--r-- | tests/PHPUnit/Core/Tracker/ActionTest.php | 7 |
10 files changed, 664 insertions, 559 deletions
diff --git a/core/Tracker.php b/core/Tracker.php index 148db37a44..42f1493d7b 100644 --- a/core/Tracker.php +++ b/core/Tracker.php @@ -40,7 +40,6 @@ class Piwik_Tracker const MAX_CUSTOM_VARIABLES = 5; const MAX_LENGTH_CUSTOM_VARIABLE = 200; - protected $authenticated = false; static protected $forcedDateTime = null; static protected $forcedIpString = null; static protected $forcedVisitorId = null; @@ -82,7 +81,6 @@ class Piwik_Tracker self::$forcedDateTime = null; self::$forcedVisitorId = null; $this->stateValid = self::STATE_NOTHING_TO_NOTICE; - $this->authenticated = false; } public static function setForceIp($ipString) @@ -173,8 +171,8 @@ class Piwik_Tracker if (isset($jsonData['requests'])) { $this->requests = $jsonData['requests']; } - $this->tokenAuth = Piwik_Common::getRequestVar('token_auth', false, null, $jsonData); - if (empty($this->tokenAuth)) { + $tokenAuth = Piwik_Common::getRequestVar('token_auth', false, null, $jsonData); + if (empty($tokenAuth)) { throw new Exception(" token_auth must be specified when using Bulk Tracking Import. See <a href='http://piwik.org/docs/tracking-api/reference/'>Tracking Doc</a>"); } if (!empty($this->requests)) { @@ -197,10 +195,11 @@ class Piwik_Tracker } // a Bulk Tracking request that is not authenticated should fail - if (!$this->authenticateSuperUserOrAdmin(array('idsite' => $idSiteForAuthentication))) { + if (!Piwik_Tracker_Request::authenticateSuperUserOrAdmin($tokenAuth, $idSiteForAuthentication)) { throw new Exception(" token_auth specified is not valid for site " . intval($idSiteForAuthentication)); } } + return $tokenAuth; } /** @@ -211,22 +210,22 @@ class Piwik_Tracker public function main($args = null) { $displayedGIF = false; - $this->initRequests($args); + $tokenAuth = $this->initRequests($args); + + $isAuthenticated = false; if (!empty($this->requests)) { - // handle all visits - foreach ($this->requests as $request) { + foreach ($this->requests as $params) { + $request = new Piwik_Tracker_Request($params, $tokenAuth); $this->init($request); - if (!$displayedGIF && !$this->authenticated) { - $this->outputTransparentGif(); - $displayedGIF = true; - } - try { if ($this->isVisitValid()) { self::connectDatabaseIfNotConnected(); $visit = $this->getNewVisitObject(); + + $request->setForcedVisitorId(self::$forcedVisitorId); + $visit->setRequest($request); $visit->handle(); unset($visit); @@ -235,10 +234,10 @@ class Piwik_Tracker } } catch (Piwik_Tracker_Db_Exception $e) { printDebug("<b>" . $e->getMessage() . "</b>"); - $this->exitWithException($e, $this->authenticated); + $this->exitWithException($e, $isAuthenticated); } catch (Piwik_Tracker_Visit_Excluded $e) { } catch (Exception $e) { - $this->exitWithException($e, $this->authenticated); + $this->exitWithException($e, $isAuthenticated); } $this->clear(); @@ -247,22 +246,22 @@ class Piwik_Tracker ++$this->countOfLoggedRequests; } - if (!$displayedGIF) { - $this->outputTransparentGif(); - $displayedGIF = true; + $this->outputTransparentGif(); + + // run scheduled task + try { + if (!$isAuthenticated // Do not run schedule task if we are importing logs or doing custom tracking (as it could slow down) + && $this->shouldRunScheduledTasks()) { + self::runScheduledTasks($now = $this->getCurrentTimestamp()); + } + } catch (Exception $e) { + $this->exitWithException($e); } + } else { $this->handleEmptyRequest($_GET + $_POST); } - // run scheduled task - try { - if ($this->shouldRunScheduledTasks()) { - self::runScheduledTasks($now = $this->getCurrentTimestamp()); - } - } catch (Exception $e) { - $this->exitWithException($e, $this->authenticated); - } $this->end(); } @@ -272,7 +271,6 @@ class Piwik_Tracker // don't run scheduled tasks in CLI mode from Tracker, this is the case // where we bulk load logs & don't want to lose time with tasks return !Piwik_Common::isPhpCliMode() - && !$this->authenticated && $this->getState() != self::STATE_LOGGING_DISABLE; } @@ -380,7 +378,7 @@ class Piwik_Tracker * @param Exception $e * @param bool $authenticated */ - protected function exitWithException($e, $authenticated) + protected function exitWithException($e, $authenticated = false) { if ($this->usingBulkTracking) { // when doing bulk tracking we return JSON so the caller will know how many succeeded @@ -414,7 +412,7 @@ class Piwik_Tracker /** * Initialization */ - protected function init($request) + protected function init(Piwik_Tracker_Request $request) { $this->handleTrackingApi($request); $this->loadTrackerPlugins($request); @@ -544,8 +542,7 @@ class Piwik_Tracker Piwik_PostEvent('Tracker.getNewVisitObject', $visit); if (is_null($visit)) { - $visit = new Piwik_Tracker_Visit(self::$forcedIpString, self::$forcedDateTime, $this->authenticated); - $visit->setForcedVisitorId(self::$forcedVisitorId); + $visit = new Piwik_Tracker_Visit(self::$forcedIpString); } elseif (!($visit instanceof Piwik_Tracker_Visit_Interface)) { throw new Exception("The Visit object set in the plugin must implement Piwik_Tracker_Visit_Interface"); } @@ -591,12 +588,12 @@ class Piwik_Tracker $this->stateValid = $value; } - protected function loadTrackerPlugins($request) + protected function loadTrackerPlugins(Piwik_Tracker_Request $request) { // Adding &dp=1 will disable the provider plugin, if token_auth is used (used to speed up bulk imports) - if (isset($request['dp']) - && !empty($request['dp']) - && $this->authenticated + $disableProvider = $request->getParam('dp'); + if (!empty($disableProvider) + && $request->isAuthenticated() ) { Piwik_Tracker::setPluginsNotToLoad(array('Provider')); } @@ -617,9 +614,9 @@ class Piwik_Tracker } } - protected function handleEmptyRequest($request) + protected function handleEmptyRequest(Piwik_Tracker_Request $request) { - $countParameters = count($request); + $countParameters = $request->getParamsCount(); if ($countParameters == 0) { $this->setState(self::STATE_EMPTY_REQUEST); } @@ -680,32 +677,26 @@ class Piwik_Tracker * This method allows to set custom IP + server time + visitor ID, when using Tracking API. * These two attributes can be only set by the Super User (passing token_auth). */ - protected function handleTrackingApi($request) + protected function handleTrackingApi(Piwik_Tracker_Request $request) { - $shouldAuthenticate = Piwik_Config::getInstance()->Tracker['tracking_requests_require_authentication']; - if ($shouldAuthenticate) { - if (!$this->authenticateSuperUserOrAdmin($request)) { - return; - } - printDebug("token_auth is authenticated!"); - } else { - printDebug("token_auth authentication not required"); + if(!$request->isAuthenticated()) { + return; } // Custom IP to use for this visitor - $customIp = Piwik_Common::getRequestVar('cip', false, 'string', $request); + $customIp = $request->getParam('cip'); if (!empty($customIp)) { $this->setForceIp($customIp); } // Custom server date time to use - $customDatetime = Piwik_Common::getRequestVar('cdt', false, 'string', $request); + $customDatetime = $request->getParam('cdt'); if (!empty($customDatetime)) { $this->setForceDateTime($customDatetime); } // Forced Visitor ID to record the visit / action - $customVisitorId = Piwik_Common::getRequestVar('cid', false, 'string', $request); + $customVisitorId = $request->getParam('cid'); if (!empty($customVisitorId)) { $this->setForceVisitorId($customVisitorId); } diff --git a/core/Tracker/Action.php b/core/Tracker/Action.php index eb4f300b92..3ea0cfb5bb 100644 --- a/core/Tracker/Action.php +++ b/core/Tracker/Action.php @@ -27,11 +27,7 @@ interface Piwik_Tracker_Action_Interface const TYPE_ECOMMERCE_ITEM_CATEGORY = 7; const TYPE_SITE_SEARCH = 8; - public function setRequest($requestArray); - - public function setIdSite($idSite); - - public function init(); + public function __construct(Piwik_Tracker_Request $request); public function getActionUrl(); @@ -57,9 +53,11 @@ interface Piwik_Tracker_Action_Interface */ class Piwik_Tracker_Action implements Piwik_Tracker_Action_Interface { + /** + * @var Piwik_Tracker_Request + */ private $request; - private $idSite; - private $timestamp; + private $idLinkVisitAction; private $idActionName = false; private $idActionUrl = false; @@ -80,7 +78,8 @@ class Piwik_Tracker_Action implements Piwik_Tracker_Action_Interface */ private $pageEncoding = false; - static private $queryParametersToExclude = array('phpsessid', 'jsessionid', 'sessionid', 'aspsessionid', 'fb_xd_fragment', 'fb_comment_id', 'doing_wp_cron', 'gclid'); + static private $queryParametersToExclude = array('gclid', 'phpsessid', 'jsessionid', 'sessionid', 'aspsessionid', 'fb_xd_fragment', 'fb_comment_id', + 'doing_wp_cron'); /* Custom Variable names & slots used for Site Search metadata (category, results count) */ const CVAR_KEY_SEARCH_CATEGORY = '_pk_scat'; @@ -88,14 +87,8 @@ class Piwik_Tracker_Action implements Piwik_Tracker_Action_Interface const CVAR_INDEX_SEARCH_CATEGORY = '4'; const CVAR_INDEX_SEARCH_COUNT = '5'; - /* Tracking API Parameters used to force a site search request */ - const PARAMETER_NAME_SEARCH_COUNT = 'search_count'; - const PARAMETER_NAME_SEARCH_CATEGORY = 'search_cat'; - const PARAMETER_NAME_SEARCH_KEYWORD = 'search'; - /* Custom Variables names & slots plus Tracking API Parameters for performance analytics */ const DB_COLUMN_TIME_GENERATION = 'custom_float'; - const PARAMETER_NAME_TIME_GENERATION = 'gt_ms'; /** * Map URL prefixes to integers. @@ -156,24 +149,10 @@ class Piwik_Tracker_Action implements Piwik_Tracker_Action_Interface } - /** - * Set request parameters - * - * @param array $requestArray - */ - public function setRequest($requestArray) + public function __construct(Piwik_Tracker_Request $request) { - $this->request = $requestArray; - } - - /** - * Returns the current set request parameters - * - * @return array - */ - public function getRequest() - { - return $this->request; + $this->request = $request; + $this->init(); } /** @@ -455,14 +434,14 @@ class Piwik_Tracker_Action implements Piwik_Tracker_Action_Interface return $validQuery; } - public function init() + protected function init() { - $this->pageEncoding = Piwik_Common::getRequestVar('cs', false, null, $this->request); + $this->pageEncoding = $this->request->getParam('cs'); $info = $this->extractUrlAndActionNameFromRequest(); $originalUrl = $info['url']; - $info['url'] = self::excludeQueryParametersFromUrl($originalUrl, $this->idSite); + $info['url'] = self::excludeQueryParametersFromUrl($originalUrl, $this->request->getIdSite()); if ($originalUrl != $info['url']) { printDebug(' Before was "' . $originalUrl . '"'); @@ -660,20 +639,6 @@ class Piwik_Tracker_Action implements Piwik_Tracker_Action_Interface } /** - * @param int $idSite - */ - function setIdSite($idSite) - { - $this->idSite = $idSite; - } - - function setTimestamp($timestamp) - { - $this->timestamp = $timestamp; - } - - - /** * Records in the DB the association between the visit and this action. * * @param int $idVisit is the ID of the current visit in the DB table log_visit @@ -696,9 +661,9 @@ class Piwik_Tracker_Action implements Piwik_Tracker_Action_Interface $insert = array( 'idvisit' => $idVisit, - 'idsite' => $this->idSite, + 'idsite' => $this->request->getIdSite(), 'idvisitor' => $visitorIdCookie, - 'server_time' => Piwik_Tracker::getDatetimeFromTimestamp($this->timestamp), + 'server_time' => Piwik_Tracker::getDatetimeFromTimestamp($this->request->getCurrentTimestamp()), 'idaction_url' => $this->getIdActionUrl(), 'idaction_name' => $idActionName, 'idaction_url_ref' => $idRefererActionUrl, @@ -732,7 +697,7 @@ class Piwik_Tracker_Action implements Piwik_Tracker_Action_Interface $this->idLinkVisitAction = Piwik_Tracker::getDatabase()->lastInsertId(); $info = array( - 'idSite' => $this->idSite, + 'idSite' => $this->request->getIdSite(), 'idLinkVisitAction' => $this->idLinkVisitAction, 'idVisit' => $idVisit, 'idRefererActionUrl' => $idRefererActionUrl, @@ -749,7 +714,7 @@ class Piwik_Tracker_Action implements Piwik_Tracker_Action_Interface public function getCustomVariables() { - $customVariables = Piwik_Tracker_Visit::getCustomVariables($scope = 'page', $this->request); + $customVariables = $this->request->getCustomVariables($scope = 'page'); // Enrich Site Search actions with Custom Variables, overwriting existing values if (!empty($this->searchCategory)) { @@ -757,7 +722,7 @@ class Piwik_Tracker_Action implements Piwik_Tracker_Action_Interface printDebug("WARNING: Overwriting existing Custom Variable in slot " . self::CVAR_INDEX_SEARCH_CATEGORY . " for this page view"); } $customVariables['custom_var_k' . self::CVAR_INDEX_SEARCH_CATEGORY] = self::CVAR_KEY_SEARCH_CATEGORY; - $customVariables['custom_var_v' . self::CVAR_INDEX_SEARCH_CATEGORY] = Piwik_Tracker_Visit::truncateCustomVariable($this->searchCategory); + $customVariables['custom_var_v' . self::CVAR_INDEX_SEARCH_CATEGORY] = Piwik_Tracker_Request::truncateCustomVariable($this->searchCategory); } if ($this->searchCount !== false) { if (!empty($customVariables['custom_var_k' . self::CVAR_INDEX_SEARCH_COUNT])) { @@ -795,7 +760,7 @@ class Piwik_Tracker_Action implements Piwik_Tracker_Action_Interface $actionName = null; // download? - $downloadUrl = Piwik_Common::getRequestVar('download', '', 'string', $this->request); + $downloadUrl = $this->request->getParam('download'); if (!empty($downloadUrl)) { $actionType = self::TYPE_DOWNLOAD; $url = $downloadUrl; @@ -803,7 +768,7 @@ class Piwik_Tracker_Action implements Piwik_Tracker_Action_Interface // outlink? if (empty($actionType)) { - $outlinkUrl = Piwik_Common::getRequestVar('link', '', 'string', $this->request); + $outlinkUrl = $this->request->getParam('link'); if (!empty($outlinkUrl)) { $actionType = self::TYPE_OUTLINK; $url = $outlinkUrl; @@ -811,12 +776,12 @@ class Piwik_Tracker_Action implements Piwik_Tracker_Action_Interface } // handle encoding - $actionName = Piwik_Common::getRequestVar('action_name', '', 'string', $this->request); + $actionName = $this->request->getParam('action_name'); // defaults to page view if (empty($actionType)) { $actionType = self::TYPE_ACTION_URL; - $url = Piwik_Common::getRequestVar('url', '', 'string', $this->request); + $url = $this->request->getParam('url'); // get the delimiter, by default '/'; BC, we read the old action_category_delimiter first (see #1067) $actionCategoryDelimiter = isset(Piwik_Config::getInstance()->General['action_category_delimiter']) @@ -864,7 +829,7 @@ class Piwik_Tracker_Action implements Piwik_Tracker_Action_Interface protected function detectSiteSearch($originalUrl) { - $website = Piwik_Tracker_Cache::getCacheWebsiteAttributes($this->idSite); + $website = Piwik_Tracker_Cache::getCacheWebsiteAttributes($this->request->getIdSite()); if (empty($website['sitesearch'])) { printDebug("Internal 'Site Search' tracking is not enabled for this site. "); return false; @@ -876,17 +841,17 @@ class Piwik_Tracker_Action implements Piwik_Tracker_Action_Interface // Detect Site search from Tracking API parameters rather than URL - $searchKwd = Piwik_Common::getRequestVar(self::PARAMETER_NAME_SEARCH_KEYWORD, '', 'string', $this->request); + $searchKwd = $this->request->getParam('search'); if (!empty($searchKwd)) { $actionName = $searchKwd; if ($doTrackUrlForSiteSearch) { $url = $originalUrl; } - $isCategoryName = Piwik_Common::getRequestVar(self::PARAMETER_NAME_SEARCH_CATEGORY, false, 'string', $this->request); + $isCategoryName = $this->request->getParam('search_cat'); if (!empty($isCategoryName)) { $categoryName = $isCategoryName; } - $isCount = Piwik_Common::getRequestVar(self::PARAMETER_NAME_SEARCH_COUNT, -1, 'int', $this->request); + $isCount = $this->request->getParam('search_count'); if ($this->isValidSearchCount($isCount)) { $count = $isCount; } @@ -991,10 +956,10 @@ class Piwik_Tracker_Action implements Piwik_Tracker_Action_Interface } } - if (isset($parameters[self::PARAMETER_NAME_SEARCH_COUNT]) - && $this->isValidSearchCount($parameters[self::PARAMETER_NAME_SEARCH_COUNT]) + if (isset($parameters['search_count']) + && $this->isValidSearchCount($parameters['search_count']) ) { - $count = $parameters[self::PARAMETER_NAME_SEARCH_COUNT]; + $count = $parameters['search_count']; } // Remove search kwd from URL if ($doRemoveSearchParametersFromUrl) { @@ -1022,7 +987,7 @@ class Piwik_Tracker_Action implements Piwik_Tracker_Action_Interface const GENERATION_TIME_MS_MAXIMUM = 3600000; // 1 hour protected function detectPerformanceAnalyticsParameters() { - $generationTime = Piwik_Common::getRequestVar(self::PARAMETER_NAME_TIME_GENERATION, -1, 'int', $this->request); + $generationTime = $this->request->getParam('gt_ms'); if ($generationTime > 0 && $generationTime < self::GENERATION_TIME_MS_MAXIMUM) { $this->timeGeneration = (int)$generationTime; diff --git a/core/Tracker/GoalManager.php b/core/Tracker/GoalManager.php index 6587baace2..87c0ff4bbd 100644 --- a/core/Tracker/GoalManager.php +++ b/core/Tracker/GoalManager.php @@ -41,15 +41,23 @@ class Piwik_Tracker_GoalManager protected $action = null; protected $convertedGoals = array(); protected $isThereExistingCartInVisit = false; + /** + * @var Piwik_Tracker_Request + */ protected $request; protected $orderId; - function init($request) + public function __construct(Piwik_Tracker_Request $request) { $this->request = $request; - $this->orderId = Piwik_Common::getRequestVar('ec_id', false, 'string', $this->request); + $this->init(); + } + + function init() + { + $this->orderId = $this->request->getParam('ec_id'); $this->isGoalAnOrder = !empty($this->orderId); - $this->idGoal = Piwik_Common::getRequestVar('idgoal', -1, 'int', $this->request); + $this->idGoal = $this->request->getParam('idgoal'); $this->requestIsEcommerce = ($this->idGoal == 0); } @@ -193,9 +201,9 @@ class Piwik_Tracker_GoalManager } $goal = $goals[$this->idGoal]; - $url = Piwik_Common::getRequestVar('url', '', 'string', $this->request); + $url = $this->request->getParam('url'); $goal['url'] = Piwik_Tracker_Action::excludeQueryParametersFromUrl($url, $idSite); - $goal['revenue'] = $this->getRevenue(Piwik_Common::getRequestVar('revenue', $goal['revenue'], 'float', $this->request)); + $goal['revenue'] = $this->getRevenue( $this->request->getGoalRevenue($goal['revenue'])); $this->convertedGoals[] = $goal; return true; } @@ -213,8 +221,14 @@ class Piwik_Tracker_GoalManager * @param string $referrerCampaignKeyword * @param string $browserLanguage */ - public function recordGoals($idSite, $visitorInformation, $visitCustomVariables, $action, $referrerTimestamp, $referrerUrl, $referrerCampaignName, $referrerCampaignKeyword, $browserLanguage) + public function recordGoals($idSite, $visitorInformation, $visitCustomVariables, $action) { + $refererTimestamp = $this->request->getParam('_refts'); + $refererUrl = $this->request->getParam('_ref'); + $refererCampaignName = $this->request->getParam('_rcn'); + $refererCampaignKeyword = $this->request->getParam('_rck'); + $browserLanguage = $this->request->getBrowserLanguage(); + $location_country = isset($visitorInformation['location_country']) ? $visitorInformation['location_country'] : Piwik_Common::getCountry( @@ -273,28 +287,28 @@ class Piwik_Tracker_GoalManager // 0) In some (unknown!?) cases the campaign is not found in the attribution cookie, but the URL ref was found. // In this case we look up if the current visit is credited to a campaign and will credit this campaign rather than the URL ref (since campaigns have higher priority) - if (empty($referrerCampaignName) + if (empty($refererCampaignName) && $type == Piwik_Common::REFERER_TYPE_CAMPAIGN && !empty($name) ) { // Use default values per above } // 1) Campaigns from 1st party cookie - elseif (!empty($referrerCampaignName)) { + elseif (!empty($refererCampaignName)) { $type = Piwik_Common::REFERER_TYPE_CAMPAIGN; - $name = $referrerCampaignName; - $keyword = $referrerCampaignKeyword; - $time = $referrerTimestamp; + $name = $refererCampaignName; + $keyword = $refererCampaignKeyword; + $time = $refererTimestamp; } // 2) Referrer URL parsing - elseif (!empty($referrerUrl)) { + elseif (!empty($refererUrl)) { $referrer = new Piwik_Tracker_Referer(); - $referrer = $referrer->getRefererInformation($referrerUrl, $currentUrl = '', $idSite); + $referrer = $referrer->getRefererInformation($refererUrl, $currentUrl = '', $idSite); // if the parsed referer is interesting enough, ie. website or search engine if (in_array($referrer['referer_type'], array(Piwik_Common::REFERER_TYPE_SEARCH_ENGINE, Piwik_Common::REFERER_TYPE_WEBSITE))) { $type = $referrer['referer_type']; $name = $referrer['referer_name']; $keyword = $referrer['referer_keyword']; - $time = $referrerTimestamp; + $time = $refererTimestamp; } } $goal += array( @@ -351,10 +365,10 @@ class Piwik_Tracker_GoalManager $goal['idgoal'] = self::IDGOAL_ORDER; $goal['idorder'] = $this->orderId; $goal['buster'] = $orderIdNumeric; - $goal['revenue_subtotal'] = $this->getRevenue(Piwik_Common::getRequestVar('ec_st', false, 'float', $this->request)); - $goal['revenue_tax'] = $this->getRevenue(Piwik_Common::getRequestVar('ec_tx', false, 'float', $this->request)); - $goal['revenue_shipping'] = $this->getRevenue(Piwik_Common::getRequestVar('ec_sh', false, 'float', $this->request)); - $goal['revenue_discount'] = $this->getRevenue(Piwik_Common::getRequestVar('ec_dt', false, 'float', $this->request)); + $goal['revenue_subtotal'] = $this->getRevenue( $this->request->getParam('ec_st')); + $goal['revenue_tax'] = $this->getRevenue($this->request->getParam('ec_tx')); + $goal['revenue_shipping'] = $this->getRevenue($this->request->getParam('ec_sh')); + $goal['revenue_discount'] = $this->getRevenue($this->request->getParam('ec_dt')); $debugMessage = 'The conversion is an Ecommerce order'; } // If Cart update, select current items in the previous Cart @@ -363,7 +377,7 @@ class Piwik_Tracker_GoalManager $goal['idgoal'] = self::IDGOAL_CART; $debugMessage = 'The conversion is an Ecommerce Cart Update'; } - $goal['revenue'] = $this->getRevenue(Piwik_Common::getRequestVar('revenue', 0, 'float', $this->request)); + $goal['revenue'] = $this->getRevenue($this->request->getGoalRevenue( $defaultRevenue = 0)); printDebug($debugMessage . ':' . var_export($goal, true)); @@ -396,7 +410,7 @@ class Piwik_Tracker_GoalManager */ protected function getEcommerceItemsFromRequest() { - $items = Piwik_Common::unsanitizeInputValue(Piwik_Common::getRequestVar('ec_items', '', 'string', $this->request)); + $items = Piwik_Common::unsanitizeInputValue($this->request->getParam('ec_items')); if (empty($items)) { printDebug("There are no Ecommerce items in the request"); // we still record an Ecommerce order without any item in it diff --git a/core/Tracker/Request.php b/core/Tracker/Request.php new file mode 100644 index 0000000000..a2f4d8b95d --- /dev/null +++ b/core/Tracker/Request.php @@ -0,0 +1,457 @@ +<?php +/** + * Piwik - Open source web analytics + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + * + * @category Piwik + * @package Piwik + */ + +class Piwik_Tracker_Request +{ + /** + * @var array + */ + protected $params; + + public function __construct(array $params, $tokenAuth = false) + { + $this->params = $params; + $this->timestamp = time(); + + // When the 'url' and referer url parameter are not given, we might be in the 'Simple Image Tracker' mode. + // The URL can default to the Referer, which will be in this case + // the URL of the page containing the Simple Image beacon + if (empty($this->params['urlref']) + && empty($this->params['url']) + ) { + $this->params['url'] = @$_SERVER['HTTP_REFERER']; + } + $this->authenticateTrackingApi($tokenAuth); + } + + protected $isAuthenticated = false; + + const UNKNOWN_RESOLUTION = 'unknown'; + + public function isAuthenticated() + { + return $this->isAuthenticated; + } + + /** + * This method allows to set custom IP + server time + visitor ID, when using Tracking API. + * These two attributes can be only set by the Super User (passing token_auth). + */ + protected function authenticateTrackingApi($tokenAuthFromBulkRequest) + { + $shouldAuthenticate = Piwik_Config::getInstance()->Tracker['tracking_requests_require_authentication']; + if ($shouldAuthenticate) { + $tokenAuth = $tokenAuthFromBulkRequest || Piwik_Common::getRequestVar('token_auth', false, 'string', $this->params); + $this->isAuthenticated = $this->authenticateSuperUserOrAdmin($tokenAuth, $this->getIdSite()); + if (!$this->isAuthenticated) { + return; + } + printDebug("token_auth is authenticated!"); + } else { + $this->isAuthenticated = true; + printDebug("token_auth authentication not required"); + } + } + + public static function authenticateSuperUserOrAdmin($tokenAuth, $idSite) + { + if (!$tokenAuth) { + return false; + } + $superUserLogin = Piwik_Config::getInstance()->superuser['login']; + $superUserPassword = Piwik_Config::getInstance()->superuser['password']; + if (md5($superUserLogin . $superUserPassword) == $tokenAuth) { + return true; + } + + // Now checking the list of admin token_auth cached in the Tracker config file + if (!empty($idSite) + && $idSite > 0 + ) { + $website = Piwik_Tracker_Cache::getCacheWebsiteAttributes($idSite); + $adminTokenAuth = $website['admin_token_auth']; + if (in_array($tokenAuth, $adminTokenAuth)) { + return true; + } + } + printDebug("WARNING! token_auth = $tokenAuth is not valid, Super User / Admin was NOT authenticated"); + + return false; + } + + public function getDaysSinceFirstVisit() + { + $cookieFirstVisitTimestamp = $this->getParam('_idts'); + if (!$this->isTimestampValid($cookieFirstVisitTimestamp)) { + $cookieFirstVisitTimestamp = $this->getCurrentTimestamp(); + } + $daysSinceFirstVisit = round(($this->getCurrentTimestamp() - $cookieFirstVisitTimestamp) / 86400, $precision = 0); + if ($daysSinceFirstVisit < 0) { + $daysSinceFirstVisit = 0; + } + return $daysSinceFirstVisit; + } + + public function getDaysSinceLastOrder() + { + $daysSinceLastOrder = false; + $lastOrderTimestamp = $this->getParam('_ects'); + if ($this->isTimestampValid($lastOrderTimestamp)) { + $daysSinceLastOrder = round(($this->getCurrentTimestamp() - $lastOrderTimestamp) / 86400, $precision = 0); + if ($daysSinceLastOrder < 0) { + $daysSinceLastOrder = 0; + } + } + return $daysSinceLastOrder; + } + + public function getDaysSinceLastVisit() + { + $daysSinceLastVisit = 0; + $lastVisitTimestamp = $this->getParam('_viewts'); + if ($this->isTimestampValid($lastVisitTimestamp)) { + $daysSinceLastVisit = round(($this->getCurrentTimestamp() - $lastVisitTimestamp) / 86400, $precision = 0); + if ($daysSinceLastVisit < 0) { + $daysSinceLastVisit = 0; + } + } + return $daysSinceLastVisit; + } + + public function getVisitCount() + { + $visitCount = $this->getParam('_idvc'); + if ($visitCount < 1) { + $visitCount = 1; + } + return $visitCount; + } + + /** + * Returns the language the visitor is viewing. + * + * @return string browser language code, eg. "en-gb,en;q=0.5" + */ + public function getBrowserLanguage() + { + return Piwik_Common::getRequestVar('lang', Piwik_Common::getBrowserLanguage(), 'string', $this->params); + } + + public function getLocalTime() + { + $localTimes = array( + 'h' => (string)Piwik_Common::getRequestVar('h', $this->getCurrentDate("H"), 'int', $this->params), + 'i' => (string)Piwik_Common::getRequestVar('m', $this->getCurrentDate("i"), 'int', $this->params), + 's' => (string)Piwik_Common::getRequestVar('s', $this->getCurrentDate("s"), 'int', $this->params) + ); + foreach ($localTimes as $k => $time) { + if (strlen($time) == 1) { + $localTimes[$k] = '0' . $time; + } + } + $localTime = $localTimes['h'] . ':' . $localTimes['i'] . ':' . $localTimes['s']; + return $localTime; + } + + /** + * Returns the current date in the "Y-m-d" PHP format + * + * @param string $format + * @return string + */ + protected function getCurrentDate($format = "Y-m-d") + { + return date($format, $this->getCurrentTimestamp()); + } + + public function getGoalRevenue($defaultGoalRevenue) + { + return Piwik_Common::getRequestVar('revenue', $defaultGoalRevenue, 'float', $this->params); + } + + public function getParam($name) + { + $supportedParams = array( + // Name => array( defaultValue, type ) + '_refts' => array(0, 'int'), + '_ref' => array('', 'string'), + '_rcn' => array('', 'string'), + '_rck' => array('', 'string'), + '_idts' => array(0, 'int'), + '_viewts' => array(0, 'int'), + '_ects' => array(0, 'int'), + '_idvc' => array(1, 'int'), + 'url' => array('', 'string'), + 'urlref' => array('', 'string'), + 'res' => array(self::UNKNOWN_RESOLUTION, 'string'), + 'idgoal' => array(-1, 'int'), + + // other + 'dp' => array(0, 'int'), + 'rec' => array(false, 'int'), + 'new_visit' => array(0, 'int'), + + // Ecommerce + 'ec_id' => array(false, 'string'), + 'ec_st' => array(false, 'float'), + 'ec_tx' => array(false, 'float'), + 'ec_sh' => array(false, 'float'), + 'ec_dt' => array(false, 'float'), + 'ec_items' => array('', 'string'), + + // some visitor attributes can be overwritten + 'cip' => array(false, 'string'), + 'cdt' => array(false, 'string'), + 'cid' => array(false, 'string'), + + // Actions / pages + 'cs' => array(false, 'string'), + 'download' => array('', 'string'), + 'link' => array('', 'string'), + 'action_name' => array('', 'string'), + 'search' => array('', 'string'), + 'search_cat' => array(false, 'string'), + 'search_count' => array(-1, 'int'), + 'gt_ms' => array(-1, 'int'), + ); + + if (!isset($supportedParams[$name])) { + throw new Exception("Requested parameter $name is not a known Tracking API Parameter."); + } + $paramDefaultValue = $supportedParams[$name][0]; + $paramType = $supportedParams[$name][1]; + + $value = Piwik_Common::getRequestVar($name, $paramDefaultValue, $paramType, $this->params); + + if ($paramType == 'string') { + return trim(urldecode($value)); + } + return $value; + } + + public function getCurrentTimestamp() + { + return $this->timestamp; + } + + protected function isTimestampValid($time) + { + return $time <= $this->getCurrentTimestamp() + && $time > $this->getCurrentTimestamp() - 10 * 365 * 86400; + } + + public function getIdSite() + { + static $idSite = null; + + if (is_null($idSite)) { + $idSite = Piwik_Common::getRequestVar('idsite', 0, 'int', $this->params); + Piwik_PostEvent('Tracker.setRequest.idSite', $idSite, $this->params); + if ($idSite <= 0) { + throw new Exception('Invalid idSite'); + } + } + return $idSite; + } + + public function getUserAgent() + { + $default = @$_SERVER['HTTP_USER_AGENT']; + return Piwik_Common::getRequestVar('ua', is_null($default) ? false : $default, 'string', $this->params); + } + + public function getCustomVariables($scope) + { + if ($scope == 'visit') { + $parameter = '_cvar'; + } else { + $parameter = 'cvar'; + } + + $customVar = Piwik_Common::unsanitizeInputValues(Piwik_Common::getRequestVar($parameter, '', 'json', $this->params)); + if (!is_array($customVar)) { + return array(); + } + $customVariables = array(); + foreach ($customVar as $id => $keyValue) { + $id = (int)$id; + if ($id < 1 + || $id > Piwik_Tracker::MAX_CUSTOM_VARIABLES + || count($keyValue) != 2 + || (!is_string($keyValue[0]) && !is_numeric($keyValue[0])) + ) { + printDebug("Invalid custom variables detected (id=$id)"); + continue; + } + if (strlen($keyValue[1]) == 0) { + $keyValue[1] = ""; + } + // We keep in the URL when Custom Variable have empty names + // and values, as it means they can be deleted server side + + $key = self::truncateCustomVariable($keyValue[0]); + $value = self::truncateCustomVariable($keyValue[1]); + $customVariables['custom_var_k' . $id] = $key; + $customVariables['custom_var_v' . $id] = $value; + } + + return $customVariables; + } + + static public function truncateCustomVariable($input) + { + return substr(trim($input), 0, Piwik_Tracker::MAX_LENGTH_CUSTOM_VARIABLE); + } + + protected function shouldUseThirdPartyCookie() + { + return (bool)Piwik_Config::getInstance()->Tracker['use_third_party_id_cookie']; + } + + /** + * Update the cookie information. + */ + public function setThirdPartyCookie($idVisitor) + { + if (!$this->shouldUseThirdPartyCookie()) { + return; + } + printDebug("We manage the cookie..."); + + $cookie = $this->makeThirdPartyCookie(); + // idcookie has been generated in handleNewVisit or we simply propagate the old value + $cookie->set(0, bin2hex($idVisitor)); + $cookie->save(); + } + + protected function makeThirdPartyCookie() + { + $cookie = new Piwik_Cookie( + $this->getCookieName(), + $this->getCookieExpire(), + $this->getCookiePath()); + printDebug($cookie); + return $cookie; + } + + protected function getCookieName() + { + return Piwik_Config::getInstance()->Tracker['cookie_name']; + } + + protected function getCookieExpire() + { + return $this->getCurrentTimestamp() + Piwik_Config::getInstance()->Tracker['cookie_expire']; + } + + protected function getCookiePath() + { + return Piwik_Config::getInstance()->Tracker['cookie_path']; + } + + /** + * Is the request for a known VisitorId, based on 1st party, 3rd party (optional) cookies or Tracking API forced Visitor ID + * @throws Exception + */ + public function getVisitorId() + { + $found = false; + + // Was a Visitor ID "forced" (@see Tracking API setVisitorId()) for this request? + $idVisitor = $this->getForcedVisitorId(); + if (!empty($idVisitor)) { + if (strlen($idVisitor) != Piwik_Tracker::LENGTH_HEX_ID_STRING) { + throw new Exception("Visitor ID (cid) $idVisitor must be " . Piwik_Tracker::LENGTH_HEX_ID_STRING . " characters long"); + } + printDebug("Request will be recorded for this idvisitor = " . $idVisitor); + $found = true; + } + + // - If set to use 3rd party cookies for Visit ID, read the cookie + if (!$found) { + // - By default, reads the first party cookie ID + $useThirdPartyCookie = $this->shouldUseThirdPartyCookie(); + if ($useThirdPartyCookie) { + $cookie = $this->makeThirdPartyCookie(); + $idVisitor = $cookie->get(0); + if ($idVisitor !== false + && strlen($idVisitor) == Piwik_Tracker::LENGTH_HEX_ID_STRING + ) { + $found = true; + } + } + } + // If a third party cookie was not found, we default to the first party cookie + if (!$found) { + $idVisitor = Piwik_Common::getRequestVar('_id', '', 'string', $this->params); + $found = strlen($idVisitor) >= Piwik_Tracker::LENGTH_HEX_ID_STRING; + } + + if ($found) { + $truncated = substr($idVisitor, 0, Piwik_Tracker::LENGTH_HEX_ID_STRING); + $binVisitorId = @Piwik_Common::hex2bin($truncated); + if (!empty($binVisitorId)) { + return $binVisitorId; + } + } + return false; + } + + public function setForcedVisitorId($visitorId) + { + $this->forcedVisitorId = $visitorId; + } + + public function getForcedVisitorId() + { + return $this->forcedVisitorId; + } + + public function enrichLocation($location) + { + if (!$this->isAuthenticated()) { + return $location; + } + + // check for location override query parameters (ie, lat, long, country, region, city) + $locationOverrideParams = array( + 'country' => array('string', Piwik_UserCountry_LocationProvider::COUNTRY_CODE_KEY), + 'region' => array('string', Piwik_UserCountry_LocationProvider::REGION_CODE_KEY), + 'city' => array('string', Piwik_UserCountry_LocationProvider::CITY_NAME_KEY), + 'lat' => array('float', Piwik_UserCountry_LocationProvider::LATITUDE_KEY), + 'long' => array('float', Piwik_UserCountry_LocationProvider::LONGITUDE_KEY), + ); + foreach ($locationOverrideParams as $queryParamName => $info) { + list($type, $locationResultKey) = $info; + + $value = Piwik_Common::getRequestVar($queryParamName, false, $type, $this->params); + if (!empty($value)) { + $location[$locationResultKey] = $value; + } + } + return $location; + } + + public function getPlugins() + { + $pluginsInOrder = array('fla', 'java', 'dir', 'qt', 'realp', 'pdf', 'wma', 'gears', 'ag', 'cookie'); + $plugins = array(); + foreach ($pluginsInOrder as $param) { + $plugins[] = Piwik_Common::getRequestVar($param, 0, 'int', $this->params); + } + return $plugins; + } + + public function getParamsCount() + { + return count($this->params); + } +}
\ No newline at end of file diff --git a/core/Tracker/Visit.php b/core/Tracker/Visit.php index 0c12b47ee6..9b30d362a0 100644 --- a/core/Tracker/Visit.php +++ b/core/Tracker/Visit.php @@ -15,7 +15,7 @@ */ interface Piwik_Tracker_Visit_Interface { - function setRequest($requestArray); + function setRequest(Piwik_Tracker_Request $request); function handle(); } @@ -38,40 +38,28 @@ class Piwik_Tracker_Visit implements Piwik_Tracker_Visit_Interface { const UNKNOWN_CODE = 'xx'; - /** - * @var Piwik_Cookie - */ - protected $cookie = null; protected $visitorInfo = array(); protected $userSettingsInformation = null; protected $visitorCustomVariables = array(); - protected $idsite; protected $visitorKnown; + + /** + * @var Piwik_Tracker_GoalManager + */ + protected $goalManager; + /** + * @var Piwik_Tracker_Request + */ protected $request; protected $forcedVisitorId = null; // can be overwritten in constructor protected $timestamp; protected $ip; - protected $authenticated = false; - // Set to true when we set some custom variables from the cookie - protected $customVariablesSetFromRequest = false; - - /** - * @var Piwik_Tracker_GoalManager - */ - protected $goalManager; - public function __construct($forcedIpString = null, $forcedDateTime = null, $authenticated = false) + public function __construct($forcedIpString = null) { - $this->timestamp = time(); - if (!empty($forcedDateTime)) { - if (!is_numeric($forcedDateTime)) { - $forcedDateTime = strtotime($forcedDateTime); - } - $this->timestamp = $forcedDateTime; - } $ipString = $forcedIpString; if (empty($ipString)) { $ipString = Piwik_IP::getIpFromHeader(); @@ -79,34 +67,11 @@ class Piwik_Tracker_Visit implements Piwik_Tracker_Visit_Interface $ip = Piwik_IP::P2N($ipString); $this->ip = $ip; - - $this->authenticated = $authenticated; } - function setForcedVisitorId($visitorId) + function setRequest(Piwik_Tracker_Request $request) { - $this->forcedVisitorId = $visitorId; - } - - function setRequest($requestArray) - { - $this->request = $requestArray; - - $idsite = Piwik_Common::getRequestVar('idsite', 0, 'int', $this->request); - Piwik_PostEvent('Tracker.setRequest.idSite', $idsite, $requestArray); - if ($idsite <= 0) { - throw new Exception('Invalid idSite'); - } - $this->idsite = $idsite; - - // When the 'url' and referer url parameter are not given, we might be in the 'Simple Image Tracker' mode. - // The URL can default to the Referer, which will be in this case - // the URL of the page containing the Simple Image beacon - if (empty($this->request['urlref']) - && empty($this->request['url']) - ) { - $this->request['url'] = @$_SERVER['HTTP_REFERER']; - } + $this->request = $request; } /** @@ -134,9 +99,8 @@ class Piwik_Tracker_Visit implements Piwik_Tracker_Visit_Interface // the IP is needed by isExcluded() and GoalManager->recordGoals() $this->visitorInfo['location_ip'] = $this->ip; - $ua = $this->getUserAgent($this->request); $ip = $this->getVisitorIp(); - $excluded = new Piwik_Tracker_VisitExcluded($this->request, $this->idsite, $ip, $ua); + $excluded = new Piwik_Tracker_VisitExcluded($this->request, $ip); if ($excluded->isExcluded()) { return; } @@ -146,21 +110,18 @@ class Piwik_Tracker_Visit implements Piwik_Tracker_Visit_Interface Piwik_PostEvent('Tracker.Visit.setVisitorIp', $ip); $this->visitorInfo['location_ip'] = $ip; - $this->visitorCustomVariables = self::getCustomVariables($scope = 'visit', $this->request); + $this->visitorCustomVariables = $this->request->getCustomVariables($scope = 'visit'); if (!empty($this->visitorCustomVariables)) { printDebug("Visit level Custom Variables: "); printDebug($this->visitorCustomVariables); - $this->customVariablesSetFromRequest = true; } - $this->goalManager = new Piwik_Tracker_GoalManager(); + $this->goalManager = new Piwik_Tracker_GoalManager($this->request); - $someGoalsConverted = $visitIsConverted = false; + $visitIsConverted = false; $idActionUrl = $idActionName = $actionType = false; $action = null; - $this->goalManager->init($this->request); - $requestIsManualGoalConversion = ($this->goalManager->idGoal > 0); $requestIsEcommerce = $this->goalManager->requestIsEcommerce; if ($requestIsEcommerce) { @@ -172,7 +133,7 @@ class Piwik_Tracker_Visit implements Piwik_Tracker_Visit_Interface } } // this request is from the JS call to piwikTracker.trackGoal() elseif ($requestIsManualGoalConversion) { - $someGoalsConverted = $this->goalManager->detectGoalId($this->idsite); + $someGoalsConverted = $this->goalManager->detectGoalId($this->request->getIdSite()); $visitIsConverted = $someGoalsConverted; // if we find a idgoal in the URL, but then the goal is not valid, this is most likely a fake request if (!$someGoalsConverted) { @@ -183,8 +144,17 @@ class Piwik_Tracker_Visit implements Piwik_Tracker_Visit_Interface } // normal page view, potentially triggering a URL matching goal else { $action = $this->newAction(); - $this->handleAction($action); - $someGoalsConverted = $this->goalManager->detectGoalsMatchingUrl($this->idsite, $action); + + if ($this->detectActionIsOutlinkOnAliasHost($action)) { + printDebug("INFO: The outlink URL host is one of the known host for this website. "); + } + if (isset($GLOBALS['PIWIK_TRACKER_DEBUG']) && $GLOBALS['PIWIK_TRACKER_DEBUG']) { + $type = Piwik_Tracker_Action::getActionTypeName($action->getActionType()); + printDebug("Action is a $type, + Action name = " . $action->getActionName() . ", + Action URL = " . $action->getActionUrl()); + } + $someGoalsConverted = $this->goalManager->detectGoalsMatchingUrl($this->request->getIdSite(), $action); $visitIsConverted = $someGoalsConverted; $action->loadIdActionNameAndUrl(); @@ -260,53 +230,19 @@ class Piwik_Tracker_Visit implements Piwik_Tracker_Visit_Interface } // update the cookie with the new visit information - $this->setThirdPartyCookie(); + $this->request->setThirdPartyCookie($this->visitorInfo['idvisitor']); // record the goals if applicable if ($someGoalsConverted) { - $refererTimestamp = Piwik_Common::getRequestVar('_refts', 0, 'int', $this->request); - $refererUrl = Piwik_Common::getRequestVar('_ref', '', 'string', $this->request); - $refererCampaignName = trim(urldecode(Piwik_Common::getRequestVar('_rcn', '', 'string', $this->request))); - $refererCampaignKeyword = trim(urldecode(Piwik_Common::getRequestVar('_rck', '', 'string', $this->request))); - $this->goalManager->recordGoals( - $this->idsite, + $this->request->getIdSite(), $this->visitorInfo, $this->visitorCustomVariables, - $action, - $refererTimestamp, - $refererUrl, - $refererCampaignName, - $refererCampaignKeyword, - $this->getBrowserLanguage() + $action ); } unset($this->goalManager); unset($action); - $this->printCookie(); - } - - protected function printCookie() - { - printDebug($this->cookie); - } - - protected function handleAction($action) - { - $action->setIdSite($this->idsite); - $action->setRequest($this->request); - $action->setTimestamp($this->getCurrentTimestamp()); - $action->init(); - - if ($this->detectActionIsOutlinkOnAliasHost($action)) { - printDebug("Info: The outlink URL host is one of the known host for this website. "); - } - if (isset($GLOBALS['PIWIK_TRACKER_DEBUG']) && $GLOBALS['PIWIK_TRACKER_DEBUG']) { - $type = Piwik_Tracker_Action::getActionTypeName($action->getActionType()); - printDebug("Action is a $type, - Action name = " . $action->getActionName() . ", - Action URL = " . $action->getActionUrl()); - } } /** @@ -351,11 +287,11 @@ class Piwik_Tracker_Visit implements Piwik_Tracker_Visit_Interface } printDebug("Visit is known (IP = " . Piwik_IP::N2P($this->getVisitorIp()) . ")"); - $datetimeServer = Piwik_Tracker::getDatetimeFromTimestamp($this->getCurrentTimestamp()); + $datetimeServer = Piwik_Tracker::getDatetimeFromTimestamp($this->request->getCurrentTimestamp()); $valuesToUpdate['visit_last_action_time'] = $datetimeServer; // Add 1 so it's always > 0 - $visitTotalTime = 1 + $this->getCurrentTimestamp() - $this->visitorInfo['visit_first_action_time']; + $visitTotalTime = 1 + $this->request->getCurrentTimestamp() - $this->visitorInfo['visit_first_action_time']; $valuesToUpdate['visit_total_time'] = self::cleanupVisitTotalTime($visitTotalTime); // Goal conversion @@ -403,11 +339,11 @@ class Piwik_Tracker_Visit implements Piwik_Tracker_Visit_Interface SET $sqlActionUpdate " . implode($updateParts, ', ') . " WHERE idsite = ? AND idvisit = ?"; - array_push($sqlBind, $this->idsite, (int)$this->visitorInfo['idvisit']); + array_push($sqlBind, $this->request->getIdSite(), (int)$this->visitorInfo['idvisit']); $result = Piwik_Tracker::getDatabase()->query($sqlQuery, $sqlBind); - $this->visitorInfo['visit_last_action_time'] = $this->getCurrentTimestamp(); + $this->visitorInfo['visit_last_action_time'] = $this->request->getCurrentTimestamp(); // Debug output if (isset($valuesToUpdate['idvisitor'])) { @@ -432,7 +368,7 @@ class Piwik_Tracker_Visit implements Piwik_Tracker_Visit_Interface */ protected function getTimeSpentRefererAction() { - $timeSpent = $this->getCurrentTimestamp() - $this->visitorInfo['visit_last_action_time']; + $timeSpent = $this->request->getCurrentTimestamp() - $this->visitorInfo['visit_last_action_time']; if ($timeSpent < 0 || $timeSpent > Piwik_Config::getInstance()->Tracker['visit_standard_length'] ) { @@ -441,12 +377,6 @@ class Piwik_Tracker_Visit implements Piwik_Tracker_Visit_Interface return $timeSpent; } - protected function isTimestampValid($time) - { - return $time <= $this->getCurrentTimestamp() - && $time > $this->getCurrentTimestamp() - 10 * 365 * 86400; - } - /** * In the case of a new visit, we have to do the following actions: * @@ -462,51 +392,15 @@ class Piwik_Tracker_Visit implements Piwik_Tracker_Visit_Interface { printDebug("New Visit (IP = " . Piwik_IP::N2P($this->getVisitorIp()) . ")"); - $localTimes = array( - 'h' => (string)Piwik_Common::getRequestVar('h', $this->getCurrentDate("H"), 'int', $this->request), - 'i' => (string)Piwik_Common::getRequestVar('m', $this->getCurrentDate("i"), 'int', $this->request), - 's' => (string)Piwik_Common::getRequestVar('s', $this->getCurrentDate("s"), 'int', $this->request) - ); - foreach ($localTimes as $k => $time) { - if (strlen($time) == 1) { - $localTimes[$k] = '0' . $time; - } - } - $localTime = $localTimes['h'] . ':' . $localTimes['i'] . ':' . $localTimes['s']; + $daysSinceFirstVisit = $this->request->getDaysSinceFirstVisit(); + $visitCount = $this->request->getVisitCount(); + $daysSinceLastVisit = $this->request->getDaysSinceLastVisit(); - $idcookie = $this->getVisitorIdcookie(); + $daysSinceLastOrder = $this->request->getDaysSinceLastOrder(); + $isReturningCustomer = ($daysSinceLastOrder !== false); - $defaultTimeOnePageVisit = Piwik_Config::getInstance()->Tracker['default_time_one_page_visit']; - - // Days since first visit - $cookieFirstVisitTimestamp = Piwik_Common::getRequestVar('_idts', 0, 'int', $this->request); - if (!$this->isTimestampValid($cookieFirstVisitTimestamp)) { - $cookieFirstVisitTimestamp = $this->getCurrentTimestamp(); - } - $daysSinceFirstVisit = round(($this->getCurrentTimestamp() - $cookieFirstVisitTimestamp) / 86400, $precision = 0); - if ($daysSinceFirstVisit < 0) $daysSinceFirstVisit = 0; - - // Number of Visits - $visitCount = Piwik_Common::getRequestVar('_idvc', 1, 'int', $this->request); - if ($visitCount < 1) $visitCount = 1; - - // Days since last visit - $daysSinceLastVisit = 0; - $lastVisitTimestamp = Piwik_Common::getRequestVar('_viewts', 0, 'int', $this->request); - if ($this->isTimestampValid($lastVisitTimestamp)) { - $daysSinceLastVisit = round(($this->getCurrentTimestamp() - $lastVisitTimestamp) / 86400, $precision = 0); - if ($daysSinceLastVisit < 0) $daysSinceLastVisit = 0; - } - - $daysSinceLastOrder = 0; - $isReturningCustomer = false; - $lastOrderTimestamp = Piwik_Common::getRequestVar('_ects', 0, 'int', $this->request); - if ($this->isTimestampValid($lastOrderTimestamp)) { - $daysSinceLastOrder = round(($this->getCurrentTimestamp() - $lastOrderTimestamp) / 86400, $precision = 0); - if ($daysSinceLastOrder < 0) { - $daysSinceLastOrder = 0; - } - $isReturningCustomer = true; + if($daysSinceLastOrder === false) { + $daysSinceLastOrder = 0; } // User settings @@ -514,29 +408,31 @@ class Piwik_Tracker_Visit implements Piwik_Tracker_Visit_Interface // Referrer data $referrer = new Piwik_Tracker_Referer(); - $refererUrl = Piwik_Common::getRequestVar('urlref', '', 'string', $this->request); - $currentUrl = Piwik_Common::getRequestVar('url', '', 'string', $this->request); - $refererInfo = $referrer->getRefererInformation($refererUrl, $currentUrl, $this->idsite); + $refererUrl = $this->request->getParam('urlref'); + $currentUrl = $this->request->getParam('url'); + $refererInfo = $referrer->getRefererInformation($refererUrl, $currentUrl, $this->request->getIdSite()); $visitorReturning = $isReturningCustomer ? 2 /* Returning customer */ : ($visitCount > 1 || $this->isVisitorKnown() || $daysSinceLastVisit > 0 ? 1 /* Returning */ : 0 /* New */); + $defaultTimeOnePageVisit = Piwik_Config::getInstance()->Tracker['default_time_one_page_visit']; + /** * Save the visitor */ $this->visitorInfo = array( - 'idsite' => $this->idsite, - 'visitor_localtime' => $localTime, - 'idvisitor' => $idcookie, + 'idsite' => $this->request->getIdSite(), + 'visitor_localtime' => $this->request->getLocalTime(), + 'idvisitor' => $this->getVisitorIdcookie(), 'visitor_returning' => $visitorReturning, 'visitor_count_visits' => $visitCount, 'visitor_days_since_last' => $daysSinceLastVisit, 'visitor_days_since_order' => $daysSinceLastOrder, 'visitor_days_since_first' => $daysSinceFirstVisit, - 'visit_first_action_time' => Piwik_Tracker::getDatetimeFromTimestamp($this->getCurrentTimestamp()), - 'visit_last_action_time' => Piwik_Tracker::getDatetimeFromTimestamp($this->getCurrentTimestamp()), + 'visit_first_action_time' => Piwik_Tracker::getDatetimeFromTimestamp($this->request->getCurrentTimestamp()), + 'visit_last_action_time' => Piwik_Tracker::getDatetimeFromTimestamp($this->request->getCurrentTimestamp()), 'visit_entry_idaction_url' => (int)$idActionUrl, 'visit_entry_idaction_name' => (int)$idActionName, 'visit_exit_idaction_url' => (int)$idActionUrl, @@ -582,7 +478,7 @@ class Piwik_Tracker_Visit implements Piwik_Tracker_Visit_Interface $this->visitorInfo = array_merge($this->visitorInfo, $this->visitorCustomVariables); $extraInfo = array( - 'UserAgent' => $this->getUserAgent($this->request), + 'UserAgent' => $this->request->getUserAgent(), ); Piwik_PostEvent('Tracker.newVisitorInformation', $this->visitorInfo, $extraInfo); @@ -619,24 +515,7 @@ class Piwik_Tracker_Visit implements Piwik_Tracker_Visit_Interface $userInfo = array('lang' => $browserLang, 'ip' => Piwik_IP::N2P($this->getVisitorIp())); Piwik_PostEvent('Tracker.getVisitorLocation', $location, $userInfo); - if ($this->authenticated) { - // check for location override query parameters (ie, lat, long, country, region, city) - $locationOverrideParams = array( - 'country' => array('string', Piwik_UserCountry_LocationProvider::COUNTRY_CODE_KEY), - 'region' => array('string', Piwik_UserCountry_LocationProvider::REGION_CODE_KEY), - 'city' => array('string', Piwik_UserCountry_LocationProvider::CITY_NAME_KEY), - 'lat' => array('float', Piwik_UserCountry_LocationProvider::LATITUDE_KEY), - 'long' => array('float', Piwik_UserCountry_LocationProvider::LONGITUDE_KEY), - ); - foreach ($locationOverrideParams as $queryParamName => $info) { - list($type, $locationResultKey) = $info; - - $value = Piwik_Common::getRequestVar($queryParamName, false, $type, $this->request); - if (!empty($value)) { - $location[$locationResultKey] = $value; - } - } - } + $location = $this->request->enrichLocation($location); if (empty($location['country_code'])) // sanity check { @@ -718,8 +597,8 @@ class Piwik_Tracker_Visit implements Piwik_Tracker_Visit_Interface $idVisit = Piwik_Tracker::getDatabase()->lastInsertId(); $this->visitorInfo['idvisit'] = $idVisit; - $this->visitorInfo['visit_first_action_time'] = $this->getCurrentTimestamp(); - $this->visitorInfo['visit_last_action_time'] = $this->getCurrentTimestamp(); + $this->visitorInfo['visit_first_action_time'] = $this->request->getCurrentTimestamp(); + $this->visitorInfo['visit_last_action_time'] = $this->request->getCurrentTimestamp(); Piwik_PostEvent('Tracker.saveVisitorInformation.end', $this->visitorInfo); } @@ -762,137 +641,6 @@ class Piwik_Tracker_Visit implements Piwik_Tracker_Visit_Interface return $this->visitorInfo['location_ip']; } - /** - * Returns the visitor's browser (user agent) - * - * @param array $request request array to use - * - * @return string - */ - static public function getUserAgent($request) - { - $default = @$_SERVER['HTTP_USER_AGENT']; - return Piwik_Common::getRequestVar('ua', is_null($default) ? false : $default, 'string', $request); - } - - /** - * Returns the language the visitor is viewing. - * - * @return string browser language code, eg. "en-gb,en;q=0.5" - */ - protected function getBrowserLanguage() - { - return Piwik_Common::getRequestVar('lang', Piwik_Common::getBrowserLanguage(), 'string', $this->request); - } - - /** - * Returns the current date in the "Y-m-d" PHP format - * - * @param string $format - * @return string - */ - protected function getCurrentDate($format = "Y-m-d") - { - return date($format, $this->getCurrentTimestamp()); - } - - /** - * Returns the current Timestamp - * - * @return int - */ - protected function getCurrentTimestamp() - { - return $this->timestamp; - } - - - /** - * Returns the cookie name used for the Piwik Tracker cookie - * - * @return string - */ - protected function getCookieName() - { - return Piwik_Config::getInstance()->Tracker['cookie_name']; - } - - /** - * Returns the cookie expiration date. - * - * @return int - */ - protected function getCookieExpire() - { - return $this->getCurrentTimestamp() + Piwik_Config::getInstance()->Tracker['cookie_expire']; - } - - /** - * Returns cookie path - * - * @return string - */ - protected function getCookiePath() - { - return Piwik_Config::getInstance()->Tracker['cookie_path']; - } - - protected function shouldUseThirdPartyCookie() - { - return (bool)Piwik_Config::getInstance()->Tracker['use_third_party_id_cookie']; - } - - /** - * Is the request for a known VisitorId, based on 1st party, 3rd party (optional) cookies or Tracking API forced Visitor ID - * @throws Exception - */ - protected function assignVisitorIdFromRequest() - { - $found = false; - - // Was a Visitor ID "forced" (@see Tracking API setVisitorId()) for this request? - $idVisitor = $this->getForcedVisitorId(); - if (!empty($idVisitor)) { - if (strlen($idVisitor) != Piwik_Tracker::LENGTH_HEX_ID_STRING) { - throw new Exception("Visitor ID (cid) $idVisitor must be " . Piwik_Tracker::LENGTH_HEX_ID_STRING . " characters long"); - } - printDebug("Request will be recorded for this idvisitor = " . $idVisitor); - $found = true; - } - - // - If set to use 3rd party cookies for Visit ID, read the cookie - if (!$found) { - // - By default, reads the first party cookie ID - $useThirdPartyCookie = $this->shouldUseThirdPartyCookie(); - if ($useThirdPartyCookie) { - $idVisitor = $this->cookie->get(0); - if ($idVisitor !== false - && strlen($idVisitor) == Piwik_Tracker::LENGTH_HEX_ID_STRING - ) { - $found = true; - } - } - } - // If a third party cookie was not found, we default to the first party cookie - if (!$found) { - $idVisitor = Piwik_Common::getRequestVar('_id', '', 'string', $this->request); - $found = strlen($idVisitor) >= Piwik_Tracker::LENGTH_HEX_ID_STRING; - } - - if ($found) { - $truncated = substr($idVisitor, 0, Piwik_Tracker::LENGTH_HEX_ID_STRING); - $binVisitorId = @Piwik_Common::hex2bin($truncated); - if (!empty($binVisitorId)) { - $this->visitorInfo['idvisitor'] = $binVisitorId; - } - - } - } - - protected function getForcedVisitorId() - { - return $this->forcedVisitorId; - } /** * This methods tries to see if the visitor has visited the website before. @@ -904,19 +652,15 @@ class Piwik_Tracker_Visit implements Piwik_Tracker_Visit_Interface protected function recognizeTheVisitor() { $this->visitorKnown = false; - $this->setCookie(new Piwik_Cookie( - $this->getCookieName(), - $this->getCookieExpire(), - $this->getCookiePath())); - $this->printCookie(); $userInfo = $this->getUserSettingsInformation(); $configId = $userInfo['config_id']; - $this->assignVisitorIdFromRequest(); - $isVisitorIdToLookup = !empty($this->visitorInfo['idvisitor']); + $idVisitor = $this->request->getVisitorId(); + $isVisitorIdToLookup = !empty($idVisitor); if ($isVisitorIdToLookup) { + $this->visitorInfo['idvisitor'] = $idVisitor; printDebug("Matching visitors with: visitorId=" . bin2hex($this->visitorInfo['idvisitor']) . " OR configId=" . bin2hex($configId)); } else { printDebug("Visitor doesn't have the piwik cookie..."); @@ -924,7 +668,7 @@ class Piwik_Tracker_Visit implements Piwik_Tracker_Visit_Interface $selectCustomVariables = ''; // No custom var were found in the request, so let's copy the previous one in a potential conversion later - if (!$this->customVariablesSetFromRequest) { + if (!$this->visitorCustomVariables) { $selectCustomVariables = ', custom_var_k1, custom_var_v1, custom_var_k2, custom_var_v2, @@ -972,16 +716,16 @@ class Piwik_Tracker_Visit implements Piwik_Tracker_Visit_Interface $bindSql = array( $timeLookBack, $timeLookAhead, - $this->idsite + $this->request->getIdSite() ); if ($shouldMatchOneFieldOnly) { - if (!$isVisitorIdToLookup) { - $whereCommon .= ' AND config_id = ?'; - $bindSql[] = $configId; - } else { + if ($isVisitorIdToLookup) { $whereCommon .= ' AND idvisitor = ?'; $bindSql[] = $this->visitorInfo['idvisitor']; + } else { + $whereCommon .= ' AND config_id = ?'; + $bindSql[] = $configId; } $sql = "$select @@ -1012,7 +756,7 @@ class Piwik_Tracker_Visit implements Piwik_Tracker_Visit_Interface // will use INDEX index_idsite_idvisitor (idsite, idvisitor) $bindSql[] = $timeLookBack; $bindSql[] = $timeLookAhead; - $bindSql[] = $this->idsite; + $bindSql[] = $this->request->getIdSite(); $where = ' AND idvisitor = ?'; $bindSql[] = $this->visitorInfo['idvisitor']; $sqlVisitorId = "$select , @@ -1034,8 +778,11 @@ class Piwik_Tracker_Visit implements Piwik_Tracker_Visit_Interface $visitRow = Piwik_Tracker::getDatabase()->fetch($sql, $bindSql); - $newVisitEnforcedAPI = !empty($this->request['new_visit']) - && ($this->authenticated || !Piwik_Config::getInstance()->Tracker['new_visit_api_requires_admin']); + $isNewVisitForced = $this->request->getParam('new_visit'); + $isNewVisitForced = !empty($isNewVisitForced); + $newVisitEnforcedAPI = $isNewVisitForced + && ($this->request->isAuthenticated() + || !Piwik_Config::getInstance()->Tracker['new_visit_api_requires_admin']); $enforceNewVisit = $newVisitEnforcedAPI || Piwik_Config::getInstance()->Debug['tracker_always_new_visitor']; if (!$enforceNewVisit @@ -1110,16 +857,16 @@ class Piwik_Tracker_Visit implements Piwik_Tracker_Visit_Interface protected function getWindowLookupThisVisit() { $visitStandardLength = Piwik_Config::getInstance()->Tracker['visit_standard_length']; - $lookbackNSecondsCustom = Piwik_Config::getInstance()->Tracker['window_look_back_for_visitor']; + $lookBackNSecondsCustom = Piwik_Config::getInstance()->Tracker['window_look_back_for_visitor']; $lookAheadNSeconds = $visitStandardLength; - $lookbackNSeconds = $visitStandardLength; - if ($lookbackNSecondsCustom > $lookbackNSeconds) { - $lookbackNSeconds = $lookbackNSecondsCustom; + $lookBackNSeconds = $visitStandardLength; + if ($lookBackNSecondsCustom > $lookBackNSeconds) { + $lookBackNSeconds = $lookBackNSecondsCustom; } - $timeLookBack = date('Y-m-d H:i:s', $this->getCurrentTimestamp() - $lookbackNSeconds); - $timeLookAhead = date('Y-m-d H:i:s', $this->getCurrentTimestamp() + $lookAheadNSeconds); + $timeLookBack = date('Y-m-d H:i:s', $this->request->getCurrentTimestamp() - $lookBackNSeconds); + $timeLookAhead = date('Y-m-d H:i:s', $this->request->getCurrentTimestamp() + $lookAheadNSeconds); return array($timeLookBack, $timeLookAhead); } @@ -1132,7 +879,7 @@ class Piwik_Tracker_Visit implements Piwik_Tracker_Visit_Interface $trustCookiesOnly = Piwik_Config::getInstance()->Tracker['trust_visitors_cookies']; // If a &cid= was set, we force to select this visitor (or create a new one) - $isForcedVisitorIdMustMatch = ($this->getForcedVisitorId() != null); + $isForcedVisitorIdMustMatch = ($this->request->getForcedVisitorId() != null); $shouldMatchOneFieldOnly = (($isVisitorIdToLookup && $trustCookiesOnly) || $isForcedVisitorIdMustMatch @@ -1140,49 +887,6 @@ class Piwik_Tracker_Visit implements Piwik_Tracker_Visit_Interface return $shouldMatchOneFieldOnly; } - static public function getCustomVariables($scope, $request) - { - if ($scope == 'visit') { - $parameter = '_cvar'; - } else { - $parameter = 'cvar'; - } - - $customVar = Piwik_Common::unsanitizeInputValues(Piwik_Common::getRequestVar($parameter, '', 'json', $request)); - if (!is_array($customVar)) { - return array(); - } - $customVariables = array(); - foreach ($customVar as $id => $keyValue) { - $id = (int)$id; - if ($id < 1 - || $id > Piwik_Tracker::MAX_CUSTOM_VARIABLES - || count($keyValue) != 2 - || (!is_string($keyValue[0]) && !is_numeric($keyValue[0])) - ) { - printDebug("Invalid custom variables detected (id=$id)"); - continue; - } - if (strlen($keyValue[1]) == 0) { - $keyValue[1] = ""; - } - // We keep in the URL when Custom Variable have empty names - // and values, as it means they can be deleted server side - - $key = self::truncateCustomVariable($keyValue[0]); - $value = self::truncateCustomVariable($keyValue[1]); - $customVariables['custom_var_k' . $id] = $key; - $customVariables['custom_var_v' . $id] = $value; - } - - return $customVariables; - } - - static public function truncateCustomVariable($input) - { - return substr(trim($input), 0, Piwik_Tracker::MAX_LENGTH_CUSTOM_VARIABLE); - } - /** * Gets the UserSettings information and returns them in an array of name => value * @@ -1196,18 +900,11 @@ class Piwik_Tracker_Visit implements Piwik_Tracker_Visit_Interface } require_once PIWIK_INCLUDE_PATH . '/libs/UserAgentParser/UserAgentParser.php'; - $plugin_Flash = Piwik_Common::getRequestVar('fla', 0, 'int', $this->request); - $plugin_Java = Piwik_Common::getRequestVar('java', 0, 'int', $this->request); - $plugin_Director = Piwik_Common::getRequestVar('dir', 0, 'int', $this->request); - $plugin_Quicktime = Piwik_Common::getRequestVar('qt', 0, 'int', $this->request); - $plugin_RealPlayer = Piwik_Common::getRequestVar('realp', 0, 'int', $this->request); - $plugin_PDF = Piwik_Common::getRequestVar('pdf', 0, 'int', $this->request); - $plugin_WindowsMedia = Piwik_Common::getRequestVar('wma', 0, 'int', $this->request); - $plugin_Gears = Piwik_Common::getRequestVar('gears', 0, 'int', $this->request); - $plugin_Silverlight = Piwik_Common::getRequestVar('ag', 0, 'int', $this->request); - $plugin_Cookie = Piwik_Common::getRequestVar('cookie', 0, 'int', $this->request); - - $userAgent = $this->getUserAgent($this->request); + list($plugin_Flash, $plugin_Java, $plugin_Director, $plugin_Quicktime, $plugin_RealPlayer, $plugin_PDF, + $plugin_WindowsMedia, $plugin_Gears, $plugin_Silverlight, $plugin_Cookie) = $this->request->getPlugins(); + + $resolution = $this->request->getParam('res'); + $userAgent = $this->request->getUserAgent(); $aBrowserInfo = UserAgentParser::getBrowser($userAgent); $browserName = ($aBrowserInfo !== false && $aBrowserInfo['id'] !== false) ? $aBrowserInfo['id'] : 'UNK'; @@ -1216,10 +913,7 @@ class Piwik_Tracker_Visit implements Piwik_Tracker_Visit_Interface $os = UserAgentParser::getOperatingSystem($userAgent); $os = $os === false ? 'UNK' : $os['id']; - $resolution = Piwik_Common::getRequestVar('res', 'unknown', 'string', $this->request); - - $browserLang = $this->getBrowserLanguage(); - + $browserLang = $this->request->getBrowserLanguage(); $configurationHash = $this->getConfigHash( $os, $browserName, @@ -1268,7 +962,7 @@ class Piwik_Tracker_Visit implements Piwik_Tracker_Visit_Interface { return isset($this->visitorInfo['visit_last_action_time']) && ($this->visitorInfo['visit_last_action_time'] - > ($this->getCurrentTimestamp() - Piwik_Config::getInstance()->Tracker['visit_standard_length'])); + > ($this->request->getCurrentTimestamp() - Piwik_Config::getInstance()->Tracker['visit_standard_length'])); } /** @@ -1281,21 +975,6 @@ class Piwik_Tracker_Visit implements Piwik_Tracker_Visit_Interface } /** - * Update the cookie information. - */ - protected function setThirdPartyCookie() - { - if (!$this->shouldUseThirdPartyCookie()) { - return; - } - printDebug("We manage the cookie..."); - - // idcookie has been generated in handleNewVisit or we simply propagate the old value - $this->cookie->set(0, bin2hex($this->visitorInfo['idvisitor'])); - $this->cookie->save(); - } - - /** * Returns an object able to handle the current action * Plugins can return an override Action that for example, does not record the action in the DB * @@ -1308,7 +987,7 @@ class Piwik_Tracker_Visit implements Piwik_Tracker_Visit_Interface Piwik_PostEvent('Tracker.newAction', $action); if (is_null($action)) { - $action = new Piwik_Tracker_Action(); + $action = new Piwik_Tracker_Action($this->request); } elseif (!($action instanceof Piwik_Tracker_Action_Interface)) { throw new Exception("The Action object set in the plugin must implement the interface Piwik_Tracker_Action_Interface"); } @@ -1331,7 +1010,7 @@ class Piwik_Tracker_Visit implements Piwik_Tracker_Visit_Interface if (!isset($actionUrlParsed['host'])) { return false; } - return Piwik_Tracker_Visit::isHostKnownAliasHost($actionUrlParsed['host'], $this->idsite); + return Piwik_Tracker_Visit::isHostKnownAliasHost($actionUrlParsed['host'], $this->request->getIdSite()); } /** @@ -1374,11 +1053,6 @@ class Piwik_Tracker_Visit implements Piwik_Tracker_Visit_Interface return Piwik_Common::generateUniqId(); } - protected function setCookie($cookie) - { - $this->cookie = $cookie; - } - // is the referer host any of the registered URLs for this website? static public function isHostKnownAliasHost($urlHost, $idSite) { diff --git a/core/Tracker/VisitExcluded.php b/core/Tracker/VisitExcluded.php index 7d23fce8e4..288e0b89b3 100644 --- a/core/Tracker/VisitExcluded.php +++ b/core/Tracker/VisitExcluded.php @@ -14,12 +14,12 @@ */ class Piwik_Tracker_VisitExcluded { - public function __construct($request, $idSite, $ip, $ua) + public function __construct(Piwik_Tracker_Request $request, $ip) { $this->request = $request; - $this->idSite = $idSite; + $this->idSite = $request->getIdSite(); + $this->userAgent = $request->getUserAgent(); $this->ip = $ip; - $this->userAgent = $ua; } /** @@ -46,8 +46,7 @@ class Piwik_Tracker_VisitExcluded * doesn't track non-JS visitors. */ if (!$excluded) { - $parameterForceRecord = 'rec'; - $toRecord = Piwik_Common::getRequestVar($parameterForceRecord, false, 'int', $this->request); + $toRecord = $this->request->getParam($parameterForceRecord = 'rec'); if (!$toRecord) { printDebug(@$_SERVER['REQUEST_METHOD'] . ' parameter ' . $parameterForceRecord . ' not found in URL, request excluded'); $excluded = true; @@ -7,7 +7,7 @@ * * @package Piwik */ -$GLOBALS['PIWIK_TRACKER_DEBUG'] = false; +$GLOBALS['PIWIK_TRACKER_DEBUG'] = !false; $GLOBALS['PIWIK_TRACKER_DEBUG_FORCE_SCHEDULED_TASKS'] = false; define('PIWIK_ENABLE_TRACKING', true); @@ -47,6 +47,9 @@ require_once PIWIK_INCLUDE_PATH . '/core/Tracker/IgnoreCookie.php'; require_once PIWIK_INCLUDE_PATH . '/core/Tracker/Visit.php'; require_once PIWIK_INCLUDE_PATH . '/core/Tracker/GoalManager.php'; require_once PIWIK_INCLUDE_PATH . '/core/Tracker/Action.php'; +require_once PIWIK_INCLUDE_PATH . '/core/Tracker/Request.php'; +require_once PIWIK_INCLUDE_PATH . '/core/Tracker/Referer.php'; +require_once PIWIK_INCLUDE_PATH . '/core/Tracker/VisitExcluded.php'; require_once PIWIK_INCLUDE_PATH . '/core/CacheFile.php'; require_once PIWIK_INCLUDE_PATH . '/core/Cookie.php'; diff --git a/plugins/DoNotTrack/DoNotTrack.php b/plugins/DoNotTrack/DoNotTrack.php index 16d8cbf7ed..9d84d0d0e4 100644 --- a/plugins/DoNotTrack/DoNotTrack.php +++ b/plugins/DoNotTrack/DoNotTrack.php @@ -52,7 +52,8 @@ class Piwik_DoNotTrack extends Piwik_Plugin if ((isset($_SERVER['HTTP_X_DO_NOT_TRACK']) && $_SERVER['HTTP_X_DO_NOT_TRACK'] === '1') || (isset($_SERVER['HTTP_DNT']) && substr($_SERVER['HTTP_DNT'], 0, 1) === '1') ) { - $ua = Piwik_Tracker_Visit::getUserAgent($_REQUEST); + $request = new Piwik_Tracker_Request($_REQUEST); + $ua = $request->getUserAgent(); if (strpos($ua, 'MSIE 10') !== false) { printDebug("INTERNET EXPLORER 10 Enables DNT by default, so Piwik ignores DNT for all IE10 browsers..."); return; diff --git a/plugins/UserSettings/functions.php b/plugins/UserSettings/functions.php index 80a63a589e..3f2f5c3697 100644 --- a/plugins/UserSettings/functions.php +++ b/plugins/UserSettings/functions.php @@ -207,7 +207,7 @@ function Piwik_UserSettings_keepStrlenGreater($value) function Piwik_getScreenTypeFromResolution($resolution) { - if ($resolution === 'unknown') { + if ($resolution === Piwik_Tracker_Request::UNKNOWN_RESOLUTION) { return $resolution; } diff --git a/tests/PHPUnit/Core/Tracker/ActionTest.php b/tests/PHPUnit/Core/Tracker/ActionTest.php index f6cb3321de..1938780923 100644 --- a/tests/PHPUnit/Core/Tracker/ActionTest.php +++ b/tests/PHPUnit/Core/Tracker/ActionTest.php @@ -359,9 +359,10 @@ class Tracker_ActionTest extends DatabaseTestCase { $this->setUpRootAccess(); $idSite = Piwik_SitesManager_API::getInstance()->addSite("site1", array('http://example.org')); - $action = new Test_Piwik_TrackerAction_extractUrlAndActionNameFromRequest(); - $action->setRequest($request); - $action->setIdSite($idSite); + $request['idsite'] = $idSite; + $request = new Piwik_Tracker_Request($request); + $action = new Test_Piwik_TrackerAction_extractUrlAndActionNameFromRequest($request); + $this->assertEquals($action->public_extractUrlAndActionNameFromRequest(), $expected); } } |