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