PluginProbe ʕ •ᴥ•ʔ
Matomo Analytics – Powerful, Privacy-First Insights for WordPress / 4.13.3
Matomo Analytics – Powerful, Privacy-First Insights for WordPress v4.13.3
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 / DataAccess / ArchiveSelector.php
matomo / app / core / DataAccess Last commit date
LogQueryBuilder 3 years ago Actions.php 5 years ago ArchiveSelector.php 3 years ago ArchiveTableCreator.php 5 years ago ArchiveTableDao.php 5 years ago ArchiveWriter.php 3 years ago ArchivingDbAdapter.php 4 years ago LogAggregator.php 3 years ago LogQueryBuilder.php 5 years ago LogTableTemporary.php 5 years ago Model.php 3 years ago RawLogDao.php 4 years ago TableMetadata.php 5 years ago
ArchiveSelector.php
503 lines
1 <?php
2 /**
3 * Matomo - free/libre analytics platform
4 *
5 * @link https://matomo.org
6 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
7 *
8 */
9 namespace Piwik\DataAccess;
10
11 use Exception;
12 use Piwik\Archive;
13 use Piwik\Archive\Chunk;
14 use Piwik\ArchiveProcessor;
15 use Piwik\ArchiveProcessor\Rules;
16 use Piwik\Common;
17 use Piwik\Container\StaticContainer;
18 use Piwik\Date;
19 use Piwik\Db;
20 use Piwik\Period;
21 use Piwik\Period\Range;
22 use Piwik\Segment;
23 use Psr\Log\LoggerInterface;
24
25 /**
26 * Data Access object used to query archives
27 *
28 * A record in the Database for a given report is defined by
29 * - idarchive = unique ID that is associated to all the data of this archive (idsite+period+date)
30 * - idsite = the ID of the website
31 * - date1 = starting day of the period
32 * - date2 = ending day of the period
33 * - period = integer that defines the period (day/week/etc.). @see period::getId()
34 * - ts_archived = timestamp when the archive was processed (UTC)
35 * - name = the name of the report (ex: uniq_visitors or search_keywords_by_search_engines)
36 * - value = the actual data (a numeric value, or a blob of compressed serialized data)
37 *
38 */
39 class ArchiveSelector
40 {
41 const NB_VISITS_RECORD_LOOKED_UP = "nb_visits";
42
43 const NB_VISITS_CONVERTED_RECORD_LOOKED_UP = "nb_visits_converted";
44
45 private static function getModel()
46 {
47 return new Model();
48 }
49
50 /**
51 * @param ArchiveProcessor\Parameters $params
52 * @param bool $minDatetimeArchiveProcessedUTC deprecated. Will be removed in Matomo 4.
53 * @return array An array with four values:
54 * - the latest archive ID or false if none
55 * - the latest visits value for the latest archive, regardless of whether the archive is invalidated or not
56 * - the latest visits converted value for the latest archive, regardless of whether the archive is invalidated or not
57 * - whether there is an archive that exists or not. if this is true and the latest archive is false, it means
58 * the archive found was not usable (for example, it was invalidated and we are not looking for invalidated archives)
59 * - the ts_archived for the latest usable archive
60 * @throws Exception
61 */
62 public static function getArchiveIdAndVisits(ArchiveProcessor\Parameters $params, $minDatetimeArchiveProcessedUTC = false, $includeInvalidated = null)
63 {
64 $idSite = $params->getSite()->getId();
65 $period = $params->getPeriod()->getId();
66 $dateStart = $params->getPeriod()->getDateStart();
67 $dateStartIso = $dateStart->toString('Y-m-d');
68 $dateEndIso = $params->getPeriod()->getDateEnd()->toString('Y-m-d');
69
70 $numericTable = ArchiveTableCreator::getNumericTable($dateStart);
71
72 $requestedPlugin = $params->getRequestedPlugin();
73 $segment = $params->getSegment();
74 $plugins = array("VisitsSummary", $requestedPlugin);
75 $plugins = array_filter($plugins);
76
77 $doneFlags = Rules::getDoneFlags($plugins, $segment);
78
79 $requestedPluginDoneFlags = empty($requestedPlugin) ? [] : Rules::getDoneFlags([$requestedPlugin], $segment);
80 $allPluginsDoneFlag = Rules::getDoneFlagArchiveContainsAllPlugins($segment);
81
82 $doneFlagValues = Rules::getSelectableDoneFlagValues($includeInvalidated === null ? true : $includeInvalidated, $params, $includeInvalidated === null);
83
84 $results = self::getModel()->getArchiveIdAndVisits($numericTable, $idSite, $period, $dateStartIso, $dateEndIso, null, $doneFlags);
85 if (empty($results)) { // no archive found
86 return [false, false, false, false, false, false];
87 }
88
89 $result = self::findArchiveDataWithLatestTsArchived($results, $requestedPluginDoneFlags, $allPluginsDoneFlag);
90
91 $tsArchived = isset($result['ts_archived']) ? $result['ts_archived'] : false;
92 $visits = isset($result['nb_visits']) ? $result['nb_visits'] : false;
93 $visitsConverted = isset($result['nb_visits_converted']) ? $result['nb_visits_converted'] : false;
94 $value = isset($result['value']) ? $result['value'] : false;
95
96 $result['idarchive'] = empty($result['idarchive']) ? [] : [$result['idarchive']];
97 if (isset($result['partial'])) {
98 $result['idarchive'] = array_merge($result['idarchive'], $result['partial']);
99 }
100
101 if (empty($result['idarchive'])
102 || (isset($result['value'])
103 && !in_array($result['value'], $doneFlagValues))
104 ) { // the archive cannot be considered valid for this request (has wrong done flag value)
105 return [false, $visits, $visitsConverted, true, $tsArchived, $value];
106 }
107
108 if (!empty($minDatetimeArchiveProcessedUTC) && !is_object($minDatetimeArchiveProcessedUTC)) {
109 $minDatetimeArchiveProcessedUTC = Date::factory($minDatetimeArchiveProcessedUTC);
110 }
111
112 // the archive is too old
113 if ($minDatetimeArchiveProcessedUTC
114 && !empty($result['idarchive'])
115 && Date::factory($tsArchived)->isEarlier($minDatetimeArchiveProcessedUTC)
116 ) {
117 return [false, $visits, $visitsConverted, true, $tsArchived, $value];
118 }
119
120 $idArchives = !empty($result['idarchive']) ? $result['idarchive'] : false;
121
122 return [$idArchives, $visits, $visitsConverted, true, $tsArchived, $value];
123 }
124
125 /**
126 * Queries and returns archive IDs for a set of sites, periods, and a segment.
127 *
128 * @param int[] $siteIds
129 * @param Period[] $periods
130 * @param Segment $segment
131 * @param string[] $plugins List of plugin names for which data is being requested.
132 * @param bool $includeInvalidated true to include archives that are DONE_INVALIDATED, false if only DONE_OK.
133 * @param bool $_skipSetGroupConcatMaxLen for tests
134 * @return array Archive IDs are grouped by archive name and period range, ie,
135 * array(
136 * 'VisitsSummary.done' => array(
137 * '2010-01-01' => array(1,2,3)
138 * )
139 * )
140 * @throws
141 */
142 public static function getArchiveIds($siteIds, $periods, $segment, $plugins, $includeInvalidated = true, $_skipSetGroupConcatMaxLen = false)
143 {
144 $logger = StaticContainer::get(LoggerInterface::class);
145 if (!$_skipSetGroupConcatMaxLen) {
146 try {
147 Db::get()->query('SET SESSION group_concat_max_len=' . (128 * 1024));
148 } catch (\Exception $ex) {
149 $logger->info("Could not set group_concat_max_len MySQL session variable.");
150 }
151 }
152
153 if (empty($siteIds)) {
154 throw new \Exception("Website IDs could not be read from the request, ie. idSite=");
155 }
156
157 foreach ($siteIds as $index => $siteId) {
158 $siteIds[$index] = (int) $siteId;
159 }
160
161 $getArchiveIdsSql = "SELECT idsite, date1, date2,
162 GROUP_CONCAT(CONCAT(idarchive,'|',`name`,'|',`value`) ORDER BY idarchive DESC SEPARATOR ',') AS archives
163 FROM %s
164 WHERE idsite IN (" . implode(',', $siteIds) . ")
165 AND " . self::getNameCondition($plugins, $segment, $includeInvalidated) . "
166 AND ts_archived IS NOT NULL
167 AND %s
168 GROUP BY idsite, date1, date2";
169
170 $monthToPeriods = array();
171 foreach ($periods as $period) {
172 /** @var Period $period */
173 if ($period->getDateStart()->isLater(Date::now()->addDay(2))) {
174 continue; // avoid creating any archive tables in the future
175 }
176 $table = ArchiveTableCreator::getNumericTable($period->getDateStart());
177 $monthToPeriods[$table][] = $period;
178 }
179
180 $db = Db::get();
181
182 // for every month within the archive query, select from numeric table
183 $result = array();
184 foreach ($monthToPeriods as $table => $periods) {
185 $firstPeriod = reset($periods);
186
187 $bind = array();
188
189 if ($firstPeriod instanceof Range) {
190 $dateCondition = "date1 = ? AND date2 = ?";
191 $bind[] = $firstPeriod->getDateStart()->toString('Y-m-d');
192 $bind[] = $firstPeriod->getDateEnd()->toString('Y-m-d');
193 } else {
194 // we assume there is no range date in $periods
195 $dateCondition = '(';
196
197 foreach ($periods as $period) {
198 if (strlen($dateCondition) > 1) {
199 $dateCondition .= ' OR ';
200 }
201
202 $dateCondition .= "(period = ? AND date1 = ? AND date2 = ?)";
203 $bind[] = $period->getId();
204 $bind[] = $period->getDateStart()->toString('Y-m-d');
205 $bind[] = $period->getDateEnd()->toString('Y-m-d');
206 }
207
208 $dateCondition .= ')';
209 }
210
211 $sql = sprintf($getArchiveIdsSql, $table, $dateCondition);
212 $archiveIds = $db->fetchAll($sql, $bind);
213
214 // get the archive IDs. we keep all archives until the first all plugins archive.
215 // everything older than that one is discarded.
216 foreach ($archiveIds as $row) {
217 $dateStr = $row['date1'] . ',' . $row['date2'];
218
219 $archives = $row['archives'];
220 $pairs = explode(',', $archives);
221 foreach ($pairs as $pair) {
222 $parts = explode('|', $pair);
223 if (count($parts) != 3) { // GROUP_CONCAT got cut off, have to ignore the rest
224 // note: in this edge case, we end up not selecting the all plugins archive because it will be older than the partials.
225 // not ideal, but it avoids an exception.
226 $logger->info("GROUP_CONCAT got cut off in ArchiveSelector." . __FUNCTION__ . ' for idsite = ' . $row['idsite'] . ', period = ' . $dateStr);
227 continue;
228 }
229
230 list($idarchive, $doneFlag, $value) = $parts;
231
232 $result[$doneFlag][$dateStr][] = $idarchive;
233 if (strpos($doneFlag, '.') === false // all plugins archive
234 // sanity check: DONE_PARTIAL shouldn't be used w/ done archives, but in case we see one,
235 // don't treat it like an all plugins archive
236 && $value != ArchiveWriter::DONE_PARTIAL
237 ) {
238 break; // found the all plugins archive, don't need to look in older archives since we have everything here
239 }
240 }
241 }
242 }
243
244 return $result;
245 }
246
247 /**
248 * Queries and returns archive data using a set of archive IDs.
249 *
250 * @param array $archiveIds The IDs of the archives to get data from.
251 * @param array $recordNames The names of the data to retrieve (ie, nb_visits, nb_actions, etc.).
252 * Note: You CANNOT pass multiple recordnames if $loadAllSubtables=true.
253 * @param string $archiveDataType The archive data type (either, 'blob' or 'numeric').
254 * @param int|null|string $idSubtable null if the root blob should be loaded, an integer if a subtable should be
255 * loaded and 'all' if all subtables should be loaded.
256 * @return array
257 *@throws Exception
258 */
259 public static function getArchiveData($archiveIds, $recordNames, $archiveDataType, $idSubtable)
260 {
261 $chunk = new Chunk();
262
263 $db = Db::get();
264
265 // create the SQL to select archive data
266 $loadAllSubtables = $idSubtable === Archive::ID_SUBTABLE_LOAD_ALL_SUBTABLES;
267 if ($loadAllSubtables) {
268 $name = reset($recordNames);
269
270 // select blobs w/ name like "$name_[0-9]+" w/o using RLIKE
271 $nameEnd = strlen($name) + 1;
272 $nameEndAppendix = $nameEnd + 1;
273 $appendix = $chunk->getAppendix();
274 $lenAppendix = strlen($appendix);
275
276 $checkForChunkBlob = "SUBSTRING(name, $nameEnd, $lenAppendix) = '$appendix'";
277 $checkForSubtableId = "(SUBSTRING(name, $nameEndAppendix, 1) >= '0'
278 AND SUBSTRING(name, $nameEndAppendix, 1) <= '9')";
279
280 $whereNameIs = "(name = ? OR (name LIKE ? AND ( $checkForChunkBlob OR $checkForSubtableId ) ))";
281 $bind = array($name, $name . '%');
282 } else {
283 if ($idSubtable === null) {
284 // select root table or specific record names
285 $bind = array_values($recordNames);
286 } else {
287 // select a subtable id
288 $bind = array();
289 foreach ($recordNames as $recordName) {
290 // to be backwards compatible we need to look for the exact idSubtable blob and for the chunk
291 // that stores the subtables (a chunk stores many blobs in one blob)
292 $bind[] = $chunk->getRecordNameForTableId($recordName, $idSubtable);
293 $bind[] = self::appendIdSubtable($recordName, $idSubtable);
294 }
295 }
296
297 $inNames = Common::getSqlStringFieldsArray($bind);
298 $whereNameIs = "name IN ($inNames)";
299 }
300
301 $getValuesSql = "SELECT value, name, idsite, date1, date2, ts_archived
302 FROM %s
303 WHERE idarchive IN (%s)
304 AND " . $whereNameIs . "
305 ORDER BY ts_archived ASC"; // ascending order so we use the latest data found
306
307 // We want to fetch as many archives at once as possible instead of fetching each period individually
308 // eg instead of issueing one query per day we'll merge all the IDs of a given month into one query
309 // we group by YYYY-MM as we have one archive table per month
310 $archiveIdsPerMonth = [];
311 foreach ($archiveIds as $period => $ids) {
312 $yearMonth = substr($period, 0, 7); // eg 2022-11
313 if (empty($archiveIdsPerMonth[$yearMonth])) {
314 $archiveIdsPerMonth[$yearMonth] = [];
315 }
316 $archiveIdsPerMonth[$yearMonth] = array_merge($archiveIdsPerMonth[$yearMonth], $ids);
317 }
318
319 // get data from every table we're querying
320 $rows = array();
321 foreach ($archiveIdsPerMonth as $yearMonth => $ids) {
322 if (empty($ids)) {
323 throw new Exception("Unexpected: id archive not found for period '$yearMonth' '");
324 }
325
326 // $yearMonth = "2022-11",
327 $date = Date::factory($yearMonth . '-01');
328
329 $isNumeric = $archiveDataType === 'numeric';
330 if ($isNumeric) {
331 $table = ArchiveTableCreator::getNumericTable($date);
332 } else {
333 $table = ArchiveTableCreator::getBlobTable($date);
334 }
335
336 $ids = array_map('intval', $ids);
337 $sql = sprintf($getValuesSql, $table, implode(',', $ids));
338 $dataRows = $db->fetchAll($sql, $bind);
339
340 foreach ($dataRows as $row) {
341 if ($isNumeric) {
342 $rows[] = $row;
343 } else {
344 $row['value'] = self::uncompress($row['value']);
345
346 if ($chunk->isRecordNameAChunk($row['name'])) {
347 self::moveChunkRowToRows($rows, $row, $chunk, $loadAllSubtables, $idSubtable);
348 } else {
349 $rows[] = $row;
350 }
351 }
352 }
353 }
354
355 return $rows;
356 }
357
358 private static function moveChunkRowToRows(&$rows, $row, Chunk $chunk, $loadAllSubtables, $idSubtable)
359 {
360 // $blobs = array([subtableID] = [blob of subtableId])
361 $blobs = Common::safe_unserialize($row['value']);
362
363 if (!is_array($blobs)) {
364 return;
365 }
366
367 // $rawName = eg 'PluginName_ArchiveName'
368 $rawName = $chunk->getRecordNameWithoutChunkAppendix($row['name']);
369
370 if ($loadAllSubtables) {
371 foreach ($blobs as $subtableId => $blob) {
372 $row['value'] = $blob;
373 $row['name'] = self::appendIdSubtable($rawName, $subtableId);
374 $rows[] = $row;
375 }
376 } elseif (array_key_exists($idSubtable, $blobs)) {
377 $row['value'] = $blobs[$idSubtable];
378 $row['name'] = self::appendIdSubtable($rawName, $idSubtable);
379 $rows[] = $row;
380 }
381 }
382
383 public static function appendIdSubtable($recordName, $id)
384 {
385 return $recordName . "_" . $id;
386 }
387
388 private static function uncompress($data)
389 {
390 return @gzuncompress($data);
391 }
392
393 /**
394 * Returns the SQL condition used to find successfully completed archives that
395 * this instance is querying for.
396 *
397 * @param array $plugins
398 * @param Segment $segment
399 * @param bool $includeInvalidated
400 * @return string
401 */
402 private static function getNameCondition(array $plugins, Segment $segment, $includeInvalidated = true)
403 {
404 // the flags used to tell how the archiving process for a specific archive was completed,
405 // if it was completed
406 $doneFlags = Rules::getDoneFlags($plugins, $segment);
407 $allDoneFlags = "'" . implode("','", $doneFlags) . "'";
408
409 $possibleValues = Rules::getSelectableDoneFlagValues($includeInvalidated, null, $checkAuthorizedToArchive = false);
410
411 // create the SQL to find archives that are DONE
412 return "((name IN ($allDoneFlags)) AND (value IN (" . implode(',', $possibleValues) . ")))";
413 }
414
415 /**
416 * This method takes the output of Model::getArchiveIdAndVisits() and selects data from the
417 * latest archives.
418 *
419 * This includes:
420 * - the idarchive with the latest ts_archived ($results will be ordered by ts_archived desc)
421 * - the visits/converted visits of the latest archive, which includes archives for VisitsSummary alone
422 * ($requestedPluginDoneFlags will have the done flag for the overall archive plus a done flag for
423 * VisitsSummary by itself)
424 * - the ts_archived for the latest idarchive
425 * - the doneFlag value for the latest archive
426 *
427 * @param $results
428 * @param $doneFlags
429 * @return array
430 */
431 private static function findArchiveDataWithLatestTsArchived($results, $requestedPluginDoneFlags, $allPluginsDoneFlag)
432 {
433 $doneFlags = array_merge($requestedPluginDoneFlags, [$allPluginsDoneFlag]);
434
435 // find latest idarchive for each done flag
436 $idArchives = [];
437 $tsArchiveds = [];
438 foreach ($results as $row) {
439 $doneFlag = $row['name'];
440 if (!isset($idArchives[$doneFlag])) {
441 $idArchives[$doneFlag] = $row['idarchive'];
442 $tsArchiveds[$doneFlag] = $row['ts_archived'];
443 }
444 }
445
446 $archiveData = [
447 self::NB_VISITS_RECORD_LOOKED_UP => false,
448 self::NB_VISITS_CONVERTED_RECORD_LOOKED_UP => false,
449 ];
450
451 foreach ($results as $result) {
452 if (in_array($result['name'], $doneFlags)
453 && in_array($result['idarchive'], $idArchives)
454 && $result['value'] != ArchiveWriter::DONE_PARTIAL
455 ) {
456 $archiveData = $result;
457 if (empty($archiveData[self::NB_VISITS_RECORD_LOOKED_UP])) {
458 $archiveData[self::NB_VISITS_RECORD_LOOKED_UP] = 0;
459 }
460 if (empty($archiveData[self::NB_VISITS_CONVERTED_RECORD_LOOKED_UP])) {
461 $archiveData[self::NB_VISITS_CONVERTED_RECORD_LOOKED_UP] = 0;
462 }
463 break;
464 }
465 }
466
467 foreach ([self::NB_VISITS_RECORD_LOOKED_UP, self::NB_VISITS_CONVERTED_RECORD_LOOKED_UP] as $metric) {
468 foreach ($results as $result) {
469 if (!in_array($result['idarchive'], $idArchives)) {
470 continue;
471 }
472
473 if (empty($archiveData[$metric])) {
474 if (!empty($result[$metric]) || $result[$metric] === 0 || $result[$metric] === '0') {
475 $archiveData[$metric] = $result[$metric];
476 }
477 }
478 }
479 }
480
481 // add partial archives
482 $mainTsArchived = isset($tsArchiveds[$allPluginsDoneFlag]) ? $tsArchiveds[$allPluginsDoneFlag] : null;
483 foreach ($results as $row) {
484 if (!isset($idArchives[$row['name']])) {
485 continue;
486 }
487
488 $thisTsArchived = Date::factory($row['ts_archived']);
489 if ($row['value'] == ArchiveWriter::DONE_PARTIAL
490 && (empty($mainTsArchived) || !Date::factory($mainTsArchived)->isLater($thisTsArchived))
491 ) {
492 $archiveData['partial'][] = $row['idarchive'];
493
494 if (empty($archiveData['ts_archived'])) {
495 $archiveData['ts_archived'] = $row['ts_archived'];
496 }
497 }
498 }
499
500 return $archiveData;
501 }
502 }
503