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

Archiver.php « CustomDimensions « plugins - github.com/matomo-org/matomo.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 1eb35dccfeb918bf74bef1b544c1d087525212e4 (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
<?php
/**
 * Matomo - free/libre analytics platform
 *
 * @link https://matomo.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 */
namespace Piwik\Plugins\CustomDimensions;

use Piwik\Config;
use Piwik\Metrics;
use Piwik\Plugins\Actions\Metrics as ActionsMetrics;
use Piwik\Plugins\CustomDimensions\Dao\Configuration;
use Piwik\Plugins\CustomDimensions\Dao\LogTable;
use Piwik\Tracker;
use Piwik\ArchiveProcessor;

/**
 * Archives reports for each active Custom Dimension of a website.
 */
class Archiver extends \Piwik\Plugin\Archiver
{
    const LABEL_CUSTOM_VALUE_NOT_DEFINED = "Value not defined";
    private $recordNames = array();

    /**
     * @var DataArray
     */
    protected $dataArray;
    protected $maximumRowsInDataTableLevelZero;
    protected $maximumRowsInSubDataTable;

    /**
     * @var ArchiveProcessor
     */
    private $processor;

    function __construct($processor)
    {
        parent::__construct($processor);

        $this->processor = $processor;

        $this->maximumRowsInDataTableLevelZero = Config::getInstance()->General['datatable_archiving_maximum_rows_custom_variables'];
        $this->maximumRowsInSubDataTable = Config::getInstance()->General['datatable_archiving_maximum_rows_subtable_custom_variables'];
    }

    public static function buildRecordNameForCustomDimensionId($id)
    {
        return 'CustomDimensions_Dimension' . (int) $id;
    }

    private function getRecordNames()
    {
        if (!empty($this->recordNames)) {
            return $this->recordNames;
        }

        $dimensions = $this->getActiveCustomDimensions();

        foreach ($dimensions as $dimension) {
            $this->recordNames[] = self::buildRecordNameForCustomDimensionId($dimension['idcustomdimension']);
        }

        return $this->recordNames;
    }

    private function getActiveCustomDimensions()
    {
        $idSite = $this->processor->getParams()->getSite()->getId();

        $config = new Configuration();
        $dimensions = $config->getCustomDimensionsForSite($idSite);

        $active = array();
        foreach ($dimensions as $index => $dimension) {
            if ($dimension['active']) {
                $active[] = $dimension;
            }
        }

        return $active;
    }

    public function aggregateMultipleReports()
    {
        $columnsAggregationOperation = null;

        $this->getProcessor()->aggregateDataTableRecords(
            $this->getRecordNames(),
            $this->maximumRowsInDataTableLevelZero,
            $this->maximumRowsInSubDataTable,
            $columnToSort = Metrics::INDEX_NB_VISITS,
            $columnsAggregationOperation,
            $columnsToRenameAfterAggregation = null,
            $countRowsRecursive = array());
    }

    public function aggregateDayReport()
    {
        $dimensions = $this->getActiveCustomDimensions();
        foreach ($dimensions as $dimension) {
            $this->dataArray = new DataArray();

            $valueField = LogTable::buildCustomDimensionColumnName($dimension);
            $dimensions = array($valueField);

            if ($dimension['scope'] === CustomDimensions::SCOPE_VISIT) {
                $this->aggregateFromVisits($valueField, $dimensions, " log_visit.$valueField is not null");
                $this->aggregateFromConversions($valueField, $dimensions, " log_conversion.$valueField is not null");
            } elseif ($dimension['scope'] === CustomDimensions::SCOPE_ACTION) {
                $this->aggregateFromActions($valueField);
            }

            $this->dataArray->enrichMetricsWithConversions();
            $table = $this->dataArray->asDataTable();

            $blob = $table->getSerialized(
                $this->maximumRowsInDataTableLevelZero, $this->maximumRowsInSubDataTable,
                $columnToSort = Metrics::INDEX_NB_VISITS
            );

            $recordName = self::buildRecordNameForCustomDimensionId($dimension['idcustomdimension']);
            $this->getProcessor()->insertBlobRecord($recordName, $blob);
        }
    }

    protected function aggregateFromVisits($valueField, $dimensions, $where)
    {
        $query = $this->getLogAggregator()->queryVisitsByDimension($dimensions, $where);

        while ($row = $query->fetch()) {
            $value = $this->cleanCustomDimensionValue($row[$valueField]);

            $this->dataArray->sumMetricsVisits($value, $row);
        }
    }

    protected function aggregateFromConversions($valueField, $dimensions, $where)
    {
        $query = $this->getLogAggregator()->queryConversionsByDimension($dimensions, $where);

        while ($row = $query->fetch()) {
            $value = $this->cleanCustomDimensionValue($row[$valueField]);

            $this->dataArray->sumMetricsGoals($value, $row);
        }
    }

    public function queryCustomDimensionActions(DataArray $dataArray, $valueField, $additionalWhere = '')
    {
        $metricsConfig = ActionsMetrics::getActionMetrics();

        $metricIds   = array_keys($metricsConfig);
        $metricIds[] = Metrics::INDEX_PAGE_SUM_TIME_SPENT;
        $metricIds[] = Metrics::INDEX_BOUNCE_COUNT;
        $metricIds[] = Metrics::INDEX_PAGE_EXIT_NB_VISITS;
        $dataArray->setActionMetricsIds($metricIds);

        $select = "log_link_visit_action.$valueField,
                  log_action.name as url,
                  sum(log_link_visit_action.time_spent) as `" . Metrics::INDEX_PAGE_SUM_TIME_SPENT . "`,
                  sum(case log_visit.visit_total_actions when 1 then 1 when 0 then 1 else 0 end) as `" . Metrics::INDEX_BOUNCE_COUNT . "`,
                  sum(IF(log_visit.last_idlink_va = log_link_visit_action.idlink_va, 1, 0)) as `" . Metrics::INDEX_PAGE_EXIT_NB_VISITS . "`";

        $select = $this->addMetricsToSelect($select, $metricsConfig);

        $from = array(
            "log_link_visit_action",
            array(
                "table"  => "log_visit",
                "joinOn" => "log_visit.idvisit = log_link_visit_action.idvisit"
            ),
            array(
                "table"  => "log_action",
                "joinOn" => "log_link_visit_action.idaction_url = log_action.idaction"
            )
        );

        $where  = $this->getLogAggregator()->getWhereStatement('log_link_visit_action', 'server_time');
        $where .= " AND log_link_visit_action.$valueField is not null";

        if (!empty($additionalWhere)) {
            $where .= ' AND ' . $additionalWhere;
        }

        $groupBy = "log_link_visit_action.$valueField, url";
        $orderBy = "`" . Metrics::INDEX_PAGE_NB_HITS . "` DESC";

        // get query with segmentation
        $logAggregator = $this->getLogAggregator();
        $query     = $logAggregator->generateQuery($select, $from, $where, $groupBy, $orderBy);
        $db        = $logAggregator->getDb();
        $resultSet = $db->query($query['sql'], $query['bind']);

        return $resultSet;
    }

    protected function aggregateFromActions($valueField)
    {
        $resultSet = $this->queryCustomDimensionActions($this->dataArray, $valueField);

        while ($row = $resultSet->fetch()) {
            $label = $row[$valueField];
            $label = $this->cleanCustomDimensionValue($label);

            $this->dataArray->sumMetricsActions($label, $row);

            // make sure we always work with normalized URL no matter how the individual action stores it
            $normalized = Tracker\PageUrl::normalizeUrl($row['url']);
            $row['url'] = $normalized['url'];

            $subLabel = $row['url'];

            if (empty($subLabel)) {
                continue;
            }

            $this->dataArray->sumMetricsActionCustomDimensionsPivot($label, $subLabel, $row);
        }
    }

    private function addMetricsToSelect($select, $metricsConfig)
    {
        if (!empty($metricsConfig)) {
            foreach ($metricsConfig as $metric => $config) {
                $select .= ', ' . $config['query'] . " as `" . $metric . "`";
            }
        }

        return $select;
    }

    protected function cleanCustomDimensionValue($value)
    {
        if (isset($value) && strlen($value)) {
            return $value;
        }

        return self::LABEL_CUSTOM_VALUE_NOT_DEFINED;
    }

}