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
|
<?php
use Piwik\Core\Config;
use Piwik\Core\Piwik_Common;
/**
* 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($params, $tokenAuth = false)
{
if(!is_array($params)) {
$params = array();
}
$this->params = $params;
$this->timestamp = time();
$this->enforcedIp = false;
// 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'])
) {
$url = @$_SERVER['HTTP_REFERER'];
if(!empty($url)) {
$this->params['url'] = $url;
}
}
$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 = Config::getInstance()->Tracker['tracking_requests_require_authentication'];
if ($shouldAuthenticate) {
$tokenAuth = $tokenAuthFromBulkRequest || Piwik_Common::getRequestVar('token_auth', false, 'string', $this->params);
try {
$idSite = $this->getIdSite();
$this->isAuthenticated = $this->authenticateSuperUserOrAdmin($tokenAuth, $idSite);
} catch(Exception $e) {
$this->isAuthenticated = false;
}
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 = Config::getInstance()->superuser['login'];
$superUserPassword = 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);
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()
{
$idSite = Piwik_Common::getRequestVar('idsite', 0, 'int', $this->params);
Piwik_PostEvent('Tracker.setRequest.idSite', array(&$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)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 Config::getInstance()->Tracker['cookie_name'];
}
protected function getCookieExpire()
{
return $this->getCurrentTimestamp() + Config::getInstance()->Tracker['cookie_expire'];
}
protected function getCookiePath()
{
return 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 getIp()
{
if (!empty($this->enforcedIp)) {
$ipString = $this->enforcedIp;
} else {
$ipString = Piwik_IP::getIpFromHeader();
}
$ip = Piwik_IP::P2N($ipString);
return $ip;
}
public function setForceIp($ip)
{
$this->enforcedIp = $ip;
}
public function setForceDateTime($dateTime)
{
if (!is_numeric($dateTime)) {
$dateTime = strtotime($dateTime);
}
$this->timestamp = $dateTime;
}
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);
}
}
|