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
|
<?php
/**
* Piwik - Open source web analytics
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*
*/
namespace Piwik\Tracker;
use Piwik\Common;
use Piwik\Config;
use Piwik\IP;
use Piwik\Piwik;
use Piwik\Plugin\VisitDimension;
use Piwik\Tracker;
/**
* Class used to handle a Visit.
* A visit is either NEW or KNOWN.
* - If a visit is NEW then we process the visitor information (settings, referrers, etc.) and save
* a new line in the log_visit table.
* - If a visit is KNOWN then we update the visit row in the log_visit table, updating the number of pages
* views, time spent, etc.
*
* Whether a visit is NEW or KNOWN we also save the action in the DB.
* One request to the piwik.php script is associated to one action.
*
*/
class Visit implements VisitInterface
{
const UNKNOWN_CODE = 'xx';
/**
* @var GoalManager
*/
protected $goalManager;
/**
* @var Request
*/
protected $request;
protected $visitorInfo = array();
/**
* @var Settings
*/
protected $userSettings;
protected $visitorCustomVariables = array();
/**
* @param Request $request
*/
public function setRequest(Request $request)
{
$this->request = $request;
}
/**
* Main algorithm to handle the visit.
*
* Once we have the visitor information, we have to determine if the visit is a new or a known visit.
*
* 1) When the last action was done more than 30min ago,
* or if the visitor is new, then this is a new visit.
*
* 2) If the last action is less than 30min ago, then the same visit is going on.
* Because the visit goes on, we can get the time spent during the last action.
*
* NB:
* - In the case of a new visit, then the time spent
* during the last action of the previous visit is unknown.
*
* - In the case of a new visit but with a known visitor,
* we can set the 'returning visitor' flag.
*
* In all the cases we set a cookie to the visitor with the new information.
*/
public function handle()
{
// the IP is needed by isExcluded() and GoalManager->recordGoals()
$ip = $this->request->getIp();
$this->visitorInfo['location_ip'] = $ip;
$excluded = new VisitExcluded($this->request, $ip);
if ($excluded->isExcluded()) {
return;
}
/**
* Triggered after visits are tested for exclusion so plugins can modify the IP address
* persisted with a visit.
*
* This event is primarily used by the **PrivacyManager** plugin to anonymize IP addresses.
*
* @param string &$ip The visitor's IP address.
*/
Piwik::postEvent('Tracker.setVisitorIp', array(&$this->visitorInfo['location_ip']));
$this->visitorCustomVariables = $this->request->getCustomVariables($scope = 'visit');
if (!empty($this->visitorCustomVariables)) {
Common::printDebug("Visit level Custom Variables: ");
Common::printDebug($this->visitorCustomVariables);
}
$this->goalManager = new GoalManager($this->request);
$visitIsConverted = false;
$action = null;
$requestIsManualGoalConversion = ($this->goalManager->idGoal > 0);
$requestIsEcommerce = $this->goalManager->requestIsEcommerce;
if ($requestIsEcommerce) {
$someGoalsConverted = true;
// Mark the visit as Converted only if it is an order (not for a Cart update)
if ($this->goalManager->isGoalAnOrder) {
$visitIsConverted = true;
}
} // this request is from the JS call to piwikTracker.trackGoal()
elseif ($requestIsManualGoalConversion) {
$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) {
throw new \Exception('Invalid goal tracking request for goal id = ' . $this->goalManager->idGoal);
}
} // normal page view, potentially triggering a URL matching goal
else {
$action = Action::factory($this->request);
$action->writeDebugInfo();
$someGoalsConverted = $this->goalManager->detectGoalsMatchingUrl($this->request->getIdSite(), $action);
$visitIsConverted = $someGoalsConverted;
$action->loadIdsFromLogActionTable();
}
/***
* Visitor recognition
*/
$visitorId = $this->getSettingsObject()->getConfigId();
$visitor = new Visitor($this->request, $visitorId, $this->visitorInfo, $this->visitorCustomVariables);
$visitor->recognize();
$this->visitorInfo = $visitor->getVisitorInfo();
$isLastActionInTheSameVisit = $this->isLastActionInTheSameVisit($visitor);
if (!$isLastActionInTheSameVisit) {
Common::printDebug("Visitor detected, but last action was more than 30 minutes ago...");
}
// Known visit when:
// ( - the visitor has the Piwik cookie with the idcookie ID used by Piwik to match the visitor
// OR
// - the visitor doesn't have the Piwik cookie but could be match using heuristics @see recognizeTheVisitor()
// )
// AND
// - the last page view for this visitor was less than 30 minutes ago @see isLastActionInTheSameVisit()
if ($visitor->isVisitorKnown()
&& $isLastActionInTheSameVisit
) {
$idReferrerActionUrl = $this->visitorInfo['visit_exit_idaction_url'];
$idReferrerActionName = $this->visitorInfo['visit_exit_idaction_name'];
try {
$this->goalManager->detectIsThereExistingCartInVisit($this->visitorInfo);
$this->handleExistingVisit($visitor, $action, $visitIsConverted);
if (!is_null($action)) {
$action->record($visitor, $idReferrerActionUrl, $idReferrerActionName);
}
} catch (VisitorNotFoundInDb $e) {
// There is an edge case when:
// - two manual goal conversions happen in the same second
// - which result in handleExistingVisit throwing the exception
// because the UPDATE didn't affect any rows (one row was found, but not updated since no field changed)
// - the exception is caught here and will result in a new visit incorrectly
// In this case, we cancel the current conversion to be recorded:
if ($requestIsManualGoalConversion
|| $requestIsEcommerce
) {
$someGoalsConverted = $visitIsConverted = false;
} // When the row wasn't found in the logs, and this is a pageview or
// goal matching URL, we force a new visitor
else {
$visitor->setIsVisitorKonwn(false);
}
}
}
// New visit when:
// - the visitor has the Piwik cookie but the last action was performed more than 30 min ago @see isLastActionInTheSameVisit()
// - the visitor doesn't have the Piwik cookie, and couldn't be matched in @see recognizeTheVisitor()
// - the visitor does have the Piwik cookie but the idcookie and idvisit found in the cookie didn't match to any existing visit in the DB
if (!$visitor->isVisitorKnown()
|| !$isLastActionInTheSameVisit
) {
$this->handleNewVisit($visitor, $action, $visitIsConverted);
if (!is_null($action)) {
$action->record($visitor, 0, 0);
}
}
// update the cookie with the new visit information
$this->request->setThirdPartyCookie($this->visitorInfo['idvisitor']);
// record the goals if applicable
if ($someGoalsConverted) {
$this->goalManager->recordGoals(
$visitor,
$this->visitorInfo,
$this->visitorCustomVariables,
$action
);
}
unset($this->goalManager);
unset($action);
}
/**
* In the case of a known visit, we have to do the following actions:
*
* 1) Insert the new action
* 2) Update the visit information
*
* @param Visitor $visitor
* @param Action $action
* @param $visitIsConverted
* @throws VisitorNotFoundInDb
*/
protected function handleExistingVisit($visitor, $action, $visitIsConverted)
{
Common::printDebug("Visit is known (IP = " . IP::N2P($this->getVisitorIp()) . ")");
$valuesToUpdate = $this->getExistingVisitFieldsToUpdate($visitor, $action, $visitIsConverted);
// TODO we should not have to sync this->visitorInfo and $visitor columns.
// TODO it should be its own dimension
$this->visitorInfo['time_spent_ref_action'] = $this->getTimeSpentReferrerAction();
$visitor->setVisitorColumn('time_spent_ref_action', $this->visitorInfo['time_spent_ref_action']);
// update visitorInfo
foreach ($valuesToUpdate AS $name => $value) {
$this->visitorInfo[$name] = $value;
}
/**
* Triggered before a [visit entity](/guides/persistence-and-the-mysql-backend#visits) is updated when
* tracking an action for an existing visit.
*
* This event can be used to modify the visit properties that will be updated before the changes
* are persisted.
*
* @param array &$valuesToUpdate Visit entity properties that will be updated.
* @param array $visit The entire visit entity. Read [this](/guides/persistence-and-the-mysql-backend#visits)
* to see what it contains.
*/
Piwik::postEvent('Tracker.existingVisitInformation', array(&$valuesToUpdate, $this->visitorInfo));
$this->updateExistingVisit($valuesToUpdate);
$this->visitorInfo['visit_last_action_time'] = $this->request->getCurrentTimestamp();
$visitor->setVisitorColumn('visit_last_action_time', $this->visitorInfo['visit_last_action_time']);
}
/**
* @return int Time in seconds
*/
protected function getTimeSpentReferrerAction()
{
$timeSpent = $this->request->getCurrentTimestamp() - $this->visitorInfo['visit_last_action_time'];
if ($timeSpent < 0
|| $timeSpent > Config::getInstance()->Tracker['visit_standard_length']
) {
$timeSpent = 0;
}
return $timeSpent;
}
/**
* In the case of a new visit, we have to do the following actions:
*
* 1) Insert the new action
*
* 2) Insert the visit information
*
* @param Visitor $visitor
* @param Action $action
* @param bool $visitIsConverted
*/
protected function handleNewVisit($visitor, $action, $visitIsConverted)
{
Common::printDebug("New Visit (IP = " . IP::N2P($this->getVisitorIp()) . ")");
$idVisitor = $this->getVisitorIdcookie($visitor);
$this->visitorInfo = $this->getNewVisitorInformation($idVisitor);
// Add Custom variable key,value to the visitor array
$this->visitorInfo = array_merge($this->visitorInfo, $this->visitorCustomVariables);
$dimensions = VisitDimension::getAllDimensions();
$this->triggerHookOnDimensions($dimensions, 'onNewVisit', $visitor, $action);
if ($visitIsConverted) {
$this->triggerHookOnDimensions($dimensions, 'onConvertedVisit', $visitor, $action);
}
/**
* Triggered before a new [visit entity](/guides/persistence-and-the-mysql-backend#visits) is persisted.
*
* This event can be used to modify the visit entity or add new information to it before it is persisted.
* The UserCountry plugin, for example, uses this event to add location information for each visit.
*
* @param array &$visit The visit entity. Read [this](/guides/persistence-and-the-mysql-backend#visits) to see
* what information it contains.
* @param \Piwik\Tracker\Request $request An object describing the tracking request being processed.
*/
Piwik::postEvent('Tracker.newVisitorInformation', array(&$this->visitorInfo, $this->request));
$this->printVisitorInformation();
$idVisit = $this->insertNewVisit( $this->visitorInfo );
$this->visitorInfo['idvisit'] = $idVisit;
$this->visitorInfo['visit_first_action_time'] = $this->request->getCurrentTimestamp();
$this->visitorInfo['visit_last_action_time'] = $this->request->getCurrentTimestamp();
$visitor->setVisitorColumn('idvisit', $this->visitorInfo['idvisit']);
$visitor->setVisitorColumn('visit_first_action_time', $this->visitorInfo['visit_first_action_time']);
$visitor->setVisitorColumn('visit_last_action_time', $this->visitorInfo['visit_last_action_time']);
}
/**
* Returns visitor cookie
*
* @return string binary
*/
protected function getVisitorIdcookie(Visitor $visitor)
{
if ($visitor->isVisitorKnown()) {
return $this->visitorInfo['idvisitor'];
}
// If the visitor had a first party ID cookie, then we use this value
if (!empty($this->visitorInfo['idvisitor'])
&& strlen($this->visitorInfo['idvisitor']) == Tracker::LENGTH_BINARY_ID
) {
return $this->visitorInfo['idvisitor'];
}
return Common::hex2bin($this->generateUniqueVisitorId());
}
/**
* @return string returns random 16 chars hex string
*/
static public function generateUniqueVisitorId()
{
$uniqueId = substr(Common::generateUniqId(), 0, Tracker::LENGTH_HEX_ID_STRING);
return $uniqueId;
}
/**
* Returns the visitor's IP address
*
* @return string
*/
protected function getVisitorIp()
{
return $this->visitorInfo['location_ip'];
}
/**
* Gets the UserSettings object
*
* @return Settings
*/
protected function getSettingsObject()
{
if(is_null($this->userSettings)) {
$this->userSettings = new Settings( $this->request, $this->getVisitorIp() );
}
return $this->userSettings;
}
/**
* Returns true if the last action was done during the last 30 minutes
* @return bool
*/
protected function isLastActionInTheSameVisit(Visitor $visitor)
{
$lastActionTime = $visitor->getVisitorColumn('visit_last_action_time');
return isset($lastActionTime)
&& false !== $lastActionTime
&& ($lastActionTime > ($this->request->getCurrentTimestamp() - Config::getInstance()->Tracker['visit_standard_length']));
}
// is the referrer host any of the registered URLs for this website?
static public function isHostKnownAliasHost($urlHost, $idSite)
{
$websiteData = Cache::getCacheWebsiteAttributes($idSite);
if (isset($websiteData['hosts'])) {
$canonicalHosts = array();
foreach ($websiteData['hosts'] as $host) {
$canonicalHosts[] = str_replace('www.', '', mb_strtolower($host, 'UTF-8'));
}
$canonicalHost = str_replace('www.', '', mb_strtolower($urlHost, 'UTF-8'));
if (in_array($canonicalHost, $canonicalHosts)) {
return true;
}
}
return false;
}
/**
* @return mixed
*/
protected function insertNewVisit($visit)
{
$fields = implode(", ", array_keys($visit));
$values = Common::getSqlStringFieldsArray($visit);
$sql = "INSERT INTO " . Common::prefixTable('log_visit') . " ($fields) VALUES ($values)";
$bind = array_values($visit);
Tracker::getDatabase()->query($sql, $bind);
$idVisit = Tracker::getDatabase()->lastInsertId();
return $idVisit;
}
/**
* @param $valuesToUpdate
* @throws VisitorNotFoundInDb
*/
protected function updateExistingVisit($valuesToUpdate)
{
$sqlQuery = "UPDATE " . Common::prefixTable('log_visit') . "
SET %s
WHERE idsite = ?
AND idvisit = ?";
// build sql query
$updateParts = $sqlBind = array();
foreach ($valuesToUpdate AS $name => $value) {
// Case where bind parameters don't work
if(strpos($value, $name) !== false) {
//$name = 'visit_total_events'
//$value = 'visit_total_events + 1';
$updateParts[] = " $name = $value ";
} else {
$updateParts[] = $name . " = ?";
$sqlBind[] = $value;
}
}
$sqlQuery = sprintf($sqlQuery, implode($updateParts, ', ') );
array_push($sqlBind, $this->request->getIdSite(), (int)$this->visitorInfo['idvisit']);
$result = Tracker::getDatabase()->query($sqlQuery, $sqlBind);
// Debug output
if (isset($valuesToUpdate['idvisitor'])) {
$valuesToUpdate['idvisitor'] = bin2hex($valuesToUpdate['idvisitor']);
}
Common::printDebug('Updating existing visit: ' . var_export($valuesToUpdate, true));
if (Tracker::getDatabase()->rowCount($result) == 0) {
Common::printDebug("Visitor with this idvisit wasn't found in the DB.");
Common::printDebug("$sqlQuery --- ");
Common::printDebug($sqlBind);
throw new VisitorNotFoundInDb(
"The visitor with idvisitor=" . bin2hex($this->visitorInfo['idvisitor']) . " and idvisit=" . $this->visitorInfo['idvisit']
. " wasn't found in the DB, we fallback to a new visitor");
}
}
protected function printVisitorInformation()
{
$debugVisitInfo = $this->visitorInfo;
$debugVisitInfo['idvisitor'] = bin2hex($debugVisitInfo['idvisitor']);
$debugVisitInfo['config_id'] = bin2hex($debugVisitInfo['config_id']);
Common::printDebug($debugVisitInfo);
}
protected function getNewVisitorInformation($idVisitor)
{
return array(
'idvisitor' => $idVisitor,
'config_id' => $this->getSettingsObject()->getConfigId(),
'location_ip' => $this->getVisitorIp(),
);
}
/**
* Gather fields=>values that needs to be updated for the existing visit in log_visit
*
* @param Visitor $visitor
* @param Action|null $action
* @param $visitIsConverted
* @return array
*/
protected function getExistingVisitFieldsToUpdate($visitor, $action, $visitIsConverted)
{
$valuesToUpdate = array();
// Might update the idvisitor when it was forced or overwritten for this visit
if (strlen($this->visitorInfo['idvisitor']) == Tracker::LENGTH_BINARY_ID) {
$valuesToUpdate['idvisitor'] = $this->visitorInfo['idvisitor'];
}
$dimensions = VisitDimension::getAllDimensions();
$valuesToUpdate = $this->triggerHookOnDimensions($dimensions, 'onExistingVisit', $visitor, $action, $valuesToUpdate);
if ($visitIsConverted) {
$valuesToUpdate = $this->triggerHookOnDimensions($dimensions, 'onConvertedVisit', $visitor, $action, $valuesToUpdate);
}
// Custom Variables overwrite previous values on each page view
$valuesToUpdate = array_merge($valuesToUpdate, $this->visitorCustomVariables);
return $valuesToUpdate;
}
/**
* @param VisitDimension[] $dimensions
* @param string $hook
* @param Visitor $visitor
* @param Action|null $action
* @param array|null $valuesToUpdate If null, $this->visitorInfo will be updated
*
* @return array|null The updated $valuesToUpdate or null if no $valuesToUpdate given
*/
private function triggerHookOnDimensions($dimensions, $hook, $visitor, $action, $valuesToUpdate = null)
{
foreach ($dimensions as $dimension) {
$value = $dimension->$hook($this->request, $visitor, $action);
if ($value !== false) {
$fieldName = $dimension->getFieldName();
$visitor->setVisitorColumn($fieldName, $value);
if ($valuesToUpdate !== null) {
$valuesToUpdate[$fieldName] = $value;
} else {
$this->visitorInfo[$fieldName] = $value;
}
}
}
return $valuesToUpdate;
}
}
|