PluginProbe ʕ •ᴥ•ʔ
Matomo Analytics – Powerful, Privacy-First Insights for WordPress / 5.0.7
Matomo Analytics – Powerful, Privacy-First Insights for WordPress v5.0.7
5.12.0 5.11.1 5.11.0 5.10.2 5.10.1 trunk 1.0.2 1.0.3 1.0.4 1.0.5 1.0.6 1.1.0 1.1.1 1.1.2 1.1.3 1.2.0 1.3.0 1.3.1 1.3.2 4.0.0 4.0.1 4.0.2 4.0.3 4.0.4 4.1.0 4.1.1 4.1.2 4.1.3 4.10.0 4.11.0 4.12.0 4.13.0 4.13.2 4.13.3 4.13.4 4.13.5 4.14.0 4.14.1 4.14.2 4.15.0 4.15.1 4.15.2 4.15.3 4.2.0 4.3.0 4.3.1 4.4.1 4.4.2 4.5.0 4.6.0 5.0.1 5.0.2 5.0.3 5.0.4 5.0.5 5.0.6 5.0.7 5.0.8 5.1.0 5.1.1 5.1.2 5.1.3 5.1.4 5.1.5 5.1.6 5.1.7 5.10.0 5.2.0 5.2.1 5.2.2 5.3.0 5.3.1 5.3.2 5.3.3 5.6.0 5.6.1 5.7.0 5.7.1 5.8.0 5.8.1 5.8.2
matomo / app / core / ArchiveProcessor.php
matomo / app / core Last commit date
API 2 years ago Access 2 years ago Application 2 years ago Archive 2 years ago ArchiveProcessor 2 years ago Archiver 2 years ago AssetManager 2 years ago Auth 2 years ago Category 2 years ago Changes 2 years ago CliMulti 2 years ago Columns 2 years ago Concurrency 2 years ago Config 2 years ago Container 2 years ago CronArchive 2 years ago DataAccess 2 years ago DataFiles 2 years ago DataTable 2 years ago Db 2 years ago DeviceDetector 2 years ago Email 2 years ago Exception 2 years ago Http 2 years ago Intl 2 years ago Log 2 years ago Mail 2 years ago Measurable 2 years ago Menu 2 years ago Metrics 2 years ago Notification 2 years ago Period 2 years ago Plugin 2 years ago ProfessionalServices 2 years ago Report 2 years ago ReportRenderer 2 years ago Scheduler 2 years ago Segment 2 years ago Session 2 years ago Settings 2 years ago Tracker 2 years ago Translation 2 years ago Twig 2 years ago UpdateCheck 2 years ago Updater 2 years ago Updates 2 years ago Validators 2 years ago View 2 years ago ViewDataTable 2 years ago Visualization 2 years ago Widget 2 years ago .htaccess 2 years ago Access.php 2 years ago Archive.php 2 years ago ArchiveProcessor.php 2 years ago AssetManager.php 2 years ago Auth.php 2 years ago AuthResult.php 2 years ago BaseFactory.php 2 years ago Cache.php 2 years ago CacheId.php 2 years ago CliMulti.php 2 years ago Common.php 2 years ago Config.php 2 years ago Console.php 2 years ago Context.php 2 years ago Cookie.php 2 years ago CronArchive.php 2 years ago DI.php 2 years ago DataArray.php 2 years ago DataTable.php 2 years ago Date.php 2 years ago Db.php 2 years ago DbHelper.php 2 years ago Development.php 2 years ago ErrorHandler.php 2 years ago EventDispatcher.php 2 years ago ExceptionHandler.php 2 years ago FileIntegrity.php 2 years ago Filechecks.php 2 years ago Filesystem.php 2 years ago FrontController.php 2 years ago Http.php 2 years ago IP.php 2 years ago Log.php 2 years ago LogDeleter.php 2 years ago Mail.php 2 years ago Metrics.php 2 years ago NoAccessException.php 2 years ago Nonce.php 2 years ago Notification.php 2 years ago NumberFormatter.php 2 years ago Option.php 2 years ago Period.php 2 years ago Piwik.php 2 years ago Plugin.php 2 years ago Profiler.php 2 years ago ProxyHeaders.php 2 years ago ProxyHttp.php 2 years ago QuickForm2.php 2 years ago RankingQuery.php 2 years ago ReportRenderer.php 2 years ago Request.php 2 years ago Segment.php 2 years ago Sequence.php 2 years ago Session.php 2 years ago SettingsPiwik.php 2 years ago SettingsServer.php 2 years ago Singleton.php 2 years ago Site.php 2 years ago SiteContentDetector.php 2 years ago SupportedBrowser.php 2 years ago TCPDF.php 2 years ago Theme.php 2 years ago Timer.php 2 years ago Tracker.php 2 years ago Twig.php 2 years ago Unzip.php 2 years ago UpdateCheck.php 2 years ago Updater.php 2 years ago UpdaterErrorException.php 2 years ago Updates.php 2 years ago Url.php 2 years ago UrlHelper.php 2 years ago Version.php 2 years ago View.php 2 years ago bootstrap.php 2 years ago dispatch.php 2 years ago testMinimumPhpVersion.php 2 years ago
ArchiveProcessor.php
669 lines
1 <?php
2
3 /**
4 * Matomo - free/libre analytics platform
5 *
6 * @link https://matomo.org
7 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
8 *
9 */
10 namespace Piwik;
11
12 use Exception;
13 use Piwik\Archive\DataTableFactory;
14 use Piwik\ArchiveProcessor\Parameters;
15 use Piwik\ArchiveProcessor\Rules;
16 use Piwik\Container\StaticContainer;
17 use Piwik\DataAccess\ArchiveWriter;
18 use Piwik\DataAccess\LogAggregator;
19 use Piwik\DataTable\Manager;
20 use Piwik\DataTable\Map;
21 use Piwik\DataTable\Row;
22 use Piwik\Segment\SegmentExpression;
23 use Piwik\Log\LoggerInterface;
24 /**
25 * Used by {@link Piwik\Plugin\Archiver} instances to insert and aggregate archive data.
26 *
27 * ### See also
28 *
29 * - **{@link Piwik\Plugin\Archiver}** - to learn how plugins should implement their own analytics
30 * aggregation logic.
31 * - **{@link Piwik\DataAccess\LogAggregator}** - to learn how plugins can perform data aggregation
32 * across Piwik's log tables.
33 *
34 * ### Examples
35 *
36 * **Inserting numeric data**
37 *
38 * // function in an Archiver descendant
39 * public function aggregateDayReport()
40 * {
41 * $archiveProcessor = $this->getProcessor();
42 *
43 * $myFancyMetric = // ... calculate the metric value ...
44 * $archiveProcessor->insertNumericRecord('MyPlugin_myFancyMetric', $myFancyMetric);
45 * }
46 *
47 * **Inserting serialized DataTables**
48 *
49 * // function in an Archiver descendant
50 * public function aggregateDayReport()
51 * {
52 * $archiveProcessor = $this->getProcessor();
53 *
54 * $maxRowsInTable = Config::getInstance()->General['datatable_archiving_maximum_rows_standard'];j
55 *
56 * $dataTable = // ... build by aggregating visits ...
57 * $serializedData = $dataTable->getSerialized($maxRowsInTable, $maxRowsInSubtable = $maxRowsInTable,
58 * $columnToSortBy = Metrics::INDEX_NB_VISITS);
59 *
60 * $archiveProcessor->insertBlobRecords('MyPlugin_myFancyReport', $serializedData);
61 * }
62 *
63 * **Aggregating archive data**
64 *
65 * // function in Archiver descendant
66 * public function aggregateMultipleReports()
67 * {
68 * $archiveProcessor = $this->getProcessor();
69 *
70 * // aggregate a metric
71 * $archiveProcessor->aggregateNumericMetrics('MyPlugin_myFancyMetric');
72 * $archiveProcessor->aggregateNumericMetrics('MyPlugin_mySuperFancyMetric', 'max');
73 *
74 * // aggregate a report
75 * $archiveProcessor->aggregateDataTableRecords('MyPlugin_myFancyReport');
76 * }
77 *
78 */
79 class ArchiveProcessor
80 {
81 /**
82 * @var bool
83 */
84 public static $isRootArchivingRequest = true;
85 /**
86 * @var \Piwik\DataAccess\ArchiveWriter
87 */
88 private $archiveWriter;
89 /**
90 * @var \Piwik\DataAccess\LogAggregator
91 */
92 private $logAggregator;
93 /**
94 * @var Archive
95 */
96 public $archive = null;
97 /**
98 * @var Parameters
99 */
100 private $params;
101 /**
102 * @var int
103 */
104 private $numberOfVisits = false;
105 private $numberOfVisitsConverted = false;
106 public function __construct(Parameters $params, ArchiveWriter $archiveWriter, LogAggregator $logAggregator)
107 {
108 $this->params = $params;
109 $this->logAggregator = $logAggregator;
110 $this->archiveWriter = $archiveWriter;
111 }
112 protected function getArchive()
113 {
114 if (empty($this->archive)) {
115 $subPeriods = $this->params->getSubPeriods();
116 $idSites = $this->params->getIdSites();
117 $this->archive = \Piwik\Archive::factory($this->params->getSegment(), $subPeriods, $idSites);
118 /**
119 * @internal
120 */
121 \Piwik\Piwik::postEvent('ArchiveProcessor.getArchive', [$this->archive]);
122 }
123 return $this->archive;
124 }
125 public function setNumberOfVisits($visits, $visitsConverted)
126 {
127 $this->numberOfVisits = $visits;
128 $this->numberOfVisitsConverted = $visitsConverted;
129 }
130 /**
131 * Returns the {@link Parameters} object containing the site, period and segment we're archiving
132 * data for.
133 *
134 * @return Parameters
135 * @api
136 */
137 public function getParams()
138 {
139 return $this->params;
140 }
141 /**
142 * Returns a `{@link Piwik\DataAccess\LogAggregator}` instance for the site, period and segment this
143 * ArchiveProcessor will insert archive data for.
144 *
145 * @return LogAggregator
146 * @api
147 */
148 public function getLogAggregator()
149 {
150 return $this->logAggregator;
151 }
152 /**
153 * Array of (column name before => column name renamed) of the columns for which sum operation is invalid.
154 * These columns will be renamed as per this mapping.
155 * @var array
156 */
157 protected static $columnsToRenameAfterAggregation = array(\Piwik\Metrics::INDEX_NB_UNIQ_VISITORS => \Piwik\Metrics::INDEX_SUM_DAILY_NB_UNIQ_VISITORS, \Piwik\Metrics::INDEX_NB_USERS => \Piwik\Metrics::INDEX_SUM_DAILY_NB_USERS);
158 /**
159 * Sums records for every subperiod of the current period and inserts the result as the record
160 * for this period.
161 *
162 * DataTables are summed recursively so subtables will be summed as well.
163 *
164 * @param string|array $recordNames Name(s) of the report we are aggregating, eg, `'Referrers_type'`.
165 * @param int $maximumRowsInDataTableLevelZero Maximum number of rows allowed in the top level DataTable.
166 * @param int $maximumRowsInSubDataTable Maximum number of rows allowed in each subtable.
167 * @param string|null $defaultColumnToSortByBeforeTruncation The name of the column to sort by before truncating a DataTable.
168 * If not set, and the table contains nb_visits or INDEX_NB_VISITS, we will
169 * sort by visits.
170 * @param array $columnsAggregationOperation Operations for aggregating columns, see {@link Row::sumRow()}.
171 * @param array $columnsToRenameAfterAggregation Columns mapped to new names for columns that must change names
172 * when summed because they cannot be summed, eg,
173 * `array('nb_uniq_visitors' => 'sum_daily_nb_uniq_visitors')`.
174 * @param bool|array $countRowsRecursive if set to true, will calculate the recursive rows count for all record names
175 * which makes it slower. If you only need it for some records pass an array of
176 * recordNames that defines for which ones you need a recursive row count.
177 * @return array Returns the row counts of each aggregated report before truncation, eg,
178 *
179 * array(
180 * 'report1' => array('level0' => $report1->getRowsCount,
181 * 'recursive' => $report1->getRowsCountRecursive()),
182 * 'report2' => array('level0' => $report2->getRowsCount,
183 * 'recursive' => $report2->getRowsCountRecursive()),
184 * ...
185 * )
186 * @api
187 */
188 public function aggregateDataTableRecords($recordNames, $maximumRowsInDataTableLevelZero = null, $maximumRowsInSubDataTable = null, $defaultColumnToSortByBeforeTruncation = null, &$columnsAggregationOperation = null, $columnsToRenameAfterAggregation = null, $countRowsRecursive = true)
189 {
190 /** @var LoggerInterface $logger */
191 $logger = StaticContainer::get(LoggerInterface::class);
192 if (!is_array($recordNames)) {
193 $recordNames = array($recordNames);
194 }
195 $archiveDescription = $this->params . '';
196 $nameToCount = array();
197 foreach ($recordNames as $recordName) {
198 $latestUsedTableId = Manager::getInstance()->getMostRecentTableId();
199 $logger->debug("aggregating record {record} [archive = {archive}]", ['record' => $recordName, 'archive' => $archiveDescription]);
200 $table = $this->aggregateDataTableRecord($recordName, $columnsAggregationOperation, $columnsToRenameAfterAggregation);
201 $nameToCount[$recordName]['level0'] = $table->getRowsCount();
202 if ($countRowsRecursive === true || is_array($countRowsRecursive) && in_array($recordName, $countRowsRecursive)) {
203 $nameToCount[$recordName]['recursive'] = $table->getRowsCountRecursive();
204 }
205 $columnToSortByBeforeTruncation = $defaultColumnToSortByBeforeTruncation;
206 if (empty($columnToSortByBeforeTruncation)) {
207 $columns = $table->getColumns();
208 if (in_array(\Piwik\Metrics::INDEX_NB_VISITS, $columns)) {
209 $columnToSortByBeforeTruncation = \Piwik\Metrics::INDEX_NB_VISITS;
210 } else {
211 if (in_array('nb_visits', $columns)) {
212 $columnToSortByBeforeTruncation = 'nb_visits';
213 }
214 }
215 }
216 $blob = $table->getSerialized($maximumRowsInDataTableLevelZero, $maximumRowsInSubDataTable, $columnToSortByBeforeTruncation);
217 \Piwik\Common::destroy($table);
218 $this->insertBlobRecord($recordName, $blob);
219 unset($blob);
220 \Piwik\DataTable\Manager::getInstance()->deleteAll($latestUsedTableId);
221 }
222 return $nameToCount;
223 }
224 /**
225 * Aggregates one or more metrics for every subperiod of the current period and inserts the results
226 * as metrics for the current period.
227 *
228 * @param array|string $columns Array of metric names to aggregate.
229 * @param bool|string|string[] $operationToApply The operation to apply to the metric. Either `'sum'`, `'max'` or `'min'`.
230 * Can also be an array mapping record names to operations.
231 * @return array|int Returns the array of aggregate values. If only one metric was aggregated,
232 * the aggregate value will be returned as is, not in an array.
233 * For example, if `array('nb_visits', 'nb_hits')` is supplied for `$columns`,
234 *
235 * array(
236 * 'nb_visits' => 3040,
237 * 'nb_hits' => 405
238 * )
239 *
240 * could be returned. If `array('nb_visits')` or `'nb_visits'` is used for `$columns`,
241 * then `3040` would be returned.
242 * @api
243 */
244 public function aggregateNumericMetrics($columns, $operationsToApply = false)
245 {
246 $metrics = $this->getAggregatedNumericMetrics($columns, $operationsToApply);
247 foreach ($metrics as $column => $value) {
248 $this->insertNumericRecord($column, $value);
249 }
250 // if asked for only one field to sum
251 if (count($metrics) === 1) {
252 return reset($metrics);
253 }
254 // returns the array of records once summed
255 return $metrics;
256 }
257 public function getNumberOfVisits()
258 {
259 if ($this->numberOfVisits === false) {
260 throw new Exception("visits should have been set here");
261 }
262 return $this->numberOfVisits;
263 }
264 public function getNumberOfVisitsConverted()
265 {
266 return $this->numberOfVisitsConverted;
267 }
268 /**
269 * Caches multiple numeric records in the archive for this processor's site, period
270 * and segment.
271 *
272 * @param array $numericRecords A name-value mapping of numeric values that should be
273 * archived, eg,
274 *
275 * array('Referrers_distinctKeywords' => 23, 'Referrers_distinctCampaigns' => 234)
276 * @api
277 */
278 public function insertNumericRecords($numericRecords)
279 {
280 foreach ($numericRecords as $name => $value) {
281 $this->insertNumericRecord($name, $value);
282 }
283 }
284 /**
285 * Caches a single numeric record in the archive for this processor's site, period and
286 * segment.
287 *
288 * Numeric values are not inserted if they equal `0`.
289 *
290 * @param string $name The name of the numeric value, eg, `'Referrers_distinctKeywords'`.
291 * @param float $value The numeric value.
292 * @api
293 */
294 public function insertNumericRecord($name, $value)
295 {
296 $value = round($value ?? 0, 2);
297 $value = \Piwik\Common::forceDotAsSeparatorForDecimalPoint($value);
298 $this->archiveWriter->insertRecord($name, $value);
299 }
300 /**
301 * Caches one or more blob records in the archive for this processor's site, period
302 * and segment.
303 *
304 * @param string $name The name of the record, eg, 'Referrers_type'.
305 * @param string|array $values A blob string or an array of blob strings. If an array
306 * is used, the first element in the array will be inserted
307 * with the `$name` name. The others will be inserted with
308 * `$name . '_' . $index` as the record name (where $index is
309 * the index of the blob record in `$values`).
310 * @api
311 */
312 public function insertBlobRecord($name, $values)
313 {
314 $this->archiveWriter->insertBlobRecord($name, $values);
315 }
316 /**
317 * This method selects all DataTables that have the name $name over the period.
318 * All these DataTables are then added together, and the resulting DataTable is returned.
319 *
320 * @param string $name
321 * @param array $columnsAggregationOperation Operations for aggregating columns, @see Row::sumRow()
322 * @param array $columnsToRenameAfterAggregation columns in the array (old name, new name) to be renamed as the sum operation is not valid on them (eg. nb_uniq_visitors->sum_daily_nb_uniq_visitors)
323 * @return DataTable
324 */
325 protected function aggregateDataTableRecord($name, $columnsAggregationOperation = null, $columnsToRenameAfterAggregation = null)
326 {
327 try {
328 \Piwik\ErrorHandler::pushFatalErrorBreadcrumb(__CLASS__, ['name' => $name]);
329 $blobs = $this->getArchive()->querySingleBlob($name);
330 $dataTable = $this->getAggregatedDataTableMapFromBlobs($blobs, $columnsAggregationOperation, $columnsToRenameAfterAggregation, $name);
331 } finally {
332 \Piwik\ErrorHandler::popFatalErrorBreadcrumb();
333 }
334 return $dataTable;
335 }
336 protected function getAggregatedDataTableMapFromBlobs(\Iterator $dataTableBlobs, $columnsAggregationOperation, $columnsToRenameAfterAggregation, $name)
337 {
338 // maps period & subtable ID in database to the Row instance in $result that subtable should be added to when encountered
339 // [$row['date1'].','.$row['date2']][$tableId] = $row in $result
340 /** @var Row[][] */
341 $tableIdToResultRowMapping = [];
342 $result = new \Piwik\DataTable();
343 if (!empty($columnsAggregationOperation)) {
344 $result->setMetadata(\Piwik\DataTable::COLUMN_AGGREGATION_OPS_METADATA_NAME, $columnsAggregationOperation);
345 }
346 foreach ($dataTableBlobs as $archiveDataRow) {
347 $period = $archiveDataRow['date1'] . ',' . $archiveDataRow['date2'];
348 $tableId = $archiveDataRow['name'] == $name ? null : $this->getSubtableIdFromBlobName($archiveDataRow['name']);
349 $blobTable = \Piwik\DataTable::fromSerializedArray($archiveDataRow['value']);
350 // see https://github.com/piwik/piwik/issues/4377
351 $blobTable->filter(function ($table) use($columnsToRenameAfterAggregation, $name) {
352 if ($this->areColumnsNotAlreadyRenamed($table)) {
353 /**
354 * This makes archiving and range dates a lot faster. Imagine we archive a week, then we will
355 * rename all columns of each 7 day archives. Afterwards we know the columns will be replaced in a
356 * week archive. When generating month archives, which uses mostly week archives, we do not have
357 * to replace those columns for the week archives again since we can be sure they were already
358 * replaced. Same when aggregating year and range archives. This can save up 10% or more when
359 * aggregating Month, Year and Range archives.
360 */
361 $this->renameColumnsAfterAggregation($table, $columnsToRenameAfterAggregation);
362 }
363 });
364 $tableToAddTo = null;
365 if ($tableId === null) {
366 $tableToAddTo = $result;
367 } else {
368 if (empty($tableIdToResultRowMapping[$period][$tableId])) {
369 // sanity check
370 StaticContainer::get(LoggerInterface::class)->info('Unexpected state when aggregating DataTable, unknown period/table ID combination encountered: {period} - {tableId}.' . ' This either means the SQL to order blobs is behaving incorrectly or the blob data is corrupt in some way.', ['period' => $period, 'tableId' => $tableId]);
371 continue;
372 } else {
373 $rowToAddTo = $tableIdToResultRowMapping[$period][$tableId];
374 if (!$rowToAddTo->getIdSubDataTable()) {
375 $newTable = new \Piwik\DataTable();
376 $newTable->setMetadata(\Piwik\DataTable::COLUMN_AGGREGATION_OPS_METADATA_NAME, $columnsAggregationOperation);
377 $rowToAddTo->setSubtable($newTable);
378 }
379 $tableToAddTo = $rowToAddTo->getSubtable();
380 }
381 }
382 $tableToAddTo->addDataTable($blobTable);
383 // add subtable IDs for $blobTableRow to $tableIdToResultRowMapping
384 foreach ($blobTable->getRows() as $blobTableRow) {
385 $label = $blobTableRow->getColumn('label');
386 $subtableId = $blobTableRow->getIdSubDataTable();
387 if (empty($subtableId)) {
388 continue;
389 }
390 $rowToAddTo = $tableToAddTo->getRowFromLabel($label);
391 $tableIdToResultRowMapping[$period][$subtableId] = $rowToAddTo;
392 }
393 \Piwik\Common::destroy($blobTable);
394 unset($blobTable);
395 }
396 return $result;
397 }
398 private function getSubtableIdFromBlobName($recordName)
399 {
400 $parts = explode('_', $recordName);
401 $id = end($parts);
402 if (is_numeric($id)) {
403 return $id;
404 }
405 return null;
406 }
407 /**
408 * Note: public only for use in closure in PHP 5.3.
409 *
410 * @param $table
411 * @return \Piwik\Period
412 */
413 public function areColumnsNotAlreadyRenamed($table)
414 {
415 $period = $table->getMetadata(DataTableFactory::TABLE_METADATA_PERIOD_INDEX);
416 return !$period || $period->getLabel() === 'day';
417 }
418 protected function getOperationForColumns($columns, $defaultOperation)
419 {
420 $operationForColumn = array();
421 foreach ($columns as $name) {
422 $operation = is_array($defaultOperation) ? $defaultOperation[$name] ?? null : $defaultOperation;
423 if (empty($operation)) {
424 $operation = $this->guessOperationForColumn($name);
425 }
426 $operationForColumn[$name] = $operation;
427 }
428 return $operationForColumn;
429 }
430 protected function enrichWithUniqueVisitorsMetric(Row $row)
431 {
432 if ($row->getColumn('nb_uniq_visitors') === false && $row->getColumn('nb_users') === false) {
433 return;
434 }
435 $periodLabel = $this->getParams()->getPeriod()->getLabel();
436 if (!\Piwik\SettingsPiwik::isUniqueVisitorsEnabled($periodLabel)) {
437 $row->deleteColumn('nb_uniq_visitors');
438 $row->deleteColumn('nb_users');
439 return;
440 }
441 $sites = $this->getIdSitesToComputeNbUniques();
442 if (count($sites) > 1 && Rules::shouldSkipUniqueVisitorsCalculationForMultipleSites()) {
443 if ($periodLabel != 'day') {
444 // for day we still keep the aggregated metric but for other periods we remove it as it becomes to
445 // inaccurate
446 $row->deleteColumn('nb_uniq_visitors');
447 $row->deleteColumn('nb_users');
448 }
449 return;
450 }
451 if (empty($sites)) {
452 // a plugin disabled running below query by removing all sites.
453 $row->deleteColumn('nb_uniq_visitors');
454 $row->deleteColumn('nb_users');
455 return;
456 }
457 if (count($sites) === 1) {
458 $uniqueVisitorsMetric = \Piwik\Metrics::INDEX_NB_UNIQ_VISITORS;
459 } else {
460 if (!\Piwik\SettingsPiwik::isSameFingerprintAcrossWebsites()) {
461 throw new Exception("Processing unique visitors across websites is enabled for this instance,\n but to process this metric you must first set enable_fingerprinting_across_websites=1\n in the config file, under the [Tracker] section.");
462 }
463 $uniqueVisitorsMetric = \Piwik\Metrics::INDEX_NB_UNIQ_FINGERPRINTS;
464 }
465 $metrics = array(\Piwik\Metrics::INDEX_NB_USERS, $uniqueVisitorsMetric);
466 $uniques = $this->computeNbUniques($metrics, $sites);
467 // see edge case as described in https://github.com/piwik/piwik/issues/9357 where uniq_visitors might be higher
468 // than visits because we archive / process it after nb_visits. Between archiving nb_visits and nb_uniq_visitors
469 // there could have been a new visit leading to a higher nb_unique_visitors than nb_visits which is not possible
470 // by definition. In this case we simply use the visits metric instead of unique visitors metric.
471 $visits = $row->getColumn('nb_visits');
472 if ($visits !== false && $uniques[$uniqueVisitorsMetric] !== false) {
473 $uniques[$uniqueVisitorsMetric] = min($uniques[$uniqueVisitorsMetric], $visits);
474 }
475 $row->setColumn('nb_uniq_visitors', $uniques[$uniqueVisitorsMetric]);
476 $row->setColumn('nb_users', $uniques[\Piwik\Metrics::INDEX_NB_USERS]);
477 }
478 protected function guessOperationForColumn($column)
479 {
480 if (strpos($column, 'max_') === 0) {
481 return 'max';
482 }
483 if (strpos($column, 'min_') === 0) {
484 return 'min';
485 }
486 return 'sum';
487 }
488 private function getIdSitesToComputeNbUniques()
489 {
490 $params = $this->getParams();
491 $sites = array($params->getSite()->getId());
492 /**
493 * Triggered to change which site ids should be looked at when processing unique visitors and users.
494 *
495 * @param array &$idSites An array with one idSite. This site is being archived currently. To cancel the query
496 * you can change this value to an empty array. To include other sites in the query you
497 * can add more idSites to this list of idSites.
498 * @param Period $period The period that is being requested to be archived.
499 * @param Segment $segment The segment that is request to be archived.
500 */
501 \Piwik\Piwik::postEvent('ArchiveProcessor.ComputeNbUniques.getIdSites', array(&$sites, $params->getPeriod(), $params->getSegment()));
502 return $sites;
503 }
504 /**
505 * Processes number of unique visitors for the given period
506 *
507 * This is the only Period metric (ie. week/month/year/range) that we process from the logs directly,
508 * since unique visitors cannot be summed like other metrics.
509 *
510 * @param array $metrics Metrics Ids for which to aggregates count of values
511 * @param int[] $sites A list of idSites that should be included
512 * @return array|null An array of metrics, where the key is metricid and the value is the metric value or null if
513 * the query was cancelled and not executed.
514 */
515 protected function computeNbUniques($metrics, $sites)
516 {
517 $logAggregator = $this->getLogAggregator();
518 $sitesBackup = $logAggregator->getSites();
519 $logAggregator->setSites($sites);
520 try {
521 $query = $logAggregator->queryVisitsByDimension(array(), false, array(), $metrics);
522 } finally {
523 $logAggregator->setSites($sitesBackup);
524 }
525 $data = $query->fetch();
526 return $data;
527 }
528 /**
529 * If the DataTable is a Map, sums all DataTable in the map and return the DataTable.
530 *
531 *
532 * @param $data DataTable|DataTable\Map
533 * @param $columnsToRenameAfterAggregation array
534 * @return DataTable
535 */
536 protected function getAggregatedDataTableMap($data, $columnsAggregationOperation)
537 {
538 $table = new \Piwik\DataTable();
539 if (!empty($columnsAggregationOperation)) {
540 $table->setMetadata(\Piwik\DataTable::COLUMN_AGGREGATION_OPS_METADATA_NAME, $columnsAggregationOperation);
541 }
542 if ($data instanceof \Piwik\DataTable\Map) {
543 // as $date => $tableToSum
544 $this->aggregatedDataTableMapsAsOne($data, $table);
545 } else {
546 $table->addDataTable($data);
547 }
548 return $table;
549 }
550 /**
551 * Aggregates the DataTable\Map into the destination $aggregated
552 * @param $map
553 * @param $aggregated
554 */
555 protected function aggregatedDataTableMapsAsOne(Map $map, \Piwik\DataTable $aggregated)
556 {
557 foreach ($map->getDataTables() as $tableToAggregate) {
558 if ($tableToAggregate instanceof Map) {
559 $this->aggregatedDataTableMapsAsOne($tableToAggregate, $aggregated);
560 } else {
561 $aggregated->addDataTable($tableToAggregate);
562 }
563 }
564 }
565 /**
566 * Note: public only for use in closure in PHP 5.3.
567 */
568 public function renameColumnsAfterAggregation(\Piwik\DataTable $table, $columnsToRenameAfterAggregation = null)
569 {
570 // Rename columns after aggregation
571 if (is_null($columnsToRenameAfterAggregation)) {
572 $columnsToRenameAfterAggregation = self::$columnsToRenameAfterAggregation;
573 }
574 if (empty($columnsToRenameAfterAggregation)) {
575 return;
576 }
577 foreach ($table->getRows() as $row) {
578 foreach ($columnsToRenameAfterAggregation as $oldName => $newName) {
579 $row->renameColumn($oldName, $newName);
580 }
581 $subTable = $row->getSubtable();
582 if ($subTable) {
583 $this->renameColumnsAfterAggregation($subTable, $columnsToRenameAfterAggregation);
584 }
585 }
586 }
587 protected function getAggregatedNumericMetrics($columns, $operationsToApply)
588 {
589 if (!is_array($columns)) {
590 $columns = array($columns);
591 }
592 $operationForColumn = $this->getOperationForColumns($columns, $operationsToApply);
593 $dataTable = $this->getArchive()->getDataTableFromNumeric($columns);
594 $results = $this->getAggregatedDataTableMap($dataTable, $operationForColumn);
595 if ($results->getRowsCount() > 1) {
596 throw new Exception("A DataTable is an unexpected state:" . var_export($results, true));
597 }
598 $rowMetrics = $results->getFirstRow();
599 if ($rowMetrics === false) {
600 $rowMetrics = new Row();
601 }
602 $this->enrichWithUniqueVisitorsMetric($rowMetrics);
603 $this->renameColumnsAfterAggregation($results, self::$columnsToRenameAfterAggregation);
604 $metrics = $rowMetrics->getColumns();
605 foreach ($columns as $name) {
606 if (!isset($metrics[$name])) {
607 $metrics[$name] = 0;
608 }
609 }
610 return $metrics;
611 }
612 /**
613 * Initiate archiving for a plugin during an ongoing archiving. The plugin can be another
614 * plugin or the same plugin.
615 *
616 * This method should be called during archiving when one plugin uses the report of another
617 * plugin with a segment. It will ensure reports for that segment & plugin will be archived
618 * without initiating archiving for every plugin with that segment (which would be a performance
619 * killer).
620 *
621 * @param string $plugin
622 * @param string $segment
623 */
624 public function processDependentArchive($plugin, $segment)
625 {
626 if (!self::$isRootArchivingRequest) {
627 // prevent all recursion
628 return;
629 }
630 $params = $this->getParams();
631 // range archives are always processed on demand, so pre-processing dependent archives is not required
632 // here
633 if (Rules::shouldProcessOnlyReportsRequestedInArchiveQuery($params->getPeriod()->getLabel())) {
634 return;
635 }
636 $idSites = [$params->getSite()->getId()];
637 // important to use the original segment string when combining. As the API itself would combine the original string.
638 // this prevents a bug where the API would use the segment
639 // userId!@%2540matomo.org;userId!=hello%2540matomo.org;visitorType==new
640 // vs here we would use
641 // userId!@%40matomo.org;userId!=hello%40matomo.org;visitorType==new
642 // thus these would result in different segment hashes and therefore the reports would either show 0 or archive the data twice
643 $originSegmentString = $params->getSegment()->getOriginalString();
644 $newSegment = \Piwik\Segment::combine($originSegmentString, SegmentExpression::AND_DELIMITER, $segment);
645 if (!empty($originSegmentString) && $newSegment === $segment && $params->getRequestedPlugin() === $plugin) {
646 // being processed now
647 return;
648 }
649 $newSegment = new \Piwik\Segment($newSegment, $idSites, $params->getDateTimeStart(), $params->getDateTimeEnd());
650 if (\Piwik\ArchiveProcessor\Rules::isSegmentPreProcessed($idSites, $newSegment)) {
651 // will be processed anyway
652 return;
653 }
654 self::$isRootArchivingRequest = false;
655 try {
656 $parameters = new \Piwik\ArchiveProcessor\Parameters($params->getSite(), $params->getPeriod(), $newSegment);
657 $parameters->onlyArchiveRequestedPlugin();
658 $archiveLoader = new \Piwik\ArchiveProcessor\Loader($parameters);
659 $archiveLoader->prepareArchive($plugin);
660 } finally {
661 self::$isRootArchivingRequest = true;
662 }
663 }
664 public function getArchiveWriter()
665 {
666 return $this->archiveWriter;
667 }
668 }
669