PluginProbe ʕ •ᴥ•ʔ
Matomo Analytics – Powerful, Privacy-First Insights for WordPress / 5.6.0
Matomo Analytics – Powerful, Privacy-First Insights for WordPress v5.6.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 7 months ago Access 7 months ago Application 1 year ago Archive 7 months ago ArchiveProcessor 7 months ago Archiver 2 years ago AssetManager 7 months ago Auth 7 months ago Category 7 months ago Changes 7 months ago CliMulti 1 year ago Columns 7 months ago Concurrency 7 months ago Config 7 months ago Container 7 months ago CronArchive 7 months ago DataAccess 7 months ago DataFiles 2 years ago DataTable 7 months ago Db 7 months ago DeviceDetector 1 year ago Email 2 years ago Exception 1 year ago Http 1 year ago Intl 7 months ago Log 2 years ago Mail 1 year ago Measurable 7 months ago Menu 7 months ago Metrics 7 months ago Notification 7 months ago Period 7 months ago Plugin 7 months ago Policy 7 months ago ProfessionalServices 1 year ago Report 1 year ago ReportRenderer 1 year ago Request 7 months ago Scheduler 7 months ago Segment 7 months ago Session 7 months ago Settings 7 months ago Tracker 7 months ago Translation 1 year ago Twig 1 year ago UpdateCheck 7 months ago Updater 7 months ago Updates 7 months ago Validators 1 year ago View 7 months ago ViewDataTable 7 months ago Visualization 1 year ago Widget 1 year ago .htaccess 2 years ago Access.php 7 months ago Archive.php 7 months ago ArchiveProcessor.php 7 months ago AssetManager.php 1 year ago Auth.php 7 months ago AuthResult.php 7 months ago BaseFactory.php 2 years ago Cache.php 2 years ago CacheId.php 1 year ago CliMulti.php 7 months ago Common.php 7 months ago Config.php 1 year ago Console.php 1 year ago Context.php 2 years ago Cookie.php 1 year ago CronArchive.php 7 months ago DI.php 1 year ago DataArray.php 1 year ago DataTable.php 7 months ago Date.php 7 months ago Db.php 1 year ago DbHelper.php 7 months ago Development.php 1 year ago ErrorHandler.php 7 months ago EventDispatcher.php 1 year ago ExceptionHandler.php 7 months ago FileIntegrity.php 1 year ago Filechecks.php 1 year ago Filesystem.php 1 year ago FrontController.php 7 months ago Http.php 7 months ago IP.php 1 year ago Log.php 7 months ago LogDeleter.php 1 year ago Mail.php 1 year ago Metrics.php 7 months ago NoAccessException.php 2 years ago Nonce.php 7 months ago Notification.php 7 months ago NumberFormatter.php 1 year ago Option.php 1 year ago Period.php 1 year ago Piwik.php 7 months ago Plugin.php 1 year ago Process.php 1 year ago Profiler.php 7 months ago ProxyHeaders.php 2 years ago ProxyHttp.php 1 year ago QuickForm2.php 1 year ago RankingQuery.php 7 months ago ReportRenderer.php 1 year ago Request.php 1 year ago Segment.php 7 months ago Sequence.php 7 months ago Session.php 1 year ago SettingsPiwik.php 1 year ago SettingsServer.php 1 year ago Singleton.php 2 years ago Site.php 7 months ago SiteContentDetector.php 1 year ago SupportedBrowser.php 2 years ago TCPDF.php 1 year ago Theme.php 1 year ago Timer.php 2 years ago Tracker.php 1 year ago Twig.php 7 months ago Unzip.php 1 year ago UpdateCheck.php 1 year ago Updater.php 1 year ago UpdaterErrorException.php 2 years ago Updates.php 1 year ago Url.php 7 months ago UrlHelper.php 1 year ago Version.php 7 months ago View.php 7 months ago bootstrap.php 1 year ago dispatch.php 2 years ago testMinimumPhpVersion.php 7 months ago
Tracker.php
295 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 void
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 private function handleFatalErrors()
263 {
264 register_shutdown_function(function () {
265 // TODO: add a log here
266 $lastError = error_get_last();
267 if (!empty($lastError) && $lastError['type'] == \E_ERROR) {
268 \Piwik\Common::sendResponseCode(500);
269 }
270 });
271 }
272 private static function isDebugEnabled()
273 {
274 try {
275 $debug = (bool) TrackerConfig::getConfigValue('debug');
276 if ($debug) {
277 return \true;
278 }
279 $debugOnDemand = (bool) TrackerConfig::getConfigValue('debug_on_demand');
280 if ($debugOnDemand) {
281 return (bool) \Piwik\Common::getRequestVar('debug', \false);
282 }
283 } catch (Exception $e) {
284 }
285 return \false;
286 }
287 public function isPreFlightCorsRequest() : bool
288 {
289 if (isset($_SERVER['REQUEST_METHOD']) && strtoupper($_SERVER['REQUEST_METHOD']) === 'OPTIONS') {
290 return !empty($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']) || !empty($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']);
291 }
292 return \false;
293 }
294 }
295