1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
|
<?php
/**
* Matomo - free/libre analytics platform
*
* @link https://matomo.org
* @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
namespace Piwik\Plugins\PrivacyManager;
use Piwik\Common;
use Piwik\DataAccess\ArchiveTableCreator;
use Piwik\Date;
use Piwik\Db;
use Piwik\DbHelper;
use Piwik\Piwik;
/**
* Purges archived reports and metrics that are considered old.
*/
class ReportsPurger
{
// constant used in database purging estimate to signify a table should be dropped
public const DROP_TABLE = -1;
/**
* The max set of rows each table scan select should query at one time.
*/
public static $selectSegmentSize = 100000;
/**
* The number of months after which report/metric data is considered old.
*/
private $deleteReportsOlderThan;
/**
* Whether to keep basic metrics or not.
*/
private $keepBasicMetrics;
/**
* Array of period types. Reports for these periods will not be purged.
*/
private $reportPeriodsToKeep;
/**
* Whether to keep reports for segments or not.
*/
private $keepSegmentReports;
/**
* The maximum number of rows to delete per DELETE query.
*/
private $maxRowsToDeletePerQuery;
/**
* List of metrics that should be kept when purging. If $keepBasicMetrics is true,
* these metrics will be saved.
*/
private $metricsToKeep;
/**
* Array that maps a year and month ('2012_01') with lists of archive IDs for segmented
* archives. Used to keep segmented reports when purging.
*/
private $segmentArchiveIds = null;
/**
* Constructor.
*
* @param int $deleteReportsOlderThan The number of months after which report/metric data
* is considered old.
* @param bool $keepBasicMetrics Whether to keep basic metrics or not.
* @param array $reportPeriodsToKeep Array of period types. Reports for these periods will not
* be purged.
* @param bool $keepSegmentReports Whether to keep reports for segments or not.
* @param array $metricsToKeep List of metrics that should be kept. if $keepBasicMetrics
* is true, these metrics will be saved.
* @param int $maxRowsToDeletePerQuery The maximum number of rows to delete per DELETE query.
*/
public function __construct(
$deleteReportsOlderThan,
$keepBasicMetrics,
$reportPeriodsToKeep,
$keepSegmentReports,
$metricsToKeep,
$maxRowsToDeletePerQuery
) {
$this->deleteReportsOlderThan = (int) $deleteReportsOlderThan;
$this->keepBasicMetrics = (bool) $keepBasicMetrics;
$this->reportPeriodsToKeep = $reportPeriodsToKeep;
$this->keepSegmentReports = (bool) $keepSegmentReports;
$this->metricsToKeep = $metricsToKeep;
$this->maxRowsToDeletePerQuery = (int) $maxRowsToDeletePerQuery;
}
/**
* Purges old report/metric data.
*
* If $keepBasicMetrics is false, old numeric tables will be dropped, otherwise only
* the metrics not in $metricsToKeep will be deleted.
*
* If $reportPeriodsToKeep is an empty array, old blob tables will be dropped. Otherwise,
* specific reports will be deleted, except reports for periods in $reportPeriodsToKeep.
*
* @param bool $optimize If tables should be optimized after rows are deleted. Normally,
* this is handled by a scheduled task.
*/
public function purgeData($optimize = false)
{
[$oldNumericTables, $oldBlobTables] = $this->getArchiveTablesToPurge();
// process blob tables first, since archive status is stored in the numeric archives
if (!empty($oldBlobTables)) {
foreach ($oldBlobTables as $table) {
$where = $this->getBlobTableWhereExpr($oldNumericTables, $table);
if (!empty($where)) {
$where = "WHERE $where";
}
Db::deleteAllRows($table, $where, "idarchive ASC", $this->maxRowsToDeletePerQuery);
}
if ($optimize) {
Db\Schema::getInstance()->optimizeTables($oldBlobTables);
}
}
$this->segmentArchiveIds = null;
if (!empty($oldNumericTables)) {
foreach ($oldNumericTables as $table) {
$conditions = array("name NOT LIKE 'done%'");
$bind = array();
if ($this->keepBasicMetrics && !empty($this->metricsToKeep)) {
$metricFields = Common::getSqlStringFieldsArray($this->metricsToKeep);
$bind = $this->metricsToKeep;
$conditions[] = sprintf("name NOT IN (%s)", $metricFields);
}
$keepWhere = $this->getBlobTableWhereExpr($oldNumericTables, $table);
if (!empty($keepWhere)) {
$conditions[] = $keepWhere;
}
$where = 'WHERE ' . implode(' AND ', $conditions);
Db::deleteAllRows($table, $where, "idarchive ASC", $this->maxRowsToDeletePerQuery, $bind);
}
if ($optimize) {
Db\Schema::getInstance()->optimizeTables($oldNumericTables);
}
}
}
/**
* Returns an array describing what data would be purged if purging were invoked.
*
* This function returns an array that maps table names with the number of rows
* that will be deleted. If a table name is mapped with self::DROP_TABLE, the table
* will be dropped.
*
* @return array
*/
public function getPurgeEstimate()
{
$result = array();
// get archive tables that will be purged
[$oldNumericTables, $oldBlobTables] = $this->getArchiveTablesToPurge();
// process blob tables first, since archive status is stored in the numeric archives
if (empty($this->reportPeriodsToKeep) && !$this->keepSegmentReports) {
// not keeping any reports, so drop all tables
foreach ($oldBlobTables as $table) {
$result[$table] = self::DROP_TABLE;
}
} else {
// figure out which rows will be deleted
foreach ($oldBlobTables as $table) {
$rowCount = $this->getBlobTableDeleteCount($oldNumericTables, $table);
if ($rowCount > 0) {
$result[$table] = $rowCount;
}
}
}
// deal w/ numeric tables
if ($this->keepBasicMetrics) {
// figure out which rows will be deleted
foreach ($oldNumericTables as $table) {
$rowCount = $this->getNumericTableDeleteCount($table);
if ($rowCount > 0) {
$result[$table] = $rowCount;
}
}
} else {
// not keeping any metrics, so drop the entire table
foreach ($oldNumericTables as $table) {
$result[$table] = self::DROP_TABLE;
}
}
return $result;
}
/**
* Utility function that finds every archive table whose reports are considered
* old.
*
* @return array An array of two arrays. The first holds the numeric archive table
* names, and the second holds the blob archive table names.
*/
private function getArchiveTablesToPurge()
{
// get month for which reports as old or older than, should be deleted
// reports whose creation date <= this month will be deleted
// (NOTE: we ignore how far we are in the current month)
$toRemoveDate = Date::factory('today')->subMonth(1 + $this->deleteReportsOlderThan);
// find all archive tables that are older than N months
$oldNumericTables = array();
$oldBlobTables = array();
foreach (DbHelper::getTablesInstalled() as $table) {
$type = ArchiveTableCreator::getTypeFromTableName($table);
if ($type === false) {
continue;
}
$date = ArchiveTableCreator::getDateFromTableName($table);
[$year, $month] = explode('_', $date);
if (self::shouldReportBePurged($year, $month, $toRemoveDate)) {
if ($type == ArchiveTableCreator::NUMERIC_TABLE) {
$oldNumericTables[] = $table;
} else {
$oldBlobTables[] = $table;
}
}
}
return array($oldNumericTables, $oldBlobTables);
}
/**
* Returns true if a report with the given year & month should be purged or not.
*
* @param int $reportDateYear The year of the report in question.
* @param int $reportDateMonth The month of the report in question.
* @param Date $toRemoveDate The date a report must be older than in order to be purged.
* @return bool
*/
public static function shouldReportBePurged($reportDateYear, $reportDateMonth, $toRemoveDate)
{
$toRemoveYear = (int)$toRemoveDate->toString('Y');
$toRemoveMonth = (int)$toRemoveDate->toString('m');
return $reportDateYear < $toRemoveYear
|| ($reportDateYear == $toRemoveYear && $reportDateMonth <= $toRemoveMonth);
}
private function getNumericTableDeleteCount($table)
{
$maxIdArchive = Db::fetchOne("SELECT MAX(idarchive) FROM `$table`");
$sql = "SELECT COUNT(*) FROM `$table`
WHERE name NOT IN ('" . implode("','", $this->metricsToKeep) . "')
AND name NOT LIKE 'done%'
AND idarchive >= ?
AND idarchive < ?";
$segments = Db::segmentedFetchOne($sql, 0, $maxIdArchive, self::$selectSegmentSize);
return array_sum($segments);
}
private function getBlobTableDeleteCount($oldNumericTables, $table)
{
$maxIdArchive = Db::fetchOne("SELECT MAX(idarchive) FROM `$table`");
$blobTableWhere = $this->getBlobTableWhereExpr($oldNumericTables, $table);
if (empty($blobTableWhere)) {
return 0;
}
$sql = "SELECT COUNT(*) FROM `$table`
WHERE " . $blobTableWhere . "
AND idarchive >= ?
AND idarchive < ?";
$segments = Db::segmentedFetchOne($sql, 0, $maxIdArchive, self::$selectSegmentSize);
return array_sum($segments);
}
/** Returns SQL WHERE expression used to find reports that should be purged. */
private function getBlobTableWhereExpr($oldNumericTables, $table)
{
$where = "";
if (!empty($this->reportPeriodsToKeep)) { // if keeping reports
$where = "period NOT IN (" . implode(',', $this->reportPeriodsToKeep) . ")";
// if not keeping segments make sure segments w/ kept periods are also deleted
if (!$this->keepSegmentReports) {
$this->findSegmentArchives($oldNumericTables);
$dateFromTable = ArchiveTableCreator::getDateFromTableName($table);
if (!empty($this->segmentArchiveIds[$dateFromTable])) {
$archiveIds = $this->segmentArchiveIds[$dateFromTable];
$where .= " OR idarchive IN (" . implode(',', $archiveIds) . ")";
}
}
$where = "($where)";
}
return $where;
}
/**
* If we're going to keep segmented reports, we need to know which archives are
* for segments. This info is only in the numeric tables, so we must query them.
*/
private function findSegmentArchives($numericTables)
{
if (!is_null($this->segmentArchiveIds) || empty($numericTables)) {
return;
}
foreach ($numericTables as $table) {
$tableDate = ArchiveTableCreator::getDateFromTableName($table);
$maxIdArchive = Db::fetchOne("SELECT MAX(idarchive) FROM `$table`");
$sql = "SELECT idarchive FROM `$table`
WHERE name != 'done'
AND name LIKE 'done_%.%'
AND idarchive >= ?
AND idarchive < ?";
if (is_null($this->segmentArchiveIds)) {
$this->segmentArchiveIds = array();
}
$this->segmentArchiveIds[$tableDate] = array();
foreach (Db::segmentedFetchAll($sql, 0, $maxIdArchive, self::$selectSegmentSize) as $row) {
$this->segmentArchiveIds[$tableDate][] = $row['idarchive'];
}
}
}
/**
* Utility function. Creates a new instance of ReportsPurger with the supplied array
* of settings.
*
* $settings must contain the following keys:
* -'delete_reports_older_than': The number of months after which reports/metrics are
* considered old.
* -'delete_reports_keep_basic_metrics': 1 if basic metrics should be kept, 0 if otherwise.
* -'delete_reports_keep_day_reports': 1 if daily reports should be kept, 0 if otherwise.
* -'delete_reports_keep_week_reports': 1 if weekly reports should be kept, 0 if otherwise.
* -'delete_reports_keep_month_reports': 1 if monthly reports should be kept, 0 if otherwise.
* -'delete_reports_keep_year_reports': 1 if yearly reports should be kept, 0 if otherwise.
* -'delete_reports_keep_range_reports': 1 if range reports should be kept, 0 if otherwise.
* -'delete_reports_keep_segment_reports': 1 if reports for segments should be kept, 0 if otherwise.
* -'delete_logs_max_rows_per_query': Maximum number of rows to delete in one DELETE query.
*/
public static function make($settings, $metricsToKeep)
{
return new ReportsPurger(
$settings['delete_reports_older_than'],
$settings['delete_reports_keep_basic_metrics'] == 1,
self::getReportPeriodsToKeep($settings),
$settings['delete_reports_keep_segment_reports'] == 1,
$metricsToKeep,
$settings['delete_logs_max_rows_per_query']
);
}
/**
* Utility function that returns an array period values based on the 'delete_reports_keep_*'
* settings. The period values returned are the integer values stored in the DB.
*
* @param array $settings The settings to use.
* @return array An array of period values that should be kept when purging old data.
*/
private static function getReportPeriodsToKeep($settings)
{
$keepReportPeriods = array();
foreach (Piwik::$idPeriods as $strPeriod => $intPeriod) {
$optionName = "delete_reports_keep_{$strPeriod}_reports";
if ($settings[$optionName] == 1) {
$keepReportPeriods[] = $intPeriod;
}
}
return $keepReportPeriods;
}
}
|