PluginProbe ʕ •ᴥ•ʔ
Matomo Analytics – Powerful, Privacy-First Insights for WordPress / 5.1.6
Matomo Analytics – Powerful, Privacy-First Insights for WordPress v5.1.6
5.13.0 5.12.1 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 / Archive / ArchiveInvalidator.php
matomo / app / core / Archive Last commit date
ArchiveInvalidator 2 years ago ArchiveInvalidator.php 2 years ago ArchivePurger.php 2 years ago ArchiveQuery.php 2 years ago ArchiveQueryFactory.php 2 years ago ArchiveState.php 2 years ago Chunk.php 2 years ago DataCollection.php 2 years ago DataTableFactory.php 2 years ago Parameters.php 2 years ago
ArchiveInvalidator.php
641 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\Archive;
10
11 use Piwik\Archive\ArchiveInvalidator\InvalidationResult;
12 use Piwik\ArchiveProcessor\Rules;
13 use Piwik\Common;
14 use Piwik\Container\StaticContainer;
15 use Piwik\CronArchive\ReArchiveList;
16 use Piwik\CronArchive\SegmentArchiving;
17 use Piwik\DataAccess\ArchiveTableCreator;
18 use Piwik\DataAccess\Model;
19 use Piwik\Date;
20 use Piwik\Db;
21 use Piwik\Option;
22 use Piwik\Period;
23 use Piwik\Piwik;
24 use Piwik\Plugin\Manager;
25 use Piwik\Plugins\CoreAdminHome\Tasks\ArchivesToPurgeDistributedList;
26 use Piwik\Plugins\PrivacyManager\PrivacyManager;
27 use Piwik\Segment;
28 use Piwik\SettingsServer;
29 use Piwik\Site;
30 use Piwik\Tracker\Cache;
31 use Piwik\Log\LoggerInterface;
32 /**
33 * Service that can be used to invalidate archives or add archive references to a list so they will
34 * be invalidated later.
35 *
36 * Archives are put in an "invalidated" state by setting the done flag to `ArchiveWriter::DONE_INVALIDATED`.
37 * This class also adds the archive's associated site to the a distributed list and adding the archive's year month to another
38 * distributed list.
39 *
40 * CronArchive will reprocess the archive data for all sites in the first list, and a scheduled task
41 * will purge the old, invalidated data in archive tables identified by the second list.
42 *
43 * Until CronArchive, or browser triggered archiving, re-processes data for an invalidated archive, the invalidated
44 * archive data will still be displayed in the UI and API.
45 *
46 * ### Deferred Invalidation
47 *
48 * Invalidating archives means running queries on one or more archive tables. In some situations, like during
49 * tracking, this is not desired. In such cases, archive references can be added to a list via the
50 * rememberToInvalidateArchivedReportsLater method, which will add the reference to a distributed list
51 *
52 * Later, during Piwik's normal execution, the list will be read and every archive it references will
53 * be invalidated.
54 */
55 class ArchiveInvalidator
56 {
57 public const TRACKER_CACHE_KEY = 'ArchiveInvalidator.rememberToInvalidate';
58 public const INVALIDATION_STATUS_QUEUED = 0;
59 public const INVALIDATION_STATUS_IN_PROGRESS = 1;
60 private $rememberArchivedReportIdStart = 'report_to_invalidate_';
61 /**
62 * @var Model
63 */
64 private $model;
65 /**
66 * @var SegmentArchiving
67 */
68 private $segmentArchiving;
69 /**
70 * @var LoggerInterface
71 */
72 private $logger;
73 /**
74 * @var int[]
75 */
76 private $allIdSitesCache;
77 public function __construct(Model $model, LoggerInterface $logger)
78 {
79 $this->model = $model;
80 $this->segmentArchiving = null;
81 $this->logger = $logger;
82 }
83 public function getAllRememberToInvalidateArchivedReportsLater()
84 {
85 // we do not really have to get the value first. we could simply always try to call set() and it would update or
86 // insert the record if needed but we do not want to lock the table (especially since there are still some
87 // MyISAM installations)
88 $values = Option::getLike('%' . str_replace('_', '\\_', $this->rememberArchivedReportIdStart) . '%');
89 $all = [];
90 foreach ($values as $name => $value) {
91 $suffix = substr($name, strpos($name, $this->rememberArchivedReportIdStart));
92 $suffix = str_replace($this->rememberArchivedReportIdStart, '', $suffix);
93 list($idSite, $dateStr) = explode('_', $suffix);
94 $all[$idSite][$dateStr] = $value;
95 }
96 return $all;
97 }
98 public function rememberToInvalidateArchivedReportsLater($idSite, Date $date)
99 {
100 if (SettingsServer::isTrackerApiRequest()) {
101 $value = $this->getRememberedArchivedReportsOptionFromTracker($idSite, $date->toString());
102 } else {
103 // To support multiple transactions at once, look for any other process to have set (and committed)
104 // this report to be invalidated.
105 $key = $this->buildRememberArchivedReportIdForSiteAndDate($idSite, $date->toString());
106 // we do not really have to get the value first. we could simply always try to call set() and it would update or
107 // insert the record if needed but we do not want to lock the table (especially since there are still some
108 // MyISAM installations)
109 $value = Option::getLike('%' . str_replace('_', '\\_', $key) . '%');
110 }
111 // getLike() returns an empty array rather than 'false'
112 if (empty($value)) {
113 // In order to support multiple concurrent transactions, add our pid to the end of the key so that it will just insert
114 // rather than waiting on some other process to commit before proceeding.The issue is that with out this, more than
115 // one process is trying to add the exact same value to the table, which causes contention. With the pid suffixed to
116 // the value, each process can successfully enter its own row in the table. The net result will be the same. We could
117 // always just set this, but it would result in a lot of rows in the options table.. more than needed. With this
118 // change you'll have at most N rows per date/site, where N is the number of parallel requests on this same idsite/date
119 // that happen to run in overlapping transactions.
120 $mykey = $this->buildRememberArchivedReportIdProcessSafe($idSite, $date->toString());
121 Option::set($mykey, '1');
122 Cache::clearCacheGeneral();
123 return $mykey;
124 }
125 }
126 private function getRememberedArchivedReportsOptionFromTracker($idSite, $dateStr)
127 {
128 $cacheKey = self::TRACKER_CACHE_KEY;
129 $generalCache = Cache::getCacheGeneral();
130 if (empty($generalCache[$cacheKey][$idSite][$dateStr])) {
131 return [];
132 }
133 return $generalCache[$cacheKey][$idSite][$dateStr];
134 }
135 public function getDaysWithRememberedInvalidationsForSite(int $idSite) : array
136 {
137 return array_keys($this->getRememberedArchivedReportsThatShouldBeInvalidated($idSite));
138 }
139 public function getRememberedArchivedReportsThatShouldBeInvalidated(int $idSite = null)
140 {
141 if (null === $idSite) {
142 $optionName = $this->rememberArchivedReportIdStart . '%';
143 } else {
144 $optionName = $this->buildRememberArchivedReportIdForSite($idSite);
145 }
146 $reports = Option::getLike('%' . str_replace('_', '\\_', $optionName) . '\\_%');
147 $sitesPerDay = [];
148 foreach ($reports as $report => $value) {
149 $report = substr($report, strpos($report, $this->rememberArchivedReportIdStart));
150 $report = str_replace($this->rememberArchivedReportIdStart, '', $report);
151 $report = explode('_', $report);
152 $siteId = (int) $report[0];
153 $date = $report[1];
154 if (empty($siteId)) {
155 continue;
156 }
157 if (empty($sitesPerDay[$date])) {
158 $sitesPerDay[$date] = [];
159 }
160 $sitesPerDay[$date][] = $siteId;
161 }
162 return $sitesPerDay;
163 }
164 private function buildRememberArchivedReportIdForSite($idSite)
165 {
166 return $this->rememberArchivedReportIdStart . (int) $idSite;
167 }
168 private function buildRememberArchivedReportIdForSiteAndDate($idSite, $date)
169 {
170 $id = $this->buildRememberArchivedReportIdForSite($idSite);
171 $id .= '_' . trim($date);
172 return $id;
173 }
174 // This version is multi process safe on the insert of a new date to invalidate.
175 private function buildRememberArchivedReportIdProcessSafe($idSite, $date)
176 {
177 $id = Common::getRandomString(4, 'abcdefghijklmnoprstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ') . '_';
178 $id .= $this->buildRememberArchivedReportIdForSiteAndDate($idSite, $date);
179 $id .= '_' . Common::getProcessId();
180 return $id;
181 }
182 public function forgetRememberedArchivedReportsToInvalidateForSite($idSite)
183 {
184 $id = $this->buildRememberArchivedReportIdForSite($idSite) . '_';
185 $hasDeletedSomething = $this->deleteOptionLike($id);
186 if ($hasDeletedSomething) {
187 Cache::clearCacheGeneral();
188 }
189 }
190 /**
191 * @internal
192 * After calling this method, make sure to call Cache::clearCacheGeneral(); For performance reasons we don't call
193 * this here immediately in case there are multiple invalidations.
194 */
195 public function forgetRememberedArchivedReportsToInvalidate($idSite, Date $date)
196 {
197 $id = $this->buildRememberArchivedReportIdForSiteAndDate($idSite, $date->toString());
198 // The process pid is added to the end of the entry in order to support multiple concurrent transactions.
199 // So this must be a deleteLike call to get all the entries, where there used to only be one.
200 return $this->deleteOptionLike($id);
201 }
202 /**
203 * @param $id
204 * @return bool true if a record was deleted, false otherwise.
205 * @throws \Zend_Db_Statement_Exception
206 */
207 private function deleteOptionLike($id)
208 {
209 // we're not using deleteLike since it maybe could cause deadlocks see https://github.com/matomo-org/matomo/issues/15545
210 // we want to reduce number of rows scanned and only delete specific primary key
211 $keys = Option::getLike('%' . str_replace('_', '\\_', $id) . '%');
212 if (empty($keys)) {
213 return false;
214 }
215 $keys = array_keys($keys);
216 $placeholders = Common::getSqlStringFieldsArray($keys);
217 $table = Common::prefixTable('option');
218 $db = Db::query('DELETE FROM `' . $table . '` WHERE `option_name` IN (' . $placeholders . ')', $keys);
219 return (bool) $db->rowCount();
220 }
221 /**
222 * @param $idSites int[]
223 * @param $dates Date[]|string[]
224 * @param $period string
225 * @param $segment Segment
226 * @param bool $cascadeDown
227 * @param bool $forceInvalidateNonexistentRanges set true to force inserting rows for ranges in archive_invalidations
228 * @param string $name null to make sure every plugin is archived when this invalidation is processed by core:archive,
229 * or a plugin name to only archive the specific plugin.
230 * @param bool $ignorePurgeLogDataDate
231 * @return InvalidationResult
232 * @throws \Exception
233 */
234 public function markArchivesAsInvalidated(array $idSites, array $dates, $period, Segment $segment = null, $cascadeDown = false, $forceInvalidateNonexistentRanges = false, $name = null, $ignorePurgeLogDataDate = false)
235 {
236 $plugin = null;
237 if ($name && strpos($name, '.') !== false) {
238 list($plugin) = explode('.', $name);
239 }
240 if ($plugin && !Manager::getInstance()->isPluginActivated($plugin)) {
241 throw new \Exception("Plugin is not activated: '{$plugin}'");
242 }
243 $invalidationInfo = new InvalidationResult();
244 // quick fix for #15086, if we're only invalidating today's date for a site, don't add the site to the list of sites
245 // to reprocess.
246 $hasMoreThanJustToday = [];
247 foreach ($idSites as $idSite) {
248 $hasMoreThanJustToday[$idSite] = true;
249 $tz = Site::getTimezoneFor($idSite);
250 if (($period == 'day' || $period === false) && count($dates) == 1 && (string) $dates[0] == (string) Date::factoryInTimezone('today', $tz)) {
251 // date is for today
252 $hasMoreThanJustToday[$idSite] = false;
253 }
254 }
255 /**
256 * Triggered when a Matomo user requested the invalidation of some reporting archives. Using this event, plugin
257 * developers can automatically invalidate another site, when a site is being invalidated. A plugin may even
258 * remove an idSite from the list of sites that should be invalidated to prevent it from ever being
259 * invalidated.
260 *
261 * **Example**
262 *
263 * public function getIdSitesToMarkArchivesAsInvalidates(&$idSites)
264 * {
265 * if (in_array(1, $idSites)) {
266 * $idSites[] = 5; // when idSite 1 is being invalidated, also invalidate idSite 5
267 * }
268 * }
269 *
270 * @param array &$idSites An array containing a list of site IDs which are requested to be invalidated.
271 * @param array $dates An array containing the dates to invalidate.
272 * @param string $period A string containing the period to be invalidated.
273 * @param Segment $segment A Segment Object containing segment to invalidate.
274 * @param string $name A string containing the name of the archive to be invalidated.
275 * @param bool $isPrivacyDeleteData A boolean value if event is triggered via Privacy delete visit action.
276 */
277 Piwik::postEvent('Archiving.getIdSitesToMarkArchivesAsInvalidated', array(&$idSites, $dates, $period, $segment, $name, $isPrivacyDeleteData = false));
278 // we trigger above event on purpose here and it is good that the segment was created like
279 // `new Segment($segmentString, $idSites)` because when a user adds a site via this event, the added idSite
280 // might not have this segment meaning we avoid a possible error. For the workflow to work, any added or removed
281 // idSite does not need to be added to $segment.
282 $datesToInvalidate = $this->removeDatesThatHaveBeenPurged($dates, $period, $invalidationInfo, $ignorePurgeLogDataDate);
283 $allPeriodsToInvalidate = $this->getAllPeriodsByYearMonth($period, $datesToInvalidate, $cascadeDown);
284 $this->markArchivesInvalidated($idSites, $allPeriodsToInvalidate, $segment, $period != 'range', $forceInvalidateNonexistentRanges, $name);
285 $isInvalidatingDays = $period == 'day' || $cascadeDown || empty($period);
286 $isNotInvalidatingSegment = empty($segment) || empty($segment->getString());
287 if ($isInvalidatingDays && $isNotInvalidatingSegment) {
288 $hasDeletedAny = false;
289 foreach ($idSites as $idSite) {
290 foreach ($dates as $date) {
291 if (is_string($date)) {
292 $date = Date::factory($date);
293 }
294 $hasDeletedAny = $this->forgetRememberedArchivedReportsToInvalidate($idSite, $date) || $hasDeletedAny;
295 }
296 }
297 if ($hasDeletedAny) {
298 Cache::clearCacheGeneral();
299 }
300 }
301 return $invalidationInfo;
302 }
303 private function getAllPeriodsByYearMonth($periodOrAll, $dates, $cascadeDown, &$result = [])
304 {
305 $periods = $periodOrAll ? [$periodOrAll] : ['day'];
306 foreach ($periods as $period) {
307 foreach ($dates as $date) {
308 $periodObj = $this->makePeriod($date, $period);
309 $result[$this->getYearMonth($periodObj)][$this->getUniquePeriodId($periodObj)] = $periodObj;
310 // cascade down
311 if ($cascadeDown && $period != 'range') {
312 $this->addChildPeriodsByYearMonth($result, $periodObj);
313 }
314 // cascade up
315 // if the period spans multiple years or months, it won't be used when aggregating parent periods, so
316 // we can avoid invalidating it
317 if ($this->shouldPropagateUp($periodObj) && $period != 'range') {
318 $this->addParentPeriodsByYearMonth($result, $periodObj);
319 }
320 }
321 }
322 return $result;
323 }
324 private function shouldPropagateUp(Period $periodObj)
325 {
326 return $periodObj->getDateStart()->toString('Y') == $periodObj->getDateEnd()->toString('Y') && $periodObj->getDateStart()->toString('m') == $periodObj->getDateEnd()->toString('m');
327 }
328 private function addChildPeriodsByYearMonth(&$result, Period $period)
329 {
330 if ($period->getLabel() == 'range') {
331 return;
332 } elseif ($period->getLabel() == 'day' && $this->shouldPropagateUp($period)) {
333 $this->addParentPeriodsByYearMonth($result, $period);
334 return;
335 }
336 foreach ($period->getSubperiods() as $subperiod) {
337 $result[$this->getYearMonth($subperiod)][$this->getUniquePeriodId($subperiod)] = $subperiod;
338 $this->addChildPeriodsByYearMonth($result, $subperiod);
339 }
340 }
341 private function addParentPeriodsByYearMonth(&$result, Period $period, Date $originalDate = null)
342 {
343 if ($period->getLabel() == 'year' || $period->getLabel() == 'range' || !Period\Factory::isPeriodEnabledForAPI($period->getParentPeriodLabel())) {
344 return;
345 }
346 $originalDate = $originalDate ?? $period->getDateStart();
347 $parentPeriod = Period\Factory::build($period->getParentPeriodLabel(), $originalDate);
348 $result[$this->getYearMonth($parentPeriod)][$this->getUniquePeriodId($parentPeriod)] = $parentPeriod;
349 $this->addParentPeriodsByYearMonth($result, $parentPeriod, $originalDate);
350 }
351 /**
352 * @param $idSites int[]
353 * @param $dates Date[]
354 * @param $period string
355 * @param $segment Segment
356 * @param bool $cascadeDown
357 * @return InvalidationResult
358 * @throws \Exception
359 */
360 public function markArchivesOverlappingRangeAsInvalidated(array $idSites, array $dates, Segment $segment = null)
361 {
362 $invalidationInfo = new InvalidationResult();
363 $ranges = array();
364 foreach ($dates as $dateRange) {
365 $ranges[] = Period\Factory::build('range', $dateRange[0] . ',' . $dateRange[1]);
366 }
367 $invalidatedMonths = array();
368 $archiveNumericTables = ArchiveTableCreator::getTablesArchivesInstalled($type = ArchiveTableCreator::NUMERIC_TABLE);
369 foreach ($archiveNumericTables as $table) {
370 $tableDate = ArchiveTableCreator::getDateFromTableName($table);
371 $rowsAffected = $this->model->updateArchiveAsInvalidated($table, $idSites, $ranges, $segment);
372 if ($rowsAffected > 0) {
373 $invalidatedMonths[] = $tableDate;
374 }
375 }
376 foreach ($idSites as $idSite) {
377 foreach ($dates as $dateRange) {
378 $this->forgetRememberedArchivedReportsToInvalidate($idSite, $dateRange[0]);
379 $invalidationInfo->processedDates[] = $dateRange[0];
380 }
381 }
382 Cache::clearCacheGeneral();
383 return $invalidationInfo;
384 }
385 /**
386 * Schedule rearchiving of reports for a single plugin or single report for N months in the past. The next time
387 * core:archive is run, they will be processed.
388 *
389 * @param int[]|string $idSites A list of idSites or 'all'
390 * @param string $plugin
391 * @param string|null $report
392 * @param Date|null $startDate
393 * @throws \Exception
394 * @api
395 */
396 public function reArchiveReport($idSites, string $plugin = null, string $report = null, Date $startDate = null, Segment $segment = null)
397 {
398 $date2 = Date::today();
399 $earliestDateToRearchive = Piwik::getEarliestDateToRearchive();
400 if (empty($startDate)) {
401 if (empty($earliestDateToRearchive)) {
402 return null;
403 // INI setting set to 0 months so no rearchiving
404 }
405 $startDate = $earliestDateToRearchive;
406 } elseif (!empty($earliestDateToRearchive)) {
407 // don't allow archiving further back than the rearchive_reports_in_past_last_n_months date allows
408 $startDate = $startDate->isEarlier($earliestDateToRearchive) ? $earliestDateToRearchive : $startDate;
409 }
410 if ($idSites === 'all') {
411 $idSites = $this->getAllSitesId();
412 }
413 $dates = [];
414 $date = $startDate;
415 while ($date->isEarlier($date2)) {
416 $dates[] = $date;
417 $date = $date->addDay(1);
418 }
419 if (empty($dates)) {
420 return;
421 }
422 $name = $plugin;
423 if (!empty($report)) {
424 $name .= '.' . $report;
425 }
426 $this->markArchivesAsInvalidated($idSites, $dates, 'day', $segment, $cascadeDown = false, $forceInvalidateRanges = false, $name);
427 if (empty($segment) && Rules::shouldProcessSegmentsWhenReArchivingReports()) {
428 foreach ($idSites as $idSite) {
429 foreach (Rules::getSegmentsToProcess([$idSite]) as $segment) {
430 $this->markArchivesAsInvalidated($idSites, $dates, 'day', new Segment($segment, [$idSite]), $cascadeDown = false, $forceInvalidateRanges = false, $name);
431 }
432 }
433 }
434 }
435 /**
436 * Remove invalidations for a specific report or all invalidations for a specific plugin. If your plugin supports
437 * archiving data in the past, you may want to call this method to remove any pending invalidations if, for example,
438 * your plugin is deactivated or a report deleted.
439 *
440 * @param int|int[] $idSite one or more site IDs or 'all' for all site IDs
441 * @param string $string
442 * @param string|null $report
443 */
444 public function removeInvalidations($idSite, $plugin, $report = null)
445 {
446 if (empty($report)) {
447 $this->model->removeInvalidationsLike($idSite, $plugin);
448 } else {
449 $this->model->removeInvalidations($idSite, $plugin, $report);
450 }
451 }
452 /**
453 * Schedules a re-archiving reports without propagating exceptions. This is scheduled
454 * since adding invalidations can take a long time and delay UI response times.
455 *
456 * @param int|int[]|'all' $idSites
457 * @param string|int $pluginName
458 * @param string|null $report
459 * @param Date|null $startDate
460 */
461 public function scheduleReArchiving($idSites, string $pluginName = null, $report = null, Date $startDate = null, Segment $segment = null)
462 {
463 if (!empty($report)) {
464 $this->removeInvalidationsSafely($idSites, $pluginName, $report);
465 }
466 try {
467 $reArchiveList = new ReArchiveList($this->logger);
468 $reArchiveList->add(json_encode(['idSites' => $idSites, 'pluginName' => $pluginName, 'report' => $report, 'startDate' => $startDate ? $startDate->getTimestamp() : null, 'segment' => $segment ? $segment->getOriginalString() : null]));
469 } catch (\Throwable $ex) {
470 $this->logger->info("Failed to schedule rearchiving of past reports for {$pluginName} plugin.");
471 }
472 }
473 /**
474 * Applies the queued archiving rearchiving entries.
475 */
476 public function applyScheduledReArchiving()
477 {
478 $reArchiveList = new ReArchiveList($this->logger);
479 $items = $reArchiveList->getAll();
480 foreach ($items as $item) {
481 try {
482 $entry = @json_decode($item, true);
483 if (empty($entry)) {
484 continue;
485 }
486 $idSites = Site::getIdSitesFromIdSitesString($entry['idSites']);
487 $this->reArchiveReport($idSites, $entry['pluginName'], $entry['report'], !empty($entry['startDate']) ? Date::factory((int) $entry['startDate']) : null, !empty($entry['segment']) ? new Segment($entry['segment'], $idSites) : null);
488 } catch (\Throwable $ex) {
489 $this->logger->info("Failed to create invalidations for report re-archiving (idSites = {idSites}, pluginName = {pluginName}, report = {report}, startDate = {startDateTs}): {ex}", ['idSites' => json_encode($entry['idSites']), 'pluginName' => $entry['pluginName'], 'report' => $entry['report'], 'startDateTs' => $entry['startDate'], 'ex' => $ex]);
490 } finally {
491 $reArchiveList->remove([$item]);
492 }
493 }
494 }
495 /**
496 * Calls removeInvalidations() without propagating exceptions.
497 *
498 * @param int|int[]|'all' $idSites
499 * @param string $pluginName
500 * @param string|null $report
501 */
502 public function removeInvalidationsSafely($idSites, $pluginName, $report = null)
503 {
504 try {
505 $this->removeInvalidations($idSites, $pluginName, $report);
506 $this->removeInvalidationsFromDistributedList($idSites, $pluginName, $report);
507 } catch (\Throwable $ex) {
508 $logger = StaticContainer::get(LoggerInterface::class);
509 $logger->debug("Failed to remove invalidations the for {$pluginName} plugin.");
510 }
511 }
512 public function removeInvalidationsFromDistributedList($idSites, $pluginName = null, $report = null)
513 {
514 $list = new ReArchiveList();
515 $entries = $list->getAll();
516 if ($idSites === 'all') {
517 $idSites = $this->getAllSitesId();
518 }
519 foreach ($entries as $index => $entry) {
520 $entry = @json_decode($entry, true);
521 if (empty($entry)) {
522 unset($entries[$index]);
523 continue;
524 }
525 $entryPluginName = $entry['pluginName'];
526 if (!empty($pluginName) && $pluginName != $entryPluginName) {
527 continue;
528 }
529 $entryReport = $entry['report'];
530 if (!empty($pluginName) && !empty($report) && $report != $entryReport) {
531 continue;
532 }
533 $sitesInEntry = $entry['idSites'];
534 if ($sitesInEntry === 'all') {
535 $sitesInEntry = $this->getAllSitesId();
536 }
537 $diffSites = array_diff($sitesInEntry, $idSites);
538 if (empty($diffSites)) {
539 unset($entries[$index]);
540 continue;
541 }
542 $entry['idSites'] = $diffSites;
543 $entries[$index] = json_encode($entry);
544 }
545 $list->setAll(array_values($entries));
546 }
547 /**
548 * @param int[] $idSites
549 * @param string[][][] $dates
550 * @throws \Exception
551 */
552 private function markArchivesInvalidated($idSites, $dates, Segment $segment = null, $removeRanges = false, $forceInvalidateNonexistentRanges = false, $name = null)
553 {
554 $idSites = array_map('intval', $idSites);
555 $yearMonths = [];
556 foreach ($dates as $tableDate => $datesForTable) {
557 $tableDateObj = Date::factory($tableDate);
558 $table = ArchiveTableCreator::getNumericTable($tableDateObj);
559 $yearMonths[] = $tableDateObj->toString('Y_m');
560 $this->model->updateArchiveAsInvalidated($table, $idSites, $datesForTable, $segment, $forceInvalidateNonexistentRanges, $name);
561 if ($removeRanges) {
562 $this->model->updateRangeArchiveAsInvalidated($table, $idSites, $datesForTable, $segment);
563 }
564 }
565 $this->markInvalidatedArchivesForReprocessAndPurge($yearMonths);
566 }
567 /**
568 * @param Date[] $dates
569 * @param InvalidationResult $invalidationInfo
570 * @return \Piwik\Date[]
571 */
572 private function removeDatesThatHaveBeenPurged($dates, $period, InvalidationResult $invalidationInfo, $ignorePurgeLogDataDate)
573 {
574 $this->findOlderDateWithLogs($invalidationInfo);
575 $result = array();
576 foreach ($dates as $date) {
577 $periodObj = $this->makePeriod($date, $period ?: 'day');
578 // we should only delete reports for dates that are more recent than N days
579 if ($invalidationInfo->minimumDateWithLogs && !$ignorePurgeLogDataDate && ($periodObj->getDateEnd()->isEarlier($invalidationInfo->minimumDateWithLogs) || $periodObj->getDateStart()->isEarlier($invalidationInfo->minimumDateWithLogs))) {
580 $invalidationInfo->warningDates[] = $date;
581 continue;
582 }
583 $result[] = $date;
584 $invalidationInfo->processedDates[] = $date;
585 }
586 return $result;
587 }
588 private function findOlderDateWithLogs(InvalidationResult $info)
589 {
590 // If using the feature "Delete logs older than N days"...
591 $purgeDataSettings = PrivacyManager::getPurgeDataSettings();
592 $logsDeletedWhenOlderThanDays = (int) $purgeDataSettings['delete_logs_older_than'];
593 $logsDeleteEnabled = $purgeDataSettings['delete_logs_enable'];
594 if ($logsDeleteEnabled && $logsDeletedWhenOlderThanDays) {
595 $info->minimumDateWithLogs = Date::factory('today')->subDay($logsDeletedWhenOlderThanDays);
596 }
597 }
598 /**
599 * @param array $idSites
600 * @param array $yearMonths
601 */
602 private function markInvalidatedArchivesForReprocessAndPurge($yearMonths)
603 {
604 $archivesToPurge = new ArchivesToPurgeDistributedList();
605 $archivesToPurge->add($yearMonths);
606 }
607 private function getYearMonth(Period $period)
608 {
609 return $period->getDateStart()->toString('Y-m-01');
610 }
611 private function getUniquePeriodId(Period $period)
612 {
613 return $period->getId() . '.' . $period->getRangeString();
614 }
615 private function makePeriod($date, $period)
616 {
617 if ($period === 'range' && strpos($date, ',') === false) {
618 $date = $date . ',' . $date;
619 return new Period\Range('range', $date);
620 } else {
621 return Period\Factory::build($period, $date);
622 }
623 }
624 private function getSegmentArchiving()
625 {
626 if (empty($this->segmentArchiving)) {
627 $this->segmentArchiving = new SegmentArchiving();
628 }
629 return $this->segmentArchiving;
630 }
631 private function getAllSitesId()
632 {
633 if (isset($this->allIdSitesCache)) {
634 return $this->allIdSitesCache;
635 }
636 $model = new \Piwik\Plugins\SitesManager\Model();
637 $this->allIdSitesCache = $model->getSitesId();
638 return $this->allIdSitesCache;
639 }
640 }
641