PluginProbe ʕ •ᴥ•ʔ
Matomo Analytics – Powerful, Privacy-First Insights for WordPress / 5.1.4
Matomo Analytics – Powerful, Privacy-First Insights for WordPress v5.1.4
5.12.0 5.11.1 5.11.0 5.10.2 5.10.1 trunk 1.0.2 1.0.3 1.0.4 1.0.5 1.0.6 1.1.0 1.1.1 1.1.2 1.1.3 1.2.0 1.3.0 1.3.1 1.3.2 4.0.0 4.0.1 4.0.2 4.0.3 4.0.4 4.1.0 4.1.1 4.1.2 4.1.3 4.10.0 4.11.0 4.12.0 4.13.0 4.13.2 4.13.3 4.13.4 4.13.5 4.14.0 4.14.1 4.14.2 4.15.0 4.15.1 4.15.2 4.15.3 4.2.0 4.3.0 4.3.1 4.4.1 4.4.2 4.5.0 4.6.0 5.0.1 5.0.2 5.0.3 5.0.4 5.0.5 5.0.6 5.0.7 5.0.8 5.1.0 5.1.1 5.1.2 5.1.3 5.1.4 5.1.5 5.1.6 5.1.7 5.10.0 5.2.0 5.2.1 5.2.2 5.3.0 5.3.1 5.3.2 5.3.3 5.6.0 5.6.1 5.7.0 5.7.1 5.8.0 5.8.1 5.8.2
matomo / app / core / Tracker.php
matomo / app / core Last commit date
API 2 years ago Access 2 years ago Application 2 years ago Archive 2 years ago ArchiveProcessor 2 years ago Archiver 2 years ago AssetManager 2 years ago Auth 2 years ago Category 2 years ago Changes 2 years ago CliMulti 2 years ago Columns 2 years ago Concurrency 2 years ago Config 2 years ago Container 2 years ago CronArchive 2 years ago DataAccess 2 years ago DataFiles 2 years ago DataTable 2 years ago Db 1 year ago DeviceDetector 2 years ago Email 2 years ago Exception 2 years ago Http 2 years ago Intl 2 years ago Log 2 years ago Mail 2 years ago Measurable 2 years ago Menu 2 years ago Metrics 2 years ago Notification 2 years ago Period 1 year ago Plugin 2 years ago ProfessionalServices 2 years ago Report 2 years ago ReportRenderer 2 years ago Scheduler 2 years ago Segment 2 years ago Session 2 years ago Settings 2 years ago Tracker 1 year ago Translation 2 years ago Twig 2 years ago UpdateCheck 2 years ago Updater 1 year ago Updates 1 year ago Validators 2 years ago View 2 years ago ViewDataTable 2 years ago Visualization 2 years ago Widget 2 years ago .htaccess 2 years ago Access.php 2 years ago Archive.php 2 years ago ArchiveProcessor.php 2 years ago AssetManager.php 2 years ago Auth.php 2 years ago AuthResult.php 2 years ago BaseFactory.php 2 years ago Cache.php 2 years ago CacheId.php 2 years ago CliMulti.php 2 years ago Common.php 2 years ago Config.php 2 years ago Console.php 2 years ago Context.php 2 years ago Cookie.php 2 years ago CronArchive.php 2 years ago DI.php 2 years ago DataArray.php 2 years ago DataTable.php 2 years ago Date.php 2 years ago Db.php 1 year ago DbHelper.php 1 year ago Development.php 2 years ago ErrorHandler.php 2 years ago EventDispatcher.php 2 years ago ExceptionHandler.php 2 years ago FileIntegrity.php 2 years ago Filechecks.php 2 years ago Filesystem.php 2 years ago FrontController.php 2 years ago Http.php 2 years ago IP.php 2 years ago Log.php 2 years ago LogDeleter.php 2 years ago Mail.php 2 years ago Metrics.php 2 years ago NoAccessException.php 2 years ago Nonce.php 2 years ago Notification.php 2 years ago NumberFormatter.php 2 years ago Option.php 2 years ago Period.php 2 years ago Piwik.php 2 years ago Plugin.php 2 years ago Profiler.php 2 years ago ProxyHeaders.php 2 years ago ProxyHttp.php 2 years ago QuickForm2.php 2 years ago RankingQuery.php 2 years ago ReportRenderer.php 2 years ago Request.php 2 years ago Segment.php 2 years ago Sequence.php 2 years ago Session.php 2 years ago SettingsPiwik.php 2 years ago SettingsServer.php 2 years ago Singleton.php 2 years ago Site.php 2 years ago SiteContentDetector.php 2 years ago SupportedBrowser.php 2 years ago TCPDF.php 2 years ago Theme.php 2 years ago Timer.php 2 years ago Tracker.php 2 years ago Twig.php 2 years ago Unzip.php 2 years ago UpdateCheck.php 2 years ago Updater.php 2 years ago UpdaterErrorException.php 2 years ago Updates.php 2 years ago Url.php 2 years ago UrlHelper.php 1 year ago Version.php 1 year ago View.php 2 years ago bootstrap.php 2 years ago dispatch.php 2 years ago testMinimumPhpVersion.php 2 years ago
Tracker.php
305 lines
1 <?php
2
3 /**
4 * Matomo - free/libre analytics platform
5 *
6 * @link https://matomo.org
7 * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
8 */
9 namespace Piwik;
10
11 use Exception;
12 use Piwik\Container\StaticContainer;
13 use Piwik\Plugins\BulkTracking\Tracker\Requests;
14 use Piwik\Plugins\PrivacyManager\Config as PrivacyManagerConfig;
15 use Piwik\Tracker\Db as TrackerDb;
16 use Piwik\Tracker\Db\DbException;
17 use Piwik\Tracker\Handler;
18 use Piwik\Tracker\Request;
19 use Piwik\Tracker\RequestSet;
20 use Piwik\Tracker\TrackerConfig;
21 use Piwik\Tracker\Visit;
22 use Piwik\Plugin\Manager as PluginManager;
23 use Piwik\Log\LoggerInterface;
24 /**
25 * Class used by the logging script piwik.php called by the javascript tag.
26 * Handles the visitor and their actions on the website, saves the data in the DB,
27 * saves information in the cookie, etc.
28 *
29 * We try to include as little files as possible (no dependency on 3rd party modules).
30 */
31 class Tracker
32 {
33 /**
34 * @var Db
35 */
36 private static $db = null;
37 // We use hex ID that are 16 chars in length, ie. 64 bits IDs
38 public const LENGTH_HEX_ID_STRING = 16;
39 public const LENGTH_BINARY_ID = 8;
40 public static $initTrackerMode = false;
41 private $countOfLoggedRequests = 0;
42 protected $isInstalled = null;
43 /**
44 * @var LoggerInterface
45 */
46 private $logger;
47 public function __construct()
48 {
49 $this->logger = StaticContainer::get(LoggerInterface::class);
50 }
51 public function isDebugModeEnabled()
52 {
53 return array_key_exists('PIWIK_TRACKER_DEBUG', $GLOBALS) && $GLOBALS['PIWIK_TRACKER_DEBUG'] === true;
54 }
55 public function shouldRecordStatistics()
56 {
57 $record = TrackerConfig::getConfigValue('record_statistics') != 0;
58 if (!$record) {
59 $this->logger->debug('Tracking is disabled in the config.ini.php via record_statistics=0');
60 }
61 return $record && $this->isInstalled();
62 }
63 public static function loadTrackerEnvironment()
64 {
65 \Piwik\SettingsServer::setIsTrackerApiRequest();
66 if (empty($GLOBALS['PIWIK_TRACKER_DEBUG'])) {
67 $GLOBALS['PIWIK_TRACKER_DEBUG'] = self::isDebugEnabled();
68 }
69 if (!empty($GLOBALS['PIWIK_TRACKER_DEBUG']) && !\Piwik\Common::isPhpCliMode()) {
70 \Piwik\Common::sendHeader('Content-Type: text/plain');
71 }
72 PluginManager::getInstance()->loadTrackerPlugins();
73 }
74 private function init()
75 {
76 $this->handleFatalErrors();
77 if ($this->isDebugModeEnabled()) {
78 \Piwik\ErrorHandler::registerErrorHandler();
79 \Piwik\ExceptionHandler::setUp();
80 $this->logger->debug("Debug enabled - Input parameters: {params}", ['params' => var_export($_GET + $_POST, true)]);
81 }
82 }
83 public function isInstalled()
84 {
85 if (is_null($this->isInstalled)) {
86 $this->isInstalled = \Piwik\SettingsPiwik::isMatomoInstalled();
87 }
88 return $this->isInstalled;
89 }
90 public function main(Handler $handler, RequestSet $requestSet)
91 {
92 try {
93 $this->init();
94 if ($this->isPreFlightCorsRequest()) {
95 \Piwik\Common::sendHeader('Access-Control-Allow-Methods: GET, POST');
96 \Piwik\Common::sendHeader('Access-Control-Allow-Headers: *');
97 \Piwik\Common::sendHeader('Access-Control-Allow-Origin: *');
98 \Piwik\Common::sendResponseCode(204);
99 $this->logger->debug("Tracker detected preflight CORS request. Skipping...");
100 return null;
101 }
102 $handler->init($this, $requestSet);
103 $this->track($handler, $requestSet);
104 } catch (Exception $e) {
105 $this->logger->debug("Tracker encountered an exception: {ex}", [$e]);
106 $handler->onException($this, $requestSet, $e);
107 }
108 \Piwik\Piwik::postEvent('Tracker.end');
109 $response = $handler->finish($this, $requestSet);
110 $this->disconnectDatabase();
111 return $response;
112 }
113 public function track(Handler $handler, RequestSet $requestSet)
114 {
115 if (!$this->shouldRecordStatistics()) {
116 return;
117 }
118 $requestSet->initRequestsAndTokenAuth();
119 if ($requestSet->hasRequests()) {
120 $handler->onStartTrackRequests($this, $requestSet);
121 $handler->process($this, $requestSet);
122 $handler->onAllRequestsTracked($this, $requestSet);
123 }
124 }
125 /**
126 * @param Request $request
127 * @return array
128 */
129 public function trackRequest(Request $request)
130 {
131 if ($request->isEmptyRequest()) {
132 $this->logger->debug('The request is empty');
133 } else {
134 $this->logger->debug('Current datetime: {date}', ['date' => date("Y-m-d H:i:s", $request->getCurrentTimestamp())]);
135 $visit = Visit\Factory::make();
136 $visit->setRequest($request);
137 $visit->handle();
138 }
139 // increment successfully logged request count. make sure to do this after try-catch,
140 // since an excluded visit is considered 'successfully logged'
141 ++$this->countOfLoggedRequests;
142 }
143 /**
144 * Used to initialize core Piwik components on a piwik.php request
145 * Eg. when cache is missed and we will be calling some APIs to generate cache
146 */
147 public static function initCorePiwikInTrackerMode()
148 {
149 if (\Piwik\SettingsServer::isTrackerApiRequest() && self::$initTrackerMode === false) {
150 self::$initTrackerMode = true;
151 require_once PIWIK_INCLUDE_PATH . '/core/Option.php';
152 \Piwik\Access::getInstance();
153 \Piwik\Config::getInstance();
154 try {
155 \Piwik\Db::get();
156 } catch (Exception $e) {
157 \Piwik\Db::createDatabaseObject();
158 }
159 PluginManager::getInstance()->loadCorePluginsDuringTracker();
160 }
161 }
162 public static function restoreTrackerPlugins()
163 {
164 if (\Piwik\SettingsServer::isTrackerApiRequest() && \Piwik\Tracker::$initTrackerMode) {
165 \Piwik\Plugin\Manager::getInstance()->loadTrackerPlugins();
166 }
167 }
168 public function getCountOfLoggedRequests()
169 {
170 return $this->countOfLoggedRequests;
171 }
172 public function setCountOfLoggedRequests($numLoggedRequests)
173 {
174 $this->countOfLoggedRequests = $numLoggedRequests;
175 }
176 public function hasLoggedRequests()
177 {
178 return 0 !== $this->countOfLoggedRequests;
179 }
180 public function isDatabaseConnected()
181 {
182 return !is_null(self::$db);
183 }
184 public static function getDatabase()
185 {
186 if (is_null(self::$db)) {
187 try {
188 self::$db = TrackerDb::connectPiwikTrackerDb();
189 } catch (Exception $e) {
190 $code = $e->getCode();
191 // Note: PDOException might return a string as code, but we can't use this for DbException
192 throw new DbException($e->getMessage(), is_int($code) ? $code : 0);
193 }
194 }
195 return self::$db;
196 }
197 protected function disconnectDatabase()
198 {
199 if ($this->isDatabaseConnected()) {
200 // note: I think we do this only for the tests
201 self::$db->disconnect();
202 self::$db = null;
203 }
204 }
205 // for tests
206 public static function disconnectCachedDbConnection()
207 {
208 // code redundancy w/ above is on purpose; above disconnectDatabase depends on method that can potentially be overridden
209 if (!is_null(self::$db)) {
210 self::$db->disconnect();
211 self::$db = null;
212 }
213 }
214 public static function setTestEnvironment($args = null, $requestMethod = null)
215 {
216 if (is_null($args)) {
217 $requests = new Requests();
218 $args = $requests->getRequestsArrayFromBulkRequest($requests->getRawBulkRequest());
219 $args = $_GET + $args;
220 }
221 if (is_null($requestMethod) && array_key_exists('REQUEST_METHOD', $_SERVER)) {
222 $requestMethod = $_SERVER['REQUEST_METHOD'];
223 } elseif (is_null($requestMethod)) {
224 $requestMethod = 'GET';
225 }
226 // Do not run scheduled tasks during tests
227 if (!defined('DEBUG_FORCE_SCHEDULED_TASKS')) {
228 TrackerConfig::setConfigValue('scheduled_tasks_min_interval', 0);
229 }
230 // if nothing found in _GET/_POST and we're doing a POST, assume bulk request. in which case,
231 // we have to bypass authentication
232 if (empty($args) && $requestMethod == 'POST') {
233 TrackerConfig::setConfigValue('tracking_requests_require_authentication', 0);
234 }
235 // Tests can force the use of 3rd party cookie for ID visitor
236 if (\Piwik\Common::getRequestVar('forceEnableFingerprintingAcrossWebsites', false, null, $args) == 1) {
237 TrackerConfig::setConfigValue('enable_fingerprinting_across_websites', 1);
238 }
239 // Tests can simulate the tracker API maintenance mode
240 if (\Piwik\Common::getRequestVar('forceEnableTrackerMaintenanceMode', false, null, $args) == 1) {
241 TrackerConfig::setConfigValue('record_statistics', 0);
242 }
243 // Tests can force the use of 3rd party cookie for ID visitor
244 if (\Piwik\Common::getRequestVar('forceUseThirdPartyCookie', false, null, $args) == 1) {
245 TrackerConfig::setConfigValue('use_third_party_id_cookie', 1);
246 }
247 // Tests using window_look_back_for_visitor
248 if (\Piwik\Common::getRequestVar('forceLargeWindowLookBackForVisitor', false, null, $args) == 1 || strpos(json_encode($args, true), '"forceLargeWindowLookBackForVisitor":"1"') !== false) {
249 TrackerConfig::setConfigValue('window_look_back_for_visitor', 2678400);
250 }
251 // Tests can force the enabling of IP anonymization
252 if (\Piwik\Common::getRequestVar('forceIpAnonymization', false, null, $args) == 1) {
253 self::getDatabase();
254 // make sure db is initialized
255 $privacyConfig = new PrivacyManagerConfig();
256 $privacyConfig->ipAddressMaskLength = 2;
257 \Piwik\Plugins\PrivacyManager\IPAnonymizer::activate();
258 \Piwik\Tracker\Cache::deleteTrackerCache();
259 \Piwik\Filesystem::clearPhpCaches();
260 }
261 }
262 protected function loadTrackerPlugins()
263 {
264 try {
265 $pluginManager = PluginManager::getInstance();
266 $pluginsTracker = $pluginManager->loadTrackerPlugins();
267 $this->logger->debug("Loading plugins: { {plugins} }", ['plugins' => implode(", ", $pluginsTracker)]);
268 } catch (Exception $e) {
269 $this->logger->error('Error loading tracker plugins: {exception}', ['exception' => $e]);
270 }
271 }
272 private function handleFatalErrors()
273 {
274 register_shutdown_function(function () {
275 // TODO: add a log here
276 $lastError = error_get_last();
277 if (!empty($lastError) && $lastError['type'] == E_ERROR) {
278 \Piwik\Common::sendResponseCode(500);
279 }
280 });
281 }
282 private static function isDebugEnabled()
283 {
284 try {
285 $debug = (bool) TrackerConfig::getConfigValue('debug');
286 if ($debug) {
287 return true;
288 }
289 $debugOnDemand = (bool) TrackerConfig::getConfigValue('debug_on_demand');
290 if ($debugOnDemand) {
291 return (bool) \Piwik\Common::getRequestVar('debug', false);
292 }
293 } catch (Exception $e) {
294 }
295 return false;
296 }
297 public function isPreFlightCorsRequest() : bool
298 {
299 if (isset($_SERVER['REQUEST_METHOD']) && strtoupper($_SERVER['REQUEST_METHOD']) === 'OPTIONS') {
300 return !empty($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']) || !empty($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']);
301 }
302 return false;
303 }
304 }
305