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
|
<?php
/**
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*
*/
namespace Piwik\Plugins\Actions;
use Piwik\Common;
use Piwik\Config;
use Piwik\Date;
use Piwik\Db;
use Piwik\Metrics\Formatter;
use Piwik\Piwik;
use Piwik\Plugins\Live\VisitorDetailsAbstract;
use Piwik\Site;
use Piwik\Tracker\Action;
use Piwik\Tracker\PageUrl;
use Piwik\View;
class VisitorDetails extends VisitorDetailsAbstract
{
public function extendVisitorDetails(&$visitor)
{
$visitor['searches'] = $this->details['visit_total_searches'];
$visitor['actions'] = $this->details['visit_total_actions'];
$visitor['interactions'] = $this->details['visit_total_interactions'];
}
public function provideActionsForVisitIds(&$actions, $visitIds)
{
$actionDetails = $this->queryActionsForVisits($visitIds);
// use while / array_shift combination instead of foreach to save memory
while (is_array($actionDetails) && count($actionDetails)) {
$action = array_shift($actionDetails);
$idVisit = $action['idvisit'];
unset($action['idvisit']);
$actions[$idVisit][] = $action;
}
}
public function provideActionsForVisit(&$actions, $visitorDetails)
{
$actionDetails = $actions;
$formatter = new Formatter();
// Enrich with time spent per action
$nextActionId = 0;
foreach ($actionDetails as $idx => &$action) {
if ($idx < $nextActionId || !$this->shouldHandleAction($action)) {
continue; // skip to next action having timeSpentRef
}
// search for next action with timeSpentRef
$nextActionId = $idx + 1;
$nextAction = null;
while (isset($actionDetails[$nextActionId]) &&
(!$this->shouldHandleAction($actionDetails[$nextActionId]) ||
!array_key_exists('timeSpentRef', $actionDetails[$nextActionId]))) {
$nextActionId++;
}
$nextAction = isset($actionDetails[$nextActionId]) ? $actionDetails[$nextActionId] : null;
// Set the time spent for this action (which is the timeSpentRef of the next action)
if ($nextAction) {
$action['timeSpent'] = $nextAction['timeSpentRef'];
} else {
// Last action of a visit.
// By default, Piwik does not know how long the user stayed on the page
// If enableHeartBeatTimer() is used in piwik.js then we can find the accurate time on page for the last pageview
$visitTotalTime = $visitorDetails['visitDuration'];
$timeOfLastAction = Date::factory($action['serverTimePretty'])->getTimestamp();
$timeSpentOnAllActionsApartFromLastOne = ($timeOfLastAction - $visitorDetails['firstActionTimestamp']);
$timeSpentOnPage = $visitTotalTime - $timeSpentOnAllActionsApartFromLastOne;
// Safe net, we assume the time is correct when it's more than 10 seconds
if ($timeSpentOnPage > 10) {
$action['timeSpent'] = $timeSpentOnPage;
}
}
if (isset($action['timeSpent'])) {
$action['timeSpentPretty'] = $formatter->getPrettyTimeFromSeconds($action['timeSpent'], true);
}
unset($action['timeSpentRef']); // not needed after timeSpent is added
}
$actions = $actionDetails;
}
private function shouldHandleAction($action) {
$actionTypesToHandle = array(
Action::TYPE_PAGE_URL,
Action::TYPE_PAGE_TITLE,
Action::TYPE_SITE_SEARCH,
Action::TYPE_EVENT,
Action::TYPE_OUTLINK,
Action::TYPE_DOWNLOAD
);
return in_array($action['type'], $actionTypesToHandle) || !empty($action['eventType']);
}
public function extendActionDetails(&$action, $nextAction, $visitorDetails)
{
$formatter = new Formatter();
if ($action['type'] == Action::TYPE_SITE_SEARCH) {
// Handle Site Search
$action['siteSearchKeyword'] = $action['pageTitle'];
unset($action['pageTitle']);
}
// Generation time
if ($this->shouldHandleAction($action) && empty($action['eventType']) && isset($action['custom_float']) && $action['custom_float'] > 0) {
$action['generationTimeMilliseconds'] = $action['custom_float'];
$action['generationTime'] = $formatter->getPrettyTimeFromSeconds($action['custom_float'] / 1000, true);
unset($action['custom_float']);
}
if (array_key_exists('custom_float', $action) && is_null($action['custom_float'])) {
unset($action['custom_float']);
}
if (array_key_exists('interaction_position', $action)) {
$action['interactionPosition'] = $action['interaction_position'];
unset($action['interaction_position']);
}
// Reconstruct url from prefix
if (array_key_exists('url', $action) && array_key_exists('url_prefix', $action)) {
$url = PageUrl::reconstructNormalizedUrl($action['url'], $action['url_prefix']);
$url = Common::unsanitizeInputValue($url);
$action['url'] = $url;
unset($action['url_prefix']);
}
switch ($action['type']) {
case 'goal':
$action['icon'] = 'plugins/Morpheus/images/goal.png';
$action['iconSVG'] = 'plugins/Morpheus/images/goal.svg';
$action['title'] = Piwik::translate('Goals_GoalConversion');
$action['subtitle'] = $action['goalName'];
if (!empty($action['revenue'])) {
$action['subtitle'] .= ' (' . Piwik::translate('Goals_NRevenue', $formatter->getPrettyMoney($action['revenue'], $visitorDetails['idSite'])) . ')';
}
break;
case Piwik::LABEL_ID_GOAL_IS_ECOMMERCE_ORDER:
case Piwik::LABEL_ID_GOAL_IS_ECOMMERCE_CART:
$action['icon'] = 'plugins/Morpheus/images/' . $action['type'] . '.png';
$action['iconSVG'] = 'plugins/Morpheus/images/' . $action['type'] . '.svg';
if ($action['type'] == Piwik::LABEL_ID_GOAL_IS_ECOMMERCE_ORDER) {
$action['title'] = Piwik::translate('CoreHome_VisitStatusOrdered') . ' (' . $action['orderId'] . ')';
} else {
$action['title'] = Piwik::translate('Goals_AbandonedCart');
}
$itemNames = implode(', ', array_column($action['itemDetails'], 'itemName'));
$action['subtitle'] = Piwik::translate('Goals_NRevenue', $formatter->getPrettyMoney($action['revenue'], $visitorDetails['idSite']));
$action['subtitle'] .= ' - ' . Piwik::translate('Goals_NItems', $action['items']) . ': ' . $itemNames .')';
break;
case Action::TYPE_CONTENT:
if (!empty($action['contentInteraction'])) {
$action['icon'] = 'plugins/Morpheus/images/contentinteraction.png';
$action['iconSVG'] = 'plugins/Morpheus/images/contentinteraction.svg';
$action['title'] = Piwik::translate('Contents_ContentInteraction') . ' (' . $action['contentInteraction'] . ')';
} else {
$action['icon'] = 'plugins/Morpheus/images/contentimpression.png';
$action['iconSVG'] = 'plugins/Morpheus/images/contentimpression.svg';
$action['title'] = Piwik::translate('Contents_ContentImpression');
}
$action['subtitle'] = $action['contentName'];
if (!empty($action['contentPiece'])) {
$action['subtitle'] .= ' - ' . $action['contentPiece'];
}
break;
case Action::TYPE_DOWNLOAD:
$action['type'] = 'download';
$action['icon'] = 'plugins/Morpheus/images/download.png';
$action['iconSVG'] = 'plugins/Morpheus/images/download.svg';
$action['title'] = Piwik::translate('General_Download');
$action['subtitle'] = $action['url'];
break;
case Action::TYPE_OUTLINK:
$action['type'] = 'outlink';
$action['icon'] = 'plugins/Morpheus/images/link.png';
$action['iconSVG'] = 'plugins/Morpheus/images/link.svg';
$action['title'] = Piwik::translate('General_Outlink');
$action['subtitle'] = $action['url'];
break;
case Action::TYPE_SITE_SEARCH:
$action['type'] = 'search';
$action['icon'] = 'plugins/Morpheus/images/search.png';
$action['iconSVG'] = 'plugins/Morpheus/images/search.svg';
$action['title'] = Piwik::translate('Actions_SubmenuSitesearch');
$action['subtitle'] = $action['siteSearchKeyword'];
break;
case Action::TYPE_PAGE_URL:
case Action::TYPE_PAGE_TITLE:
case '':
if (!isset($action['title'])) {
$action['title'] = $action['pageTitle'];
$action['subtitle'] = $action['url'];
}
$action['type'] = 'action';
$action['icon'] = '';
$action['iconSVG'] = 'plugins/Morpheus/images/action.svg';
break;
}
// Convert datetimes to the site timezone
$dateTimeVisit = Date::factory($action['serverTimePretty'],
Site::getTimezoneFor($visitorDetails['idSite']));
$action['serverTimePretty'] = $dateTimeVisit->getLocalized(Date::DATETIME_FORMAT_SHORT);
$action['timestamp'] = $dateTimeVisit->getTimestamp();
unset($action['idlink_va']);
}
/**
* @param $idVisit
* @return array
* @throws \Exception
*/
protected function queryActionsForVisits($idVisits)
{
$customFields = array();
$customJoins = array();
Piwik::postEvent('Actions.getCustomActionDimensionFieldsAndJoins', array(&$customFields, &$customJoins));
$customFields = array_filter($customFields);
array_unshift($customFields, ''); // add empty element at first
$customActionDimensionFields = implode(', ', $customFields);
// The second join is a LEFT join to allow returning records that don't have a matching page title
// eg. Downloads, Outlinks. For these, idaction_name is set to 0
$sql = "
SELECT
log_link_visit_action.idvisit,
COALESCE(log_action.type, log_action_title.type) AS type,
log_action.name AS url,
log_action.url_prefix,
log_action_title.name AS pageTitle,
log_action.idaction AS pageIdAction,
log_link_visit_action.idpageview,
log_link_visit_action.idlink_va,
log_link_visit_action.server_time as serverTimePretty,
log_link_visit_action.time_spent_ref_action as timeSpentRef,
log_link_visit_action.idlink_va AS pageId,
log_link_visit_action.custom_float,
log_link_visit_action.interaction_position
" . $customActionDimensionFields . "
FROM " . Common::prefixTable('log_link_visit_action') . " AS log_link_visit_action
LEFT JOIN " . Common::prefixTable('log_action') . " AS log_action
ON log_link_visit_action.idaction_url = log_action.idaction
LEFT JOIN " . Common::prefixTable('log_action') . " AS log_action_title
ON log_link_visit_action.idaction_name = log_action_title.idaction
" . implode(" ", $customJoins) . "
WHERE log_link_visit_action.idvisit IN ('" . implode("','", $idVisits) . "')
ORDER BY log_link_visit_action.idvisit, server_time ASC
";
$actionDetails = Db::fetchAll($sql);
return $actionDetails;
}
private $visitedPageUrls = array();
private $siteSearchKeywords = array();
private $pageGenerationTimeTotal = 0;
public function initProfile($visits, &$profile)
{
$this->visitedPageUrls = array();
$this->siteSearchKeywords = array();
$this->pageGenerationTimeTotal = 0;
$profile['totalActions'] = 0;
$profile['totalOutlinks'] = 0;
$profile['totalDownloads'] = 0;
$profile['totalSearches'] = 0;
$profile['totalPageViews'] = 0;
$profile['totalUniquePageViews'] = 0;
$profile['totalRevisitedPages'] = 0;
$profile['totalPageViewsWithTiming'] = 0;
$profile['searches'] = array();
}
public function handleProfileVisit($visit, &$profile)
{
$profile['totalActions'] += $visit->getColumn('actions');
}
public function handleProfileAction($action, &$profile)
{
$this->handleIfDownloadAction($action, $profile);
$this->handleIfOutlinkAction($action, $profile);
$this->handleIfSiteSearchAction($action, $profile);
$this->handleIfPageViewAction($action, $profile);
$this->handleIfPageGenerationTime($action, $profile);
}
public function finalizeProfile($visits, &$profile)
{
$profile['visitedPages'] = [];
foreach ($this->visitedPageUrls as $visitedPageUrl => $count) {
$profile['visitedPages'][] = [
'url' => $visitedPageUrl,
'count' => $count
];
}
usort($profile['visitedPages'], function($a, $b) {
if ($a['count'] == $b['count']) {
return strcmp($a['url'], $b['url']);
}
return $a['count'] > $b['count'] ? -1 : 1;
});
$this->handleSiteSearches($profile);
$this->handleAveragePageGenerationTime($profile);
}
/**
* @param $action
*/
private function handleIfDownloadAction($action, &$profile)
{
if ($action['type'] != 'download') {
return;
}
$profile['totalDownloads']++;
}
/**
* @param $action
*/
private function handleIfOutlinkAction($action, &$profile)
{
if ($action['type'] != 'outlink') {
return;
}
$profile['totalOutlinks']++;
}
/**
* @param $action
*/
private function handleIfPageViewAction($action, &$profile)
{
if ($action['type'] != 'action') {
return;
}
$profile['totalPageViews']++;
$pageUrl = $action['url'];
if (!empty($pageUrl)) {
if (!array_key_exists($pageUrl, $this->visitedPageUrls)) {
$this->visitedPageUrls[$pageUrl] = 0;
$profile['totalUniquePageViews']++;
}
$this->visitedPageUrls[$pageUrl]++;
if ($this->visitedPageUrls[$pageUrl] == 2) {
$profile['totalRevisitedPages']++;
}
}
}
private function handleIfSiteSearchAction($action, &$profile)
{
if (!isset($action['siteSearchKeyword'])) {
return;
}
$keyword = $action['siteSearchKeyword'];
if (!isset($this->siteSearchKeywords[$keyword])) {
$this->siteSearchKeywords[$keyword] = 0;
++$profile['totalSearches'];
}
++$this->siteSearchKeywords[$keyword];
}
private function handleSiteSearches(&$profile)
{
// sort by visit/action
arsort($this->siteSearchKeywords);
foreach ($this->siteSearchKeywords as $keyword => $searchCount) {
$profile['searches'][] = array(
'keyword' => $keyword,
'searches' => $searchCount
);
}
}
private function handleIfPageGenerationTime($action, &$profile)
{
if (isset($action['generationTimeMilliseconds'])) {
$this->pageGenerationTimeTotal += $action['generationTimeMilliseconds'];
++$profile['totalPageViewsWithTiming'];
}
}
private function handleAveragePageGenerationTime(&$profile)
{
if ($profile['totalPageViewsWithTiming']) {
$profile['averagePageGenerationTime'] =
round($this->pageGenerationTimeTotal / (1000 * $profile['totalPageViewsWithTiming']), $precision = 3);
}
}
}
|