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