summaryrefslogtreecommitdiff
blob: 7046ac9eac772bb7ead8b2a1ec443efda69b8a4d (plain)
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
<?php

use MediaWiki\MediaWikiServices;

if ( getenv( 'MW_INSTALL_PATH' ) ) {
	$IP = getenv( 'MW_INSTALL_PATH' );
} else {
	$IP = __DIR__ . '/../../..';
}
require_once "$IP/maintenance/Maintenance.php";

class PurgeOldData extends Maintenance {
	public function __construct() {
		parent::__construct();
		$this->addDescription( 'Purge expired rows in CheckUser and RecentChanges' );
		$this->setBatchSize( 200 );

		$this->requireExtension( 'CheckUser' );
	}

	public function execute() {
		global $wgCUDMaxAge, $wgRCMaxAge, $wgPutIPinRC;

		$this->output( "Purging data from cu_changes..." );
		$count = $this->prune( 'cu_changes', 'cuc_timestamp', $wgCUDMaxAge );
		$this->output( $count . " rows.\n" );

		if ( $wgPutIPinRC ) {
			$this->output( "Purging data from recentchanges..." );
			$count = $this->prune( 'recentchanges', 'rc_timestamp', $wgRCMaxAge );
			$this->output( $count . " rows.\n" );
		}

		$this->output( "Done.\n" );
	}

	protected function prune( $table, $ts_column, $maxAge ) {
		$dbw = wfGetDB( DB_MASTER );

		$lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();

		$expiredCond = "$ts_column < " . $dbw->addQuotes( $dbw->timestamp( time() - $maxAge ) );

		$count = 0;
		while ( true ) {
			// Get the first $this->mBatchSize (or less) items
			$res = $dbw->select( $table, $ts_column,
				$expiredCond,
				__METHOD__,
				[ 'ORDER BY' => "$ts_column ASC", 'LIMIT' => $this->mBatchSize ]
			);
			if ( !$res->numRows() ) {
				break; // all cleared
			}
			// Record the start and end timestamp for the set
			$blockStart = $dbw->addQuotes( $res->fetchRow()[$ts_column] );
			$res->seek( $res->numRows() - 1 );
			$blockEnd = $dbw->addQuotes( $res->fetchRow()[$ts_column] );
			$res->free();

			// Do the actual delete...
			$this->beginTransaction( $dbw, __METHOD__ );
			$dbw->delete( $table,
				[ "$ts_column BETWEEN $blockStart AND $blockEnd" ], __METHOD__ );
			$count += $dbw->affectedRows();
			$this->commitTransaction( $dbw, __METHOD__ );

			$lbFactory->waitForReplication();
		}

		return $count;
	}
}

$maintClass = PurgeOldData::class;
require_once RUN_MAINTENANCE_IF_MAIN;