ArchiveInvalidator
1 year ago
ArchiveInvalidator.php
1 month ago
ArchivePurger.php
1 month ago
ArchiveQuery.php
1 year ago
ArchiveQueryFactory.php
1 year ago
ArchiveState.php
1 year ago
Chunk.php
1 year ago
DataCollection.php
1 month ago
DataTableFactory.php
1 month ago
Parameters.php
2 years ago
ArchiveInvalidator.php
620 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 | [$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 int[] $idSites |
| 223 | * @param Date[]|string[] $dates |
| 224 | * @param string $period |
| 225 | * @param bool $forceInvalidateNonexistentRanges set true to force inserting rows for ranges in archive_invalidations |
| 226 | * @param null|string $name null to make sure every plugin is archived when this invalidation is processed by core:archive, |
| 227 | * or a plugin name to only archive the specific plugin. |
| 228 | * @param bool $doNotCreateInvalidations If true, archives will only be marked as invalid, but no archive_invalidation record will be created |
| 229 | * @return InvalidationResult |
| 230 | * @throws \Exception |
| 231 | */ |
| 232 | public function markArchivesAsInvalidated(array $idSites, array $dates, $period, ?Segment $segment = null, bool $cascadeDown = \false, bool $forceInvalidateNonexistentRanges = \false, ?string $name = null, bool $ignorePurgeLogDataDate = \false, bool $doNotCreateInvalidations = \false) |
| 233 | { |
| 234 | $plugin = null; |
| 235 | if ($name && strpos($name, '.') !== \false) { |
| 236 | [$plugin] = explode('.', $name); |
| 237 | } elseif ($name) { |
| 238 | $plugin = $name; |
| 239 | } |
| 240 | if ($plugin && !Manager::getInstance()->isPluginActivated($plugin)) { |
| 241 | throw new \Exception("Plugin is not activated: '{$plugin}'"); |
| 242 | } |
| 243 | $invalidationInfo = new InvalidationResult(); |
| 244 | /** |
| 245 | * Triggered when a Matomo user requested the invalidation of some reporting archives. Using this event, plugin |
| 246 | * developers can automatically invalidate another site, when a site is being invalidated. A plugin may even |
| 247 | * remove an idSite from the list of sites that should be invalidated to prevent it from ever being |
| 248 | * invalidated. |
| 249 | * |
| 250 | * **Example** |
| 251 | * |
| 252 | * public function getIdSitesToMarkArchivesAsInvalidates(&$idSites) |
| 253 | * { |
| 254 | * if (in_array(1, $idSites)) { |
| 255 | * $idSites[] = 5; // when idSite 1 is being invalidated, also invalidate idSite 5 |
| 256 | * } |
| 257 | * } |
| 258 | * |
| 259 | * @param array &$idSites An array containing a list of site IDs which are requested to be invalidated. |
| 260 | * @param array $dates An array containing the dates to invalidate. |
| 261 | * @param string $period A string containing the period to be invalidated. |
| 262 | * @param null|Segment $segment A Segment Object containing segment to invalidate. |
| 263 | * @param string $name A string containing the name of the archive to be invalidated. |
| 264 | * @param bool $isPrivacyDeleteData A boolean value if event is triggered via Privacy delete visit action. |
| 265 | */ |
| 266 | Piwik::postEvent('Archiving.getIdSitesToMarkArchivesAsInvalidated', array(&$idSites, $dates, $period, $segment, $name, $isPrivacyDeleteData = \false)); |
| 267 | // we trigger above event on purpose here and it is good that the segment was created like |
| 268 | // `new Segment($segmentString, $idSites)` because when a user adds a site via this event, the added idSite |
| 269 | // might not have this segment meaning we avoid a possible error. For the workflow to work, any added or removed |
| 270 | // idSite does not need to be added to $segment. |
| 271 | $datesToInvalidate = $this->removeDatesThatHaveBeenPurged($dates, $period, $invalidationInfo, $ignorePurgeLogDataDate); |
| 272 | $allPeriodsToInvalidate = $this->getAllPeriodsByYearMonth($period, $datesToInvalidate, $cascadeDown); |
| 273 | $this->markArchivesInvalidated($idSites, $allPeriodsToInvalidate, $segment, $period != 'range', $forceInvalidateNonexistentRanges, $name, $doNotCreateInvalidations); |
| 274 | $isInvalidatingDays = $period == 'day' || $cascadeDown || empty($period); |
| 275 | $isNotInvalidatingSegment = empty($segment) || empty($segment->getString()); |
| 276 | if ($isInvalidatingDays && $isNotInvalidatingSegment) { |
| 277 | $hasDeletedAny = \false; |
| 278 | foreach ($idSites as $idSite) { |
| 279 | foreach ($dates as $date) { |
| 280 | if (is_string($date)) { |
| 281 | $date = Date::factory($date); |
| 282 | } |
| 283 | $hasDeletedAny = $this->forgetRememberedArchivedReportsToInvalidate($idSite, $date) || $hasDeletedAny; |
| 284 | } |
| 285 | } |
| 286 | if ($hasDeletedAny) { |
| 287 | Cache::clearCacheGeneral(); |
| 288 | } |
| 289 | } |
| 290 | return $invalidationInfo; |
| 291 | } |
| 292 | private function getAllPeriodsByYearMonth($periodOrAll, $dates, $cascadeDown, &$result = []) |
| 293 | { |
| 294 | $periods = $periodOrAll ? [$periodOrAll] : ['day']; |
| 295 | foreach ($periods as $period) { |
| 296 | foreach ($dates as $date) { |
| 297 | $periodObj = $this->makePeriod($date, $period); |
| 298 | $result[$this->getYearMonth($periodObj)][$this->getUniquePeriodId($periodObj)] = $periodObj; |
| 299 | // cascade down |
| 300 | if ($cascadeDown && $period != 'range') { |
| 301 | $this->addChildPeriodsByYearMonth($result, $periodObj); |
| 302 | } |
| 303 | // cascade up |
| 304 | // if the period spans multiple years or months, it won't be used when aggregating parent periods, so |
| 305 | // we can avoid invalidating it |
| 306 | if ($this->shouldPropagateUp($periodObj) && $period != 'range') { |
| 307 | $this->addParentPeriodsByYearMonth($result, $periodObj); |
| 308 | } |
| 309 | } |
| 310 | } |
| 311 | return $result; |
| 312 | } |
| 313 | private function shouldPropagateUp(Period $periodObj) |
| 314 | { |
| 315 | return $periodObj->getDateStart()->toString('Y') == $periodObj->getDateEnd()->toString('Y') && $periodObj->getDateStart()->toString('m') == $periodObj->getDateEnd()->toString('m'); |
| 316 | } |
| 317 | private function addChildPeriodsByYearMonth(&$result, Period $period) |
| 318 | { |
| 319 | if ($period->getLabel() == 'range') { |
| 320 | return; |
| 321 | } elseif ($period->getLabel() == 'day' && $this->shouldPropagateUp($period)) { |
| 322 | $this->addParentPeriodsByYearMonth($result, $period); |
| 323 | return; |
| 324 | } |
| 325 | foreach ($period->getSubperiods() as $subperiod) { |
| 326 | $result[$this->getYearMonth($subperiod)][$this->getUniquePeriodId($subperiod)] = $subperiod; |
| 327 | $this->addChildPeriodsByYearMonth($result, $subperiod); |
| 328 | } |
| 329 | } |
| 330 | private function addParentPeriodsByYearMonth(&$result, Period $period, ?Date $originalDate = null) |
| 331 | { |
| 332 | if ($period->getLabel() == 'year' || $period->getLabel() == 'range' || !Period\Factory::isPeriodEnabledForAPI($period->getParentPeriodLabel())) { |
| 333 | return; |
| 334 | } |
| 335 | $originalDate = $originalDate ?? $period->getDateStart(); |
| 336 | $parentPeriod = Period\Factory::build($period->getParentPeriodLabel(), $originalDate); |
| 337 | $result[$this->getYearMonth($parentPeriod)][$this->getUniquePeriodId($parentPeriod)] = $parentPeriod; |
| 338 | $this->addParentPeriodsByYearMonth($result, $parentPeriod, $originalDate); |
| 339 | } |
| 340 | /** |
| 341 | * @param int[] $idSites |
| 342 | * @param Date[] $dates |
| 343 | * @param null|string $name null to make sure every plugin is archived when this invalidation is processed by core:archive, |
| 344 | * * or a plugin name to only archive the specific plugin. |
| 345 | * @return InvalidationResult |
| 346 | * @throws \Exception |
| 347 | */ |
| 348 | public function markArchivesOverlappingRangeAsInvalidated(array $idSites, array $dates, ?Segment $segment = null, ?string $name = null) |
| 349 | { |
| 350 | $invalidationInfo = new InvalidationResult(); |
| 351 | $ranges = array(); |
| 352 | foreach ($dates as $dateRange) { |
| 353 | $ranges[] = Period\Factory::build('range', $dateRange[0] . ',' . $dateRange[1]); |
| 354 | } |
| 355 | $archiveNumericTables = ArchiveTableCreator::getTablesArchivesInstalled($type = ArchiveTableCreator::NUMERIC_TABLE); |
| 356 | foreach ($archiveNumericTables as $table) { |
| 357 | $this->model->updateArchiveAsInvalidated($table, $idSites, $ranges, $segment, \false, $name); |
| 358 | } |
| 359 | foreach ($idSites as $idSite) { |
| 360 | foreach ($dates as $dateRange) { |
| 361 | $this->forgetRememberedArchivedReportsToInvalidate($idSite, $dateRange[0]); |
| 362 | $invalidationInfo->processedDates[] = $dateRange[0]; |
| 363 | } |
| 364 | } |
| 365 | Cache::clearCacheGeneral(); |
| 366 | return $invalidationInfo; |
| 367 | } |
| 368 | /** |
| 369 | * Schedule rearchiving of reports for a single plugin or single report for N months in the past. The next time |
| 370 | * core:archive is run, they will be processed. |
| 371 | * |
| 372 | * @param int[]|string $idSites A list of idSites or 'all' |
| 373 | * @throws \Exception |
| 374 | * @api |
| 375 | */ |
| 376 | public function reArchiveReport($idSites, ?string $plugin = null, ?string $report = null, ?Date $startDate = null, ?Segment $segment = null) |
| 377 | { |
| 378 | $date2 = Date::today(); |
| 379 | $earliestDateToRearchive = Piwik::getEarliestDateToRearchive(); |
| 380 | if (empty($startDate)) { |
| 381 | if (empty($earliestDateToRearchive)) { |
| 382 | return null; |
| 383 | // INI setting set to 0 months so no rearchiving |
| 384 | } |
| 385 | $startDate = $earliestDateToRearchive; |
| 386 | } elseif (!empty($earliestDateToRearchive)) { |
| 387 | // don't allow archiving further back than the rearchive_reports_in_past_last_n_months date allows |
| 388 | $startDate = $startDate->isEarlier($earliestDateToRearchive) ? $earliestDateToRearchive : $startDate; |
| 389 | } |
| 390 | if ($idSites === 'all') { |
| 391 | $idSites = $this->getAllSitesId(); |
| 392 | } |
| 393 | $dates = []; |
| 394 | $date = $startDate; |
| 395 | while ($date->isEarlier($date2)) { |
| 396 | $dates[] = $date; |
| 397 | $date = $date->addDay(1); |
| 398 | } |
| 399 | if (empty($dates)) { |
| 400 | return; |
| 401 | } |
| 402 | $name = $plugin; |
| 403 | if (!empty($report)) { |
| 404 | $name .= '.' . $report; |
| 405 | } |
| 406 | $this->markArchivesAsInvalidated($idSites, $dates, 'day', $segment, $cascadeDown = \false, $forceInvalidateRanges = \false, $name); |
| 407 | if (empty($segment) && Rules::shouldProcessSegmentsWhenReArchivingReports()) { |
| 408 | foreach ($idSites as $idSite) { |
| 409 | foreach (Rules::getSegmentsToProcess([$idSite]) as $segment) { |
| 410 | $this->markArchivesAsInvalidated([$idSite], $dates, 'day', new Segment($segment, [$idSite]), $cascadeDown = \false, $forceInvalidateRanges = \false, $name); |
| 411 | } |
| 412 | } |
| 413 | } |
| 414 | } |
| 415 | /** |
| 416 | * Remove invalidations for a specific report or all invalidations for a specific plugin. If your plugin supports |
| 417 | * archiving data in the past, you may want to call this method to remove any pending invalidations if, for example, |
| 418 | * your plugin is deactivated or a report deleted. |
| 419 | * |
| 420 | * @param int|int[] $idSite one or more site IDs or 'all' for all site IDs |
| 421 | * @param string $plugin |
| 422 | * @param string|null $report |
| 423 | */ |
| 424 | public function removeInvalidations($idSite, $plugin, $report = null) |
| 425 | { |
| 426 | if (empty($report)) { |
| 427 | $this->model->removeInvalidationsLike($idSite, $plugin); |
| 428 | } else { |
| 429 | $this->model->removeInvalidations($idSite, $plugin, $report); |
| 430 | } |
| 431 | } |
| 432 | /** |
| 433 | * Schedules a re-archiving reports without propagating exceptions. This is scheduled |
| 434 | * since adding invalidations can take a long time and delay UI response times. |
| 435 | * |
| 436 | * @param int|int[]|'all' $idSites |
| 437 | * @param string|int $pluginName |
| 438 | * @param string|null $report |
| 439 | */ |
| 440 | public function scheduleReArchiving($idSites, ?string $pluginName = null, $report = null, ?Date $startDate = null, ?Segment $segment = null) |
| 441 | { |
| 442 | if (!empty($report)) { |
| 443 | $this->removeInvalidationsSafely($idSites, $pluginName, $report); |
| 444 | } |
| 445 | try { |
| 446 | $reArchiveList = new ReArchiveList($this->logger); |
| 447 | $reArchiveList->add(json_encode(['idSites' => $idSites, 'pluginName' => $pluginName, 'report' => $report, 'startDate' => $startDate ? $startDate->getTimestamp() : null, 'segment' => $segment ? $segment->getOriginalString() : null])); |
| 448 | } catch (\Throwable $ex) { |
| 449 | $this->logger->info("Failed to schedule rearchiving of past reports for {$pluginName} plugin."); |
| 450 | } |
| 451 | } |
| 452 | /** |
| 453 | * Applies the queued archiving rearchiving entries. |
| 454 | */ |
| 455 | public function applyScheduledReArchiving() |
| 456 | { |
| 457 | $reArchiveList = new ReArchiveList($this->logger); |
| 458 | $items = $reArchiveList->getAll(); |
| 459 | foreach ($items as $item) { |
| 460 | try { |
| 461 | $entry = @json_decode($item, \true); |
| 462 | if (empty($entry)) { |
| 463 | continue; |
| 464 | } |
| 465 | $idSites = Site::getIdSitesFromIdSitesString($entry['idSites']); |
| 466 | $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); |
| 467 | } catch (\Throwable $ex) { |
| 468 | $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]); |
| 469 | } finally { |
| 470 | $reArchiveList->remove([$item]); |
| 471 | } |
| 472 | } |
| 473 | } |
| 474 | /** |
| 475 | * Calls removeInvalidations() without propagating exceptions. |
| 476 | * |
| 477 | * @param int|int[]|'all' $idSites |
| 478 | * @param string $pluginName |
| 479 | * @param string|null $report |
| 480 | */ |
| 481 | public function removeInvalidationsSafely($idSites, $pluginName, $report = null) |
| 482 | { |
| 483 | try { |
| 484 | $this->removeInvalidations($idSites, $pluginName, $report); |
| 485 | $this->removeInvalidationsFromDistributedList($idSites, $pluginName, $report); |
| 486 | } catch (\Throwable $ex) { |
| 487 | $logger = StaticContainer::get(LoggerInterface::class); |
| 488 | $logger->debug("Failed to remove invalidations the for {$pluginName} plugin."); |
| 489 | } |
| 490 | } |
| 491 | public function removeInvalidationsFromDistributedList($idSites, $pluginName = null, $report = null) |
| 492 | { |
| 493 | $list = new ReArchiveList(); |
| 494 | $entries = $list->getAll(); |
| 495 | if ($idSites === 'all') { |
| 496 | $idSites = $this->getAllSitesId(); |
| 497 | } |
| 498 | // Make sure that idSites is an array to prevent typeError |
| 499 | $idSites = is_array($idSites) ? $idSites : ($idSites !== \true ? [$idSites] : []); |
| 500 | foreach ($entries as $index => $entry) { |
| 501 | $entry = @json_decode($entry, \true); |
| 502 | if (empty($entry)) { |
| 503 | unset($entries[$index]); |
| 504 | continue; |
| 505 | } |
| 506 | $entryPluginName = $entry['pluginName']; |
| 507 | if (!empty($pluginName) && $pluginName != $entryPluginName) { |
| 508 | continue; |
| 509 | } |
| 510 | $entryReport = $entry['report']; |
| 511 | if (!empty($pluginName) && !empty($report) && $report != $entryReport) { |
| 512 | continue; |
| 513 | } |
| 514 | $sitesInEntry = $entry['idSites']; |
| 515 | if ($sitesInEntry === 'all') { |
| 516 | $sitesInEntry = $this->getAllSitesId(); |
| 517 | } |
| 518 | $diffSites = array_diff($sitesInEntry, $idSites); |
| 519 | if (empty($diffSites)) { |
| 520 | unset($entries[$index]); |
| 521 | continue; |
| 522 | } |
| 523 | $entry['idSites'] = $diffSites; |
| 524 | $entries[$index] = json_encode($entry); |
| 525 | } |
| 526 | $list->setAll(array_values($entries)); |
| 527 | } |
| 528 | /** |
| 529 | * @param int[] $idSites |
| 530 | * @param array<string, array<string, Period>> $dates |
| 531 | * @throws \Exception |
| 532 | */ |
| 533 | private function markArchivesInvalidated($idSites, $dates, ?Segment $segment = null, bool $removeRanges = \false, bool $forceInvalidateNonexistentRanges = \false, ?string $name = null, bool $doNotCreateInvalidations = \false) |
| 534 | { |
| 535 | $idSites = array_map('intval', $idSites); |
| 536 | $yearMonths = []; |
| 537 | foreach ($dates as $tableDate => $datesForTable) { |
| 538 | $tableDateObj = Date::factory($tableDate); |
| 539 | $table = ArchiveTableCreator::getNumericTable($tableDateObj, \false); |
| 540 | $yearMonths[] = $tableDateObj->toString('Y_m'); |
| 541 | $this->model->updateArchiveAsInvalidated($table, $idSites, $datesForTable, $segment, $forceInvalidateNonexistentRanges, $name, $doNotCreateInvalidations); |
| 542 | if ($removeRanges && !empty($table)) { |
| 543 | $this->model->updateRangeArchiveAsInvalidated($table, $idSites, $datesForTable, $segment); |
| 544 | } |
| 545 | } |
| 546 | $this->markInvalidatedArchivesForReprocessAndPurge($yearMonths); |
| 547 | } |
| 548 | /** |
| 549 | * @param Date[] $dates |
| 550 | * @return \Piwik\Date[] |
| 551 | */ |
| 552 | private function removeDatesThatHaveBeenPurged($dates, $period, InvalidationResult $invalidationInfo, $ignorePurgeLogDataDate) |
| 553 | { |
| 554 | $this->findOlderDateWithLogs($invalidationInfo); |
| 555 | $result = array(); |
| 556 | foreach ($dates as $date) { |
| 557 | $periodObj = $this->makePeriod($date, $period ?: 'day'); |
| 558 | // we should only delete reports for dates that are more recent than N days |
| 559 | if ($invalidationInfo->minimumDateWithLogs && !$ignorePurgeLogDataDate && ($periodObj->getDateEnd()->isEarlier($invalidationInfo->minimumDateWithLogs) || $periodObj->getDateStart()->isEarlier($invalidationInfo->minimumDateWithLogs))) { |
| 560 | $invalidationInfo->warningDates[] = $date; |
| 561 | continue; |
| 562 | } |
| 563 | $result[] = $date; |
| 564 | $invalidationInfo->processedDates[] = $date; |
| 565 | } |
| 566 | return $result; |
| 567 | } |
| 568 | private function findOlderDateWithLogs(InvalidationResult $info) |
| 569 | { |
| 570 | // If using the feature "Delete logs older than N days"... |
| 571 | $purgeDataSettings = PrivacyManager::getPurgeDataSettings(); |
| 572 | $logsDeletedWhenOlderThanDays = (int) $purgeDataSettings['delete_logs_older_than']; |
| 573 | $logsDeleteEnabled = $purgeDataSettings['delete_logs_enable']; |
| 574 | if ($logsDeleteEnabled && $logsDeletedWhenOlderThanDays) { |
| 575 | $info->minimumDateWithLogs = Date::factory('today')->subDay($logsDeletedWhenOlderThanDays); |
| 576 | } |
| 577 | } |
| 578 | /** |
| 579 | * @param array $yearMonths |
| 580 | */ |
| 581 | private function markInvalidatedArchivesForReprocessAndPurge($yearMonths) |
| 582 | { |
| 583 | $archivesToPurge = new ArchivesToPurgeDistributedList(); |
| 584 | $archivesToPurge->add($yearMonths); |
| 585 | } |
| 586 | private function getYearMonth(Period $period) |
| 587 | { |
| 588 | return $period->getDateStart()->toString('Y-m-01'); |
| 589 | } |
| 590 | private function getUniquePeriodId(Period $period) |
| 591 | { |
| 592 | return $period->getId() . '.' . $period->getRangeString(); |
| 593 | } |
| 594 | private function makePeriod($date, $period) |
| 595 | { |
| 596 | if ($period === 'range' && strpos($date, ',') === \false) { |
| 597 | $date = $date . ',' . $date; |
| 598 | return new Period\Range('range', $date); |
| 599 | } else { |
| 600 | return Period\Factory::build($period, $date); |
| 601 | } |
| 602 | } |
| 603 | private function getSegmentArchiving() |
| 604 | { |
| 605 | if (empty($this->segmentArchiving)) { |
| 606 | $this->segmentArchiving = new SegmentArchiving(); |
| 607 | } |
| 608 | return $this->segmentArchiving; |
| 609 | } |
| 610 | private function getAllSitesId() |
| 611 | { |
| 612 | if (isset($this->allIdSitesCache)) { |
| 613 | return $this->allIdSitesCache; |
| 614 | } |
| 615 | $model = new \Piwik\Plugins\SitesManager\Model(); |
| 616 | $this->allIdSitesCache = $model->getSitesId(); |
| 617 | return $this->allIdSitesCache; |
| 618 | } |
| 619 | } |
| 620 |