File: Locations.php

package info (click to toggle)
matomo 5.8.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 95,068 kB
  • sloc: php: 289,425; xml: 127,249; javascript: 112,130; python: 202; sh: 178; makefile: 20; sql: 10
file content (195 lines) | stat: -rw-r--r-- 7,341 bytes parent folder | download | duplicates (2)
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
<?php

/**
 * Matomo - free/libre analytics platform
 *
 * @link    https://matomo.org
 * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 */

namespace Piwik\Plugins\UserCountry\RecordBuilders;

use Piwik\ArchiveProcessor;
use Piwik\ArchiveProcessor\Record;
use Piwik\ArchiveProcessor\RecordBuilder;
use Piwik\Config as PiwikConfig;
use Piwik\DataTable;
use Piwik\DataAccess\LogAggregator;
use Piwik\Metrics;
use Piwik\Plugins\UserCountry\Archiver;
use Piwik\Plugins\UserCountry\LocationProvider;

class Locations extends RecordBuilder
{
    protected $dimensions = [
        Archiver::COUNTRY_RECORD_NAME => Archiver::COUNTRY_FIELD,
        Archiver::REGION_RECORD_NAME => Archiver::REGION_FIELD,
        Archiver::CITY_RECORD_NAME => Archiver::CITY_FIELD,
    ];

    private $latLongForCities = [];

    public function __construct()
    {
        parent::__construct();

        $this->columnToSortByBeforeTruncation = Metrics::INDEX_NB_VISITS;
    }

    public function getRecordMetadata(ArchiveProcessor $archiveProcessor): array
    {
        $maxRowsInTable = PiwikConfig::getInstance()->General['datatable_archiving_maximum_rows_standard'];

        return [
            Record::make(Record::TYPE_BLOB, Archiver::COUNTRY_RECORD_NAME),
            Record::make(Record::TYPE_BLOB, Archiver::REGION_RECORD_NAME)
                ->setMaxRowsInTable($maxRowsInTable),
            Record::make(Record::TYPE_BLOB, Archiver::CITY_RECORD_NAME)
                ->setMaxRowsInTable($maxRowsInTable),

            Record::make(Record::TYPE_NUMERIC, Archiver::DISTINCT_COUNTRIES_METRIC)
                ->setIsCountOfBlobRecordRows(Archiver::COUNTRY_RECORD_NAME),
        ];
    }

    protected function aggregate(ArchiveProcessor $archiveProcessor): array
    {
        try {
            /** @var DataTable[] $records */
            $records = [];
            foreach ($this->dimensions as $recordName => $dimension) {
                $records[$recordName] = new DataTable();
            }

            $logAggregator = $archiveProcessor->getLogAggregator();

            $this->aggregateFromVisits($records, $logAggregator);
            $this->aggregateFromConversions($records, $logAggregator);

            $this->setLatitudeLongitude($records[Archiver::CITY_RECORD_NAME]);

            $records[Archiver::DISTINCT_COUNTRIES_METRIC] = $records[Archiver::COUNTRY_RECORD_NAME]->getRowsCount();

            return $records;
        } finally {
            unset($this->latLongForCities);
        }
    }

    /**
     * @param DataTable[] $records
     */
    protected function aggregateFromVisits(array $records, LogAggregator $logAggregator): void
    {
        $additionalSelects = array('MAX(log_visit.location_latitude) as location_latitude',
            'MAX(log_visit.location_longitude) as location_longitude');
        $query = $logAggregator->queryVisitsByDimension(array_values($this->dimensions), $where = false, $additionalSelects);
        if ($query === false) {
            return;
        }

        while ($row = $query->fetch()) {
            $this->makeRegionCityLabelsUnique($row);
            $this->rememberCityLatLong($row);

            $columns = [
                Metrics::INDEX_NB_UNIQ_VISITORS => $row[Metrics::INDEX_NB_UNIQ_VISITORS],
                Metrics::INDEX_NB_VISITS => $row[Metrics::INDEX_NB_VISITS],
                Metrics::INDEX_NB_ACTIONS => $row[Metrics::INDEX_NB_ACTIONS],
                Metrics::INDEX_NB_USERS => $row[Metrics::INDEX_NB_USERS],
                Metrics::INDEX_MAX_ACTIONS => $row[Metrics::INDEX_MAX_ACTIONS],
                Metrics::INDEX_SUM_VISIT_LENGTH => $row[Metrics::INDEX_SUM_VISIT_LENGTH],
                Metrics::INDEX_BOUNCE_COUNT => $row[Metrics::INDEX_BOUNCE_COUNT],
                Metrics::INDEX_NB_VISITS_CONVERTED => $row[Metrics::INDEX_NB_VISITS_CONVERTED],
            ];

            foreach ($records as $recordName => $dataTable) {
                $dimension = $this->dimensions[$recordName];
                $dataTable->sumRowWithLabel($row[$dimension], $columns);
            }
        }
    }

    /**
     * Makes sure the region and city of a query row are unique.
     *
     * @param array $row
     */
    private function makeRegionCityLabelsUnique(array &$row): void
    {
        // remove the location separator from the region/city/country we get from the query
        foreach ($this->dimensions as $column) {
            $row[$column] = str_replace(Archiver::LOCATION_SEPARATOR, '', $row[$column] ?? '');
        }

        // set city first, as containing region might be manipulated afterwards if not empty
        if (!empty($row[Archiver::CITY_FIELD])) {
            $row[Archiver::CITY_FIELD] = $row[Archiver::CITY_FIELD] . Archiver::LOCATION_SEPARATOR . $row[Archiver::REGION_FIELD] . Archiver::LOCATION_SEPARATOR . $row[Archiver::COUNTRY_FIELD];
        }

        if (!empty($row[Archiver::REGION_FIELD])) {
            $row[Archiver::REGION_FIELD] = $row[Archiver::REGION_FIELD] . Archiver::LOCATION_SEPARATOR . $row[Archiver::COUNTRY_FIELD];
        }
    }

    protected function rememberCityLatLong(array $row): void
    {
        if (
            !empty($row[Archiver::CITY_FIELD])
            && !empty($row[Archiver::LATITUDE_FIELD])
            && !empty($row[Archiver::LONGITUDE_FIELD])
            && empty($this->latLongForCities[$row[Archiver::CITY_FIELD]])
        ) {
            $this->latLongForCities[$row[Archiver::CITY_FIELD]] = array($row[Archiver::LATITUDE_FIELD], $row[Archiver::LONGITUDE_FIELD]);
        }
    }

    /**
     * @param DataTable[] $records
     */
    protected function aggregateFromConversions(array $records, LogAggregator $logAggregator): void
    {
        $query = $logAggregator->queryConversionsByDimension(array_values($this->dimensions));

        while ($row = $query->fetch()) {
            $this->makeRegionCityLabelsUnique($row);

            foreach ($records as $recordName => $table) {
                $idGoal = (int) $row['idgoal'];
                $columns = [
                    Metrics::INDEX_GOALS => [
                        $idGoal => Metrics::makeGoalColumnsRow($idGoal, $row),
                    ],
                ];

                $dimension = $this->dimensions[$recordName];
                $table->sumRowWithLabel($row[$dimension], $columns);
            }
        }

        foreach ($records as $table) {
            $table->filter(DataTable\Filter\EnrichRecordWithGoalMetricSums::class);
        }
    }

    /**
     * Utility method, appends latitude/longitude pairs to city table labels, if that data
     * exists for the city.
     */
    private function setLatitudeLongitude(DataTable $tableCity): void
    {
        foreach ($tableCity->getRows() as $row) {
            $label = $row->getColumn('label');
            if (isset($this->latLongForCities[$label])) {
                // get lat/long for city
                list($lat, $long) = $this->latLongForCities[$label];
                $lat = round($lat, LocationProvider::GEOGRAPHIC_COORD_PRECISION);
                $long = round($long, LocationProvider::GEOGRAPHIC_COORD_PRECISION);

                // set latitude + longitude metadata
                $row->setMetadata('lat', $lat);
                $row->setMetadata('long', $long);
            }
        }
    }
}