Welcome to mirror list, hosted at ThFree Co, Russian Federation.

VisitorProfile.php « Live « plugins - github.com/matomo-org/matomo.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 181c8bb302e7fde4799a18114b5cbb16fd43bf34 (plain)
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
<?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\Live;

use Exception;
use Piwik\DataTable;
use Piwik\Date;
use Piwik\Metrics\Formatter;
use Piwik\Piwik;
use Piwik\Site;
use Piwik\Plugins\Referrers\API as APIReferrers;

class VisitorProfile
{
    const VISITOR_PROFILE_MAX_VISITS_TO_SHOW = 10;

    protected $profile = array();
    private $siteSearchKeywords = array();
    private $continents = array();
    private $countries = array();
    private $cities = array();
    private $pageGenerationTimeTotal = 0;

    public function __construct($idSite)
    {
        $this->idSite = $idSite;
        $this->isEcommerceEnabled = Site::isEcommerceEnabledFor($this->idSite);
    }

    /**
     * @param $visits
     * @param $visitorId
     * @param $segment
     * @param $numLastVisits
     * @return array
     * @throws Exception
     */
    public function makeVisitorProfile(DataTable $visits, $visitorId, $segment, $numLastVisits)
    {
        $this->initVisitorProfile();

        /** @var DataTable\Row $visit */
        foreach ($visits->getRows() as $visit) {
            ++$this->profile['totalVisits'];

            $this->profile['totalVisitDuration'] += $visit->getColumn('visitDuration');
            $this->profile['totalActions'] += $visit->getColumn('actions');
            $this->profile['totalGoalConversions'] += $visit->getColumn('goalConversions');

            // individual goal conversions are stored in action details
            foreach ($visit->getColumn('actionDetails') as $action) {
                $this->handleIfGoalAction($action);
                $this->handleIfEventAction($action);
                $this->handleIfDownloadAction($action);
                $this->handleIfOutlinkAction($action);
                $this->handleIfEcommerceAction($action);
                $this->handleIfSiteSearchAction($action);
                $this->handleIfPageViewAction($action);
                $this->handleIfPageGenerationTime($action);
            }
            $this->handleGeoLocation($visit);
        }

        $this->handleGeoLocationCountries();
        $this->handleGeoLocationContinents();
        $this->handleSiteSearches();
        $this->handleAveragePageGenerationTime();

        $formatter = new Formatter();
        $this->profile['totalVisitDurationPretty'] = $formatter->getPrettyTimeFromSeconds($this->profile['totalVisitDuration'], true);

        $this->handleVisitsSummary($visits);
        $this->handleAdjacentVisitorIds($visits, $visitorId, $segment);

        // use N most recent visits for last_visits
        $visits->deleteRowsOffset($numLastVisits);

        $this->profile['lastVisits'] = $visits;

        $this->profile['userId'] = $visit->getColumn('userId');

        return $this->profile;
    }

    /**
     * Returns a summary for an important visit. Used to describe the first & last visits of a visitor.
     *
     * @param DataTable\Row $visit
     * @return array
     */
    private function getVisitorProfileVisitSummary($visit)
    {
        $today = Date::today();

        $serverDate = $visit->getColumn('firstActionTimestamp');
        return array(
            'date'            => $serverDate,
            'prettyDate'      => Date::factory($serverDate)->getLocalized(Date::DATE_FORMAT_LONG),
            'daysAgo'         => (int)Date::secondsToDays($today->getTimestamp() - Date::factory($serverDate)->getTimestamp()),
            'referrerType'    => $visit->getColumn('referrerType'),
            'referralSummary' => self::getReferrerSummaryForVisit($visit),
        );
    }


    /**
     * Returns a summary for a visit's referral.
     *
     * @param DataTable\Row $visit
     * @return bool|mixed|string
     */
    public static function getReferrerSummaryForVisit($visit)
    {
        $referrerType = $visit->getColumn('referrerType');
        if ($referrerType === false
            || $referrerType == 'direct'
        ) {
            return Piwik::translate('Referrers_DirectEntry');
        }

        if ($referrerType == 'search') {
            $referrerName = $visit->getColumn('referrerName');

            $keyword = $visit->getColumn('referrerKeyword');
            if ($keyword !== false
                && $keyword != APIReferrers::getKeywordNotDefinedString()
            ) {
                $referrerName .= ' (' . $keyword . ')';
            }
            return $referrerName;
        }

        if ($referrerType == 'campaign') {

            $summary = Piwik::translate('Referrers_ColumnCampaign') . ': ' . $visit->getColumn('referrerName');
            $keyword = $visit->getColumn('referrerKeyword');
            if (!empty($keyword)) {
                $summary .= ' - ' . $keyword;
            }

            return $summary;
        }

        return $visit->getColumn('referrerName');
    }

    private function isEcommerceEnabled()
    {
        return $this->isEcommerceEnabled;
    }

    /**
     * @param $action
     */
    private function handleIfEventAction($action)
    {
        if ($action['type'] != 'event') {
            return;
        }
        $this->profile['totalEvents']++;
    }

    /**
     * @param $action
     */
    private function handleIfDownloadAction($action)
    {
        if ($action['type'] != 'download') {
            return;
        }
        $this->profile['totalDownloads']++;
    }

    /**
     * @param $action
     */
    private function handleIfOutlinkAction($action)
    {
        if ($action['type'] != 'outlink') {
            return;
        }
        $this->profile['totalOutlinks']++;
    }

    /**
     * @param $action
     */
    private function handleIfPageViewAction($action)
    {
        if ($action['type'] != 'action') {
            return;
        }
        $this->profile['totalPageViews']++;
    }

    /**
     * @param $action
     */
    private function handleIfEcommerceAction($action)
    {
        if (!$this->isEcommerceEnabled()) {
            return;
        }
        if ($action['type'] == Piwik::LABEL_ID_GOAL_IS_ECOMMERCE_ORDER) {
            ++$this->profile['totalEcommerceConversions'];
            $this->profile['totalEcommerceRevenue'] += $action['revenue'];
            $this->profile['totalEcommerceItems'] += $action['items'];
        } else if ($action['type'] == Piwik::LABEL_ID_GOAL_IS_ECOMMERCE_CART) {
            ++$this->profile['totalAbandonedCarts'];
            $this->profile['totalAbandonedCartsRevenue'] += $action['revenue'];
            $this->profile['totalAbandonedCartsItems'] += $action['items'];
        }
    }

    private function handleIfGoalAction($action)
    {
        if ($action['type'] != 'goal') {
            return;
        }
        $idGoal = $action['goalId'];
        $idGoalKey = 'idgoal=' . $idGoal;

        if (!isset($this->profile['totalConversionsByGoal'][$idGoalKey])) {
            $this->profile['totalConversionsByGoal'][$idGoalKey] = 0;
        }
        ++$this->profile['totalConversionsByGoal'][$idGoalKey];

        if (!empty($action['revenue'])) {
            if (!isset($this->profile['totalRevenueByGoal'][$idGoalKey])) {
                $this->profile['totalRevenueByGoal'][$idGoalKey] = 0;
            }
            $this->profile['totalRevenueByGoal'][$idGoalKey] += $action['revenue'];
        }
    }

    private function handleIfSiteSearchAction($action)
    {
        if (!isset($action['siteSearchKeyword'])) {
            return;
        }
        $keyword = $action['siteSearchKeyword'];

        if (!isset($this->siteSearchKeywords[$keyword])) {
            $this->siteSearchKeywords[$keyword] = 0;
            ++$this->profile['totalSearches'];
        }
        ++$this->siteSearchKeywords[$keyword];
    }

    private function handleGeoLocation(DataTable\Row $visit)
    {
        // realtime map only checks for latitude
        $hasLatitude = $visit->getColumn('latitude') !== false;
        if ($hasLatitude) {
            $this->profile['hasLatLong'] = true;
        }

        $countryCode = $visit->getColumn('countryCode');
        if (!isset($this->countries[$countryCode])) {
            $this->countries[$countryCode] = 0;
        }
        ++$this->countries[$countryCode];

        $continentCode = $visit->getColumn('continentCode');
        if (!isset($this->continents[$continentCode])) {
            $this->continents[$continentCode] = 0;
        }
        ++$this->continents[$continentCode];

        if ($countryCode && !array_key_exists($countryCode, $this->cities)) {
            $this->cities[$countryCode] = array();
        }
        $city = $visit->getColumn('city');
        if (!empty($city)) {
            $this->cities[$countryCode][] = $city;
        }
    }

    private function handleSiteSearches()
    {
        // sort by visit/action
        arsort($this->siteSearchKeywords);

        foreach ($this->siteSearchKeywords as $keyword => $searchCount) {
            $this->profile['searches'][] = array('keyword' => $keyword,
                'searches' => $searchCount);
        }
    }

    private function handleGeoLocationContinents()
    {
        // sort by visit/action
        asort($this->continents);
        foreach ($this->continents as $continentCode => $nbVisits) {
            $this->profile['continents'][] = array('continent' => $continentCode,
                'nb_visits' => $nbVisits,
                'prettyName' => \Piwik\Plugins\UserCountry\continentTranslate($continentCode));
        }
    }

    private function handleGeoLocationCountries()
    {
        // sort by visit/action
        asort($this->countries);

        // transform country/continents/search keywords into something that will look good in XML
        $this->profile['countries'] = $this->profile['continents'] = $this->profile['searches'] = array();

        foreach ($this->countries as $countryCode => $nbVisits) {

            $countryInfo = array('country' => $countryCode,
                'nb_visits' => $nbVisits,
                'flag' => \Piwik\Plugins\UserCountry\getFlagFromCode($countryCode),
                'prettyName' => \Piwik\Plugins\UserCountry\countryTranslate($countryCode));
            if (!empty($this->cities[$countryCode])) {
                $countryInfo['cities'] = array_unique($this->cities[$countryCode]);
            }
            $this->profile['countries'][] = $countryInfo;
        }
    }

    private function initVisitorProfile()
    {
        $this->profile['totalVisits'] = 0;
        $this->profile['totalVisitDuration'] = 0;
        $this->profile['totalActions'] = 0;
        $this->profile['totalEvents'] = 0;
        $this->profile['totalOutlinks'] = 0;
        $this->profile['totalDownloads'] = 0;
        $this->profile['totalSearches'] = 0;
        $this->profile['totalPageViews'] = 0;
        $this->profile['totalPageViewsWithTiming'] = 0;
        $this->profile['totalGoalConversions'] = 0;
        $this->profile['totalConversionsByGoal'] = array();
        $this->profile['hasLatLong'] = false;

        if ($this->isEcommerceEnabled()) {
            $this->profile['totalEcommerceConversions'] = 0;
            $this->profile['totalEcommerceRevenue'] = 0;
            $this->profile['totalEcommerceItems'] = 0;
            $this->profile['totalAbandonedCarts'] = 0;
            $this->profile['totalAbandonedCartsRevenue'] = 0;
            $this->profile['totalAbandonedCartsItems'] = 0;
        }
    }

    private function handleAveragePageGenerationTime()
    {
        if ($this->profile['totalPageViewsWithTiming']) {
            $this->profile['averagePageGenerationTime'] =
                round($this->pageGenerationTimeTotal / (1000 * $this->profile['totalPageViewsWithTiming']), $precision = 3);
        }
    }

    private function handleIfPageGenerationTime($action)
    {
        if (isset($action['generationTimeMilliseconds'])) {
            $this->pageGenerationTimeTotal += $action['generationTimeMilliseconds'];
            ++$this->profile['totalPageViewsWithTiming'];
        }
    }

    /**
     * @param DataTable $visits
     * @param $visitorId
     * @param $segment
     */
    private function handleAdjacentVisitorIds(DataTable $visits, $visitorId, $segment)
    {
        // get visitor IDs that are adjacent to this one in log_visit
        // TODO: make sure order of visitor ids is not changed if a returning visitor visits while the user is
        //       looking at the popup.
        $rows = $visits->getRows();
        $latestVisitTime = reset($rows)->getColumn('lastActionDateTime');

        $model = new Model();
        $this->profile['nextVisitorId'] = $model->queryAdjacentVisitorId($this->idSite, $visitorId, $latestVisitTime, $segment, $getNext = true);
        $this->profile['previousVisitorId'] = $model->queryAdjacentVisitorId($this->idSite, $visitorId, $latestVisitTime, $segment, $getNext = false);
    }

    /**
     * @param DataTable $visits
     */
    private function handleVisitsSummary(DataTable $visits)
    {
        $rows = $visits->getRows();
        $this->profile['firstVisit'] = $this->getVisitorProfileVisitSummary(end($rows));
        $this->profile['lastVisit'] = $this->getVisitorProfileVisitSummary(reset($rows));
        $this->profile['visitsAggregated'] = count($rows);
    }
}