1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
|
<?php
/**
* Matomo - free/libre analytics platform
*
* @link https://matomo.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*
*/
namespace Piwik\Tracker;
use Exception;
use Piwik\Common;
use Piwik\Config;
use Piwik\Container\StaticContainer;
use Piwik\Cookie;
use Piwik\Exception\InvalidRequestParameterException;
use Piwik\Exception\UnexpectedWebsiteFoundException;
use Piwik\IP;
use Matomo\Network\IPUtils;
use Piwik\Piwik;
use Piwik\Plugins\PrivacyManager\PrivacyManager;
use Piwik\Plugins\UsersManager\UsersManager;
use Piwik\ProxyHttp;
use Piwik\Segment\SegmentExpression;
use Piwik\Tracker;
use Piwik\Cache as PiwikCache;
/**
* The Request object holding the http parameters for this tracking request. Use getParam() to fetch a named parameter.
*
*/
class Request
{
private $cdtCache;
private $idSiteCache;
private $paramsCache = array();
/**
* @var array
*/
protected $params;
protected $rawParams;
protected $isAuthenticated = null;
private $isEmptyRequest = false;
protected $tokenAuth;
/**
* Stores plugin specific tracking request metadata. RequestProcessors can store
* whatever they want in this array, and other RequestProcessors can modify these
* values to change tracker behavior.
*
* @var string[][]
*/
private $requestMetadata = array();
const UNKNOWN_RESOLUTION = 'unknown';
private $customTimestampDoesNotRequireTokenauthWhenNewerThan;
/**
* @param $params
* @param bool|string $tokenAuth
*/
public function __construct($params, $tokenAuth = false)
{
if (!is_array($params)) {
$params = array();
}
$this->params = $params;
$this->rawParams = $params;
$this->tokenAuth = $tokenAuth;
$this->timestamp = time();
$this->isEmptyRequest = empty($params);
$this->customTimestampDoesNotRequireTokenauthWhenNewerThan = (int) TrackerConfig::getConfigValue('tracking_requests_require_authentication_when_custom_timestamp_newer_than');
// When the 'url' and referrer url parameter are not given, we might be in the 'Simple Image Tracker' mode.
// The URL can default to the Referrer, 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'])
&& array_key_exists('HTTP_REFERER', $_SERVER)
) {
$url = $_SERVER['HTTP_REFERER'];
if (!empty($url)) {
$this->params['url'] = $url;
}
}
// check for 4byte utf8 characters in all tracking params and replace them with � if not support by database
$this->params = $this->replaceUnsupportedUtf8Chars($this->params);
}
protected function replaceUnsupportedUtf8Chars($value, $key=false)
{
$dbSettings = new \Piwik\Db\Settings();
$charset = $dbSettings->getUsedCharset();
if ('utf8mb4' === $charset) {
return $value; // no need to replace anything if utf8mb4 is supported
}
if (is_string($value) && preg_match('/[\x{10000}-\x{10FFFF}]/u', $value)) {
Common::printDebug("Unsupported character detected in $key. Replacing with \xEF\xBF\xBD");
return preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
}
if (is_array($value)) {
array_walk_recursive ($value, function(&$value, $key){
$value = $this->replaceUnsupportedUtf8Chars($value, $key);
});
}
return $value;
}
/**
* Get the params that were originally passed to the instance. These params do not contain any params that were added
* within this object.
* @return array
*/
public function getRawParams()
{
return $this->rawParams;
}
public function getTokenAuth()
{
return $this->tokenAuth;
}
/**
* @return bool
*/
public function isAuthenticated()
{
if (is_null($this->isAuthenticated)) {
$this->authenticateTrackingApi($this->tokenAuth);
}
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($tokenAuth)
{
$shouldAuthenticate = TrackerConfig::getConfigValue('tracking_requests_require_authentication');
if ($shouldAuthenticate) {
try {
$idSite = $this->getIdSite();
} catch (Exception $e) {
Common::printDebug("failed to authenticate: invalid idSite");
$this->isAuthenticated = false;
return;
}
if (empty($tokenAuth)) {
$tokenAuth = Common::getRequestVar('token_auth', false, 'string', $this->params);
}
$cache = PiwikCache::getTransientCache();
$cacheKey = 'tracker_request_authentication_' . $idSite . '_' . $tokenAuth;
if ($cache->contains($cacheKey)) {
Common::printDebug("token_auth is authenticated in cache!");
$this->isAuthenticated = $cache->fetch($cacheKey);
return;
}
try {
$this->isAuthenticated = self::authenticateSuperUserOrAdminOrWrite($tokenAuth, $idSite);
$cache->save($cacheKey, $this->isAuthenticated);
} catch (Exception $e) {
Common::printDebug("could not authenticate, caught exception: " . $e->getMessage());
$this->isAuthenticated = false;
}
if ($this->isAuthenticated) {
Common::printDebug("token_auth is authenticated!");
} else {
StaticContainer::get('Piwik\Tracker\Failures')->logFailure(Failures::FAILURE_ID_NOT_AUTHENTICATED, $this);
}
} else {
$this->isAuthenticated = true;
Common::printDebug("token_auth authentication not required");
}
}
public static function authenticateSuperUserOrAdminOrWrite($tokenAuth, $idSite)
{
if (empty($tokenAuth)) {
return false;
}
// Now checking the list of admin token_auth cached in the Tracker config file
if (!empty($idSite) && $idSite > 0) {
$website = Cache::getCacheWebsiteAttributes($idSite);
$userModel = new \Piwik\Plugins\UsersManager\Model();
$tokenAuthHashed = $userModel->hashTokenAuth($tokenAuth);
$hashedToken = UsersManager::hashTrackingToken((string) $tokenAuthHashed, $idSite);
if (array_key_exists('tracking_token_auth', $website)
&& in_array($hashedToken, $website['tracking_token_auth'], true)) {
return true;
}
}
Piwik::postEvent('Request.initAuthenticationObject');
/** @var \Piwik\Auth $auth */
$auth = StaticContainer::get('Piwik\Auth');
$auth->setTokenAuth($tokenAuth);
$auth->setLogin(null);
$auth->setPassword(null);
$auth->setPasswordHash(null);
$access = $auth->authenticate();
if (!empty($access) && $access->hasSuperUserAccess()) {
return true;
}
Common::printDebug("WARNING! token_auth = $tokenAuth is not valid, Super User / Admin / Write was NOT authenticated");
/**
* @ignore
* @internal
*/
Piwik::postEvent('Tracker.Request.authenticate.failed');
return false;
}
public function isRequestExcluded()
{
$config = Config::getInstance();
$tracker = $config->Tracker;
if (!empty($tracker['exclude_requests'])) {
$excludedRequests = explode(',', $tracker['exclude_requests']);
$pattern = '/^(.+?)('.SegmentExpression::MATCH_EQUAL.'|'
.SegmentExpression::MATCH_NOT_EQUAL.'|'
.SegmentExpression::MATCH_CONTAINS.'|'
.SegmentExpression::MATCH_DOES_NOT_CONTAIN.'|'
.preg_quote(SegmentExpression::MATCH_STARTS_WITH).'|'
.preg_quote(SegmentExpression::MATCH_ENDS_WITH)
.'){1}(.*)/';
foreach ($excludedRequests as $excludedRequest) {
$match = preg_match($pattern, $excludedRequest, $matches);
if (!empty($match)) {
$leftMember = $matches[1];
$operation = $matches[2];
if (!isset($matches[3])) {
$valueRightMember = '';
} else {
$valueRightMember = urldecode($matches[3]);
}
$actual = Common::getRequestVar($leftMember, '', 'string', $this->params);
$actual = Common::mb_strtolower($actual);
$valueRightMember = Common::mb_strtolower($valueRightMember);
switch ($operation) {
case SegmentExpression::MATCH_EQUAL:
if ($actual === $valueRightMember) {
return true;
}
break;
case SegmentExpression::MATCH_NOT_EQUAL:
if ($actual !== $valueRightMember) {
return true;
}
break;
case SegmentExpression::MATCH_CONTAINS:
if (stripos($actual, $valueRightMember) !== false) {
return true;
}
break;
case SegmentExpression::MATCH_DOES_NOT_CONTAIN:
if (stripos($actual, $valueRightMember) === false) {
return true;
}
break;
case SegmentExpression::MATCH_STARTS_WITH:
if (stripos($actual, $valueRightMember) === 0) {
return true;
}
break;
case SegmentExpression::MATCH_ENDS_WITH:
if (Common::stringEndsWith($actual, $valueRightMember)) {
return true;
}
break;
}
}
}
}
return false;
}
/**
* Returns the language the visitor is viewing.
*
* @return string browser language code, eg. "en-gb,en;q=0.5"
*/
public function getBrowserLanguage()
{
return Common::getRequestVar('lang', Common::getBrowserLanguage(), 'string', $this->params);
}
/**
* @return string
*/
public function getLocalTime()
{
$localTimes = array(
'h' => (string)Common::getRequestVar('h', $this->getCurrentDate("H"), 'int', $this->params),
'i' => (string)Common::getRequestVar('m', $this->getCurrentDate("i"), 'int', $this->params),
's' => (string)Common::getRequestVar('s', $this->getCurrentDate("s"), 'int', $this->params)
);
if($localTimes['h'] < 0 || $localTimes['h'] > 23) {
$localTimes['h'] = 0;
}
if($localTimes['i'] < 0 || $localTimes['i'] > 59) {
$localTimes['i'] = 0;
}
if($localTimes['s'] < 0 || $localTimes['s'] > 59) {
$localTimes['s'] = 0;
}
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 Common::getRequestVar('revenue', $defaultGoalRevenue, 'float', $this->params);
}
public function getParam($name)
{
static $supportedParams = array(
// Name => array( defaultValue, type )
'_refts' => array(0, 'int'),
'_ref' => array('', 'string'),
'_rcn' => array('', 'string'),
'_rck' => array('', 'string'),
'url' => array('', 'string'),
'urlref' => array('', 'string'),
'res' => array(self::UNKNOWN_RESOLUTION, 'string'),
'idgoal' => array(-1, 'int'),
'ping' => array(0, 'int'),
// other
'bots' => array(0, 'int'),
'dp' => array(0, 'int'),
'rec' => array(0, 'int'),
'new_visit' => array(0, 'int'),
// Ecommerce
'ec_id' => array('', 'string'),
'ec_st' => array(false, 'float'),
'ec_tx' => array(false, 'float'),
'ec_sh' => array(false, 'float'),
'ec_dt' => array(false, 'float'),
'ec_items' => array('', 'json'),
// ecommerce product/category view
'_pkc' => array('', 'string'),
'_pks' => array('', 'string'),
'_pkn' => array('', 'string'),
'_pkp' => array(false, 'float'),
// Events
'e_c' => array('', 'string'),
'e_a' => array('', 'string'),
'e_n' => array('', 'string'),
'e_v' => array(false, 'float'),
// some visitor attributes can be overwritten
'cip' => array('', 'string'),
'cdt' => array('', 'string'),
'cdo' => array('', 'int'),
'cid' => array('', 'string'),
'uid' => array('', 'string'),
// Actions / pages
'cs' => array('', 'string'),
'download' => array('', 'string'),
'link' => array('', 'string'),
'action_name' => array('', 'string'),
'search' => array('', 'string'),
'search_cat' => array('', 'string'),
'pv_id' => array('', 'string'),
'search_count' => array(-1, 'int'),
'pf_net' => array(-1, 'int'),
'pf_srv' => array(-1, 'int'),
'pf_tfr' => array(-1, 'int'),
'pf_dm1' => array(-1, 'int'),
'pf_dm2' => array(-1, 'int'),
'pf_onl' => array(-1, 'int'),
// Content
'c_p' => array('', 'string'),
'c_n' => array('', 'string'),
'c_t' => array('', 'string'),
'c_i' => array('', 'string'),
// custom action request. Recommended when a plugin declares its own action handler/requestprocessor
// refs https://github.com/matomo-org/matomo/issues/16569
'ca' => array(0, 'int'),
);
if (isset($this->paramsCache[$name])) {
return $this->paramsCache[$name];
}
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];
if ($this->hasParam($name)) {
$this->paramsCache[$name] = $this->replaceUnsupportedUtf8Chars(Common::getRequestVar($name, $paramDefaultValue, $paramType, $this->params), $name);
} else {
$this->paramsCache[$name] = $paramDefaultValue;
}
return $this->paramsCache[$name];
}
public function setParam($name, $value)
{
$this->params[$name] = $value;
unset($this->paramsCache[$name]);
if ($name === 'cdt') {
$this->cdtCache = null;
}
}
public function hasParam($name)
{
return isset($this->params[$name]);
}
public function getParams()
{
return $this->params;
}
public function getCurrentTimestamp()
{
if (!isset($this->cdtCache)) {
$this->cdtCache = $this->getCustomTimestamp();
}
if (!empty($this->cdtCache)) {
return $this->cdtCache;
}
return $this->timestamp;
}
public function setCurrentTimestamp($timestamp)
{
$this->timestamp = $timestamp;
}
protected function getCustomTimestamp()
{
if (!$this->hasParam('cdt') && !$this->hasParam('cdo')) {
return false;
}
$cdt = $this->getParam('cdt');
$cdo = $this->getParam('cdo');
if (empty($cdt) && $cdo) {
$cdt = $this->timestamp;
}
if (empty($cdt)) {
return false;
}
if (!is_numeric($cdt)) {
$cdt = strtotime($cdt);
}
if (!empty($cdo)) {
$cdt = $cdt - abs($cdo);
}
if (!$this->isTimestampValid($cdt, $this->timestamp)) {
Common::printDebug(sprintf("Datetime %s is not valid", date("Y-m-d H:i:m", $cdt)));
return false;
}
// If timestamp in the past, token_auth is required
$timeFromNow = $this->timestamp - $cdt;
$isTimestampRecent = $timeFromNow < $this->customTimestampDoesNotRequireTokenauthWhenNewerThan;
if (!$isTimestampRecent) {
if (!$this->isAuthenticated()) {
$message = sprintf("Custom timestamp is %s seconds old, requires &token_auth...", $timeFromNow);
Common::printDebug($message);
Common::printDebug("WARN: Tracker API 'cdt' was used with invalid token_auth");
throw new InvalidRequestParameterException($message);
}
}
$cache = Tracker\Cache::getCacheGeneral();
if (!empty($cache['delete_logs_enable']) && !empty($cache['delete_logs_older_than'])) {
$scheduleInterval = $cache['delete_logs_schedule_lowest_interval'];
$maxLogAge = $cache['delete_logs_older_than'];
$logEntryCutoff = time() - (($maxLogAge + $scheduleInterval) * 60*60*24);
if ($cdt < $logEntryCutoff) {
$message = "Custom timestamp is older than the configured 'deleted old raw data' value of $maxLogAge days";
Common::printDebug($message);
throw new InvalidRequestParameterException($message);
}
}
return (int) $cdt;
}
/**
* Returns true if the timestamp is valid ie. timestamp is sometime in the last 10 years and is not in the future.
*
* @param $time int Timestamp to test
* @param $now int Current timestamp
* @return bool
*/
protected function isTimestampValid($time, $now = null)
{
if (empty($now)) {
$now = $this->getCurrentTimestamp();
}
return $time <= $now
&& $time > $now - 20 * 365 * 86400;
}
/**
* @internal
* @ignore
*/
public function getIdSiteUnverified()
{
$idSite = Common::getRequestVar('idsite', 0, 'int', $this->params);
/**
* Triggered when obtaining the ID of the site we are tracking a visit for.
*
* This event can be used to change the site ID so data is tracked for a different
* website.
*
* @param int &$idSite Initialized to the value of the **idsite** query parameter. If a
* subscriber sets this variable, the value it uses must be greater
* than 0.
* @param array $params The entire array of request parameters in the current tracking
* request.
*/
Piwik::postEvent('Tracker.Request.getIdSite', array(&$idSite, $this->params));
return $idSite;
}
public function getIdSite()
{
if (isset($this->idSiteCache)) {
return $this->idSiteCache;
}
$idSite = $this->getIdSiteUnverified();
if ($idSite <= 0) {
throw new UnexpectedWebsiteFoundException('Invalid idSite: \'' . $idSite . '\'');
}
// check site actually exists, should throw UnexpectedWebsiteFoundException directly
$site = Cache::getCacheWebsiteAttributes($idSite);
if (empty($site)) {
// fallback just in case exception wasn't thrown...
throw new UnexpectedWebsiteFoundException('Invalid idSite: \'' . $idSite . '\'');
}
$this->idSiteCache = $idSite;
return $idSite;
}
public function getUserAgent()
{
$default = false;
if (array_key_exists('HTTP_USER_AGENT', $_SERVER)) {
$default = $_SERVER['HTTP_USER_AGENT'];
}
return Common::getRequestVar('ua', $default, 'string', $this->params);
}
public function shouldUseThirdPartyCookie()
{
return (bool)Config::getInstance()->Tracker['use_third_party_id_cookie'];
}
public function getThirdPartyCookieVisitorId()
{
$cookie = $this->makeThirdPartyCookieUID();
$idVisitor = $cookie->get(0);
if ($idVisitor !== false
&& strlen($idVisitor) == Tracker::LENGTH_HEX_ID_STRING
) {
return $idVisitor;
}
return null;
}
/**
* Update the cookie information.
*/
public function setThirdPartyCookie($idVisitor)
{
if (!$this->shouldUseThirdPartyCookie()) {
return;
}
if (\Piwik\Tracker\IgnoreCookie::isIgnoreCookieFound()) {
return;
}
$cookie = $this->makeThirdPartyCookieUID();
$idVisitor = bin2hex($idVisitor);
$cookie->set(0, $idVisitor);
if (ProxyHttp::isHttps()) {
$cookie->setSecure(true);
$cookie->save('None');
} else {
$cookie->save('Lax');
}
Common::printDebug(sprintf("We set the visitor ID to %s in the 3rd party cookie...", $idVisitor));
}
protected function makeThirdPartyCookieUID()
{
$cookie = new Cookie(
$this->getCookieName(),
$this->getCookieExpire(),
$this->getCookiePath());
$domain = $this->getCookieDomain();
if (!empty($domain)) {
$cookie->setDomain($domain);
}
Common::printDebug($cookie);
return $cookie;
}
protected function getCookieName()
{
return TrackerConfig::getConfigValue('cookie_name');
}
protected function getCookieExpire()
{
return $this->getCurrentTimestamp() + TrackerConfig::getConfigValue('cookie_expire');
}
protected function getCookiePath()
{
return TrackerConfig::getConfigValue('cookie_path');
}
protected function getCookieDomain()
{
return TrackerConfig::getConfigValue('cookie_domain');
}
/**
* Returns the ID from the request in this order:
* return from a given User ID,
* or from a Tracking API forced Visitor ID,
* or from a Visitor ID from 3rd party (optional) cookies,
* or from a given Visitor Id from 1st party?
*
* @throws Exception
*/
public function getVisitorId()
{
$found = false;
if (TrackerConfig::getConfigValue('enable_userid_overwrites_visitorid')) {
// If User ID is set it takes precedence
$userId = $this->getForcedUserId();
if ($userId) {
$userIdHashed = $this->getUserIdHashed($userId);
$idVisitor = $this->truncateIdAsVisitorId($userIdHashed);
Common::printDebug("Request will be recorded for this user_id = " . $userId . " (idvisitor = $idVisitor)");
$found = true;
}
}
// Was a Visitor ID "forced" (@see Tracking API setVisitorId()) for this request?
if (!$found) {
$idVisitor = $this->getForcedVisitorId();
if (!empty($idVisitor)) {
if (strlen($idVisitor) != Tracker::LENGTH_HEX_ID_STRING) {
throw new InvalidRequestParameterException("Visitor ID (cid) $idVisitor must be " . Tracker::LENGTH_HEX_ID_STRING . " characters long");
}
Common::printDebug("Request will be recorded for this idvisitor = " . $idVisitor);
$found = true;
}
}
$privacyConfig = new \Piwik\Plugins\PrivacyManager\Config();
// Only check for cookie values if cookieless tracking is NOT forced
if (!$privacyConfig->forceCookielessTracking) {
// - If set to use 3rd party cookies for Visit ID, read the cookie
if (!$found) {
$useThirdPartyCookie = $this->shouldUseThirdPartyCookie();
if ($useThirdPartyCookie) {
$idVisitor = $this->getThirdPartyCookieVisitorId();
if (!empty($idVisitor)) {
$found = true;
}
}
}
// If a third party cookie was not found, we default to the first party cookie
if (!$found) {
$idVisitor = Common::getRequestVar('_id', '', 'string', $this->params);
$found = strlen($idVisitor) >= Tracker::LENGTH_HEX_ID_STRING;
}
}
if ($found) {
return $this->getVisitorIdAsBinary($idVisitor);
}
return false;
}
/**
* When creating a third party cookie, we want to ensure that the original value set in this 3rd party cookie
* sticks and is not overwritten later.
*/
public function getVisitorIdForThirdPartyCookie()
{
$found = false;
// For 3rd party cookies, priority is on re-using the existing 3rd party cookie value
if (!$found) {
$useThirdPartyCookie = $this->shouldUseThirdPartyCookie();
if ($useThirdPartyCookie) {
$idVisitor = $this->getThirdPartyCookieVisitorId();
if(!empty($idVisitor)) {
$found = true;
}
}
}
// If a third party cookie was not found, we default to the first party cookie
if (!$found) {
$idVisitor = Common::getRequestVar('_id', '', 'string', $this->params);
$found = strlen($idVisitor) >= Tracker::LENGTH_HEX_ID_STRING;
}
if ($found) {
return $this->getVisitorIdAsBinary($idVisitor);
}
return false;
}
public function getIp()
{
return IPUtils::stringToBinaryIP($this->getIpString());
}
public function getForcedUserId()
{
$userId = $this->getParam('uid');
if (strlen($userId) > 0) {
return $userId;
}
return false;
}
public function getForcedVisitorId()
{
return $this->getParam('cid');
}
public function getPlugins()
{
static $pluginsInOrder = array('fla', 'java', 'qt', 'realp', 'pdf', 'wma', 'ag', 'cookie');
$plugins = array();
foreach ($pluginsInOrder as $param) {
$plugins[] = Common::getRequestVar($param, 0, 'int', $this->params);
}
return $plugins;
}
public function isEmptyRequest()
{
return $this->isEmptyRequest;
}
/**
* @param $idVisitor
* @return string
*/
private function truncateIdAsVisitorId($idVisitor)
{
return substr($idVisitor, 0, Tracker::LENGTH_HEX_ID_STRING);
}
/**
* Matches implementation of MatomoTracker::getUserIdHashed
*
* @param $userId
* @return string
*/
public function getUserIdHashed($userId)
{
return substr(sha1($userId), 0, 16);
}
/**
* @return mixed|string
* @throws Exception
*/
public function getIpString()
{
$cip = $this->getParam('cip');
if (empty($cip)) {
return IP::getIpFromHeader();
}
if (!$this->isAuthenticated()) {
Common::printDebug("WARN: Tracker API 'cip' was used with invalid token_auth");
throw new InvalidRequestParameterException("Tracker API 'cip' was used, requires valid token_auth");
}
return $cip;
}
/**
* Set a request metadata value.
*
* @param string $pluginName eg, `'Actions'`, `'Goals'`, `'YourPlugin'`
* @param string $key
* @param mixed $value
*/
public function setMetadata($pluginName, $key, $value)
{
$this->requestMetadata[$pluginName][$key] = $value;
}
/**
* Get a request metadata value. Returns `null` if none exists.
*
* @param string $pluginName eg, `'Actions'`, `'Goals'`, `'YourPlugin'`
* @param string $key
* @return mixed
*/
public function getMetadata($pluginName, $key)
{
return isset($this->requestMetadata[$pluginName][$key]) ? $this->requestMetadata[$pluginName][$key] : null;
}
/**
* @param $idVisitor
* @return bool|string
*/
private function getVisitorIdAsBinary($idVisitor)
{
$truncated = $this->truncateIdAsVisitorId($idVisitor);
$binVisitorId = @Common::hex2bin($truncated);
if (!empty($binVisitorId)) {
return $binVisitorId;
}
return false;
}
}
|