3 * Rebuild recent changes from scratch. This takes several hours,
4 * depending on the database size and server configuration.
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
22 * @ingroup Maintenance
26 require_once __DIR__
. '/Maintenance.php';
28 use MediaWiki\MediaWikiServices
;
29 use Wikimedia\Rdbms\IDatabase
;
30 use Wikimedia\Rdbms\ILBFactory
;
33 * Maintenance script that rebuilds recent changes from scratch.
35 * @ingroup Maintenance
37 class RebuildRecentchanges
extends Maintenance
{
38 /** @var int UNIX timestamp */
40 /** @var int UNIX timestamp */
43 public function __construct() {
44 parent
::__construct();
45 $this->addDescription( 'Rebuild recent changes' );
49 "Only rebuild rows in requested time range (in YYYYMMDDHHMMSS format)",
55 "Only rebuild rows in requested time range (in YYYYMMDDHHMMSS format)",
59 $this->setBatchSize( 200 );
62 public function execute() {
64 ( $this->hasOption( 'from' ) && !$this->hasOption( 'to' ) ) ||
65 ( !$this->hasOption( 'from' ) && $this->hasOption( 'to' ) )
67 $this->fatalError( "Both 'from' and 'to' must be given, or neither" );
70 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
71 $this->rebuildRecentChangesTablePass1( $lbFactory );
72 $this->rebuildRecentChangesTablePass2( $lbFactory );
73 $this->rebuildRecentChangesTablePass3( $lbFactory );
74 $this->rebuildRecentChangesTablePass4( $lbFactory );
75 $this->rebuildRecentChangesTablePass5( $lbFactory );
76 if ( !( $this->hasOption( 'from' ) && $this->hasOption( 'to' ) ) ) {
79 $this->output( "Done.\n" );
83 * Rebuild pass 1: Insert `recentchanges` entries for page revisions.
85 * @param ILBFactory $lbFactory
87 private function rebuildRecentChangesTablePass1( ILBFactory
$lbFactory ) {
88 $dbw = $this->getDB( DB_MASTER
);
89 $commentStore = CommentStore
::getStore();
91 if ( $this->hasOption( 'from' ) && $this->hasOption( 'to' ) ) {
92 $this->cutoffFrom
= wfTimestamp( TS_UNIX
, $this->getOption( 'from' ) );
93 $this->cutoffTo
= wfTimestamp( TS_UNIX
, $this->getOption( 'to' ) );
95 $sec = $this->cutoffTo
- $this->cutoffFrom
;
96 $days = $sec / 24 / 3600;
97 $this->output( "Rebuilding range of $sec seconds ($days days)\n" );
101 $days = $wgRCMaxAge / 24 / 3600;
102 $this->output( "Rebuilding \$wgRCMaxAge=$wgRCMaxAge seconds ($days days)\n" );
104 $this->cutoffFrom
= time() - $wgRCMaxAge;
105 $this->cutoffTo
= time();
108 $this->output( "Clearing recentchanges table for time range...\n" );
109 $rcids = $dbw->selectFieldValues(
113 'rc_timestamp > ' . $dbw->addQuotes( $dbw->timestamp( $this->cutoffFrom
) ),
114 'rc_timestamp < ' . $dbw->addQuotes( $dbw->timestamp( $this->cutoffTo
) )
118 foreach ( array_chunk( $rcids, $this->getBatchSize() ) as $rcidBatch ) {
119 $dbw->delete( 'recentchanges', [ 'rc_id' => $rcidBatch ], __METHOD__
);
120 $lbFactory->waitForReplication();
123 $this->output( "Loading from page and revision tables...\n" );
125 $commentQuery = $commentStore->getJoin( 'rev_comment' );
126 $actorQuery = ActorMigration
::newMigration()->getJoin( 'rev_user' );
128 [ 'revision', 'page' ] +
$commentQuery['tables'] +
$actorQuery['tables'],
138 ] +
$commentQuery['fields'] +
$actorQuery['fields'],
140 'rev_timestamp > ' . $dbw->addQuotes( $dbw->timestamp( $this->cutoffFrom
) ),
141 'rev_timestamp < ' . $dbw->addQuotes( $dbw->timestamp( $this->cutoffTo
) )
144 [ 'ORDER BY' => 'rev_timestamp DESC' ],
146 'page' => [ 'JOIN', 'rev_page=page_id' ],
147 ] +
$commentQuery['joins'] +
$actorQuery['joins']
150 $this->output( "Inserting from page and revision tables...\n" );
152 $actorMigration = ActorMigration
::newMigration();
153 foreach ( $res as $row ) {
154 $comment = $commentStore->getComment( 'rev_comment', $row );
155 $user = User
::newFromAnyId( $row->rev_user
, $row->rev_user_text
, $row->rev_actor
);
159 'rc_timestamp' => $row->rev_timestamp
,
160 'rc_namespace' => $row->page_namespace
,
161 'rc_title' => $row->page_title
,
162 'rc_minor' => $row->rev_minor_edit
,
164 'rc_new' => $row->page_is_new
,
165 'rc_cur_id' => $row->page_id
,
166 'rc_this_oldid' => $row->rev_id
,
167 'rc_last_oldid' => 0, // is this ok?
168 'rc_type' => $row->page_is_new ? RC_NEW
: RC_EDIT
,
169 'rc_source' => $row->page_is_new ? RecentChange
::SRC_NEW
: RecentChange
::SRC_EDIT
,
170 'rc_deleted' => $row->rev_deleted
171 ] +
$commentStore->insert( $dbw, 'rc_comment', $comment )
172 +
$actorMigration->getInsertValues( $dbw, 'rc_user', $user ),
176 $rcid = $dbw->insertId();
179 [ 'ct_rc_id' => $rcid ],
180 [ 'ct_rev_id' => $row->rev_id
],
184 if ( ( ++
$inserted %
$this->getBatchSize() ) == 0 ) {
185 $lbFactory->waitForReplication();
191 * Rebuild pass 2: Enhance entries for page revisions with references to the previous revision
192 * (rc_last_oldid, rc_new etc.) and size differences (rc_old_len, rc_new_len).
194 * @param ILBFactory $lbFactory
196 private function rebuildRecentChangesTablePass2( ILBFactory
$lbFactory ) {
197 $dbw = $this->getDB( DB_MASTER
);
199 $this->output( "Updating links and size differences...\n" );
201 # Fill in the rc_last_oldid field, which points to the previous edit
204 [ 'rc_cur_id', 'rc_this_oldid', 'rc_timestamp' ],
206 "rc_timestamp > " . $dbw->addQuotes( $dbw->timestamp( $this->cutoffFrom
) ),
207 "rc_timestamp < " . $dbw->addQuotes( $dbw->timestamp( $this->cutoffTo
) )
210 [ 'ORDER BY' => [ 'rc_cur_id', 'rc_timestamp' ] ]
217 foreach ( $res as $row ) {
220 if ( $row->rc_cur_id
!= $lastCurId ) {
221 # Switch! Look up the previous last edit, if any
222 $lastCurId = intval( $row->rc_cur_id
);
223 $emit = $row->rc_timestamp
;
225 $revRow = $dbw->selectRow(
227 [ 'rev_id', 'rev_len' ],
228 [ 'rev_page' => $lastCurId, "rev_timestamp < " . $dbw->addQuotes( $emit ) ],
230 [ 'ORDER BY' => 'rev_timestamp DESC' ]
233 $lastOldId = intval( $revRow->rev_id
);
234 # Grab the last text size if available
235 $lastSize = $revRow->rev_len
!== null ?
intval( $revRow->rev_len
) : null;
240 $new = 1; // probably true
244 if ( $lastCurId == 0 ) {
245 $this->output( "Uhhh, something wrong? No curid\n" );
247 # Grab the entry's text size
248 $size = (int)$dbw->selectField(
251 [ 'rev_id' => $row->rc_this_oldid
],
258 'rc_last_oldid' => $lastOldId,
260 'rc_type' => $new ? RC_NEW
: RC_EDIT
,
261 'rc_source' => $new === 1 ? RecentChange
::SRC_NEW
: RecentChange
::SRC_EDIT
,
262 'rc_old_len' => $lastSize,
263 'rc_new_len' => $size,
266 'rc_cur_id' => $lastCurId,
267 'rc_this_oldid' => $row->rc_this_oldid
,
268 'rc_timestamp' => $row->rc_timestamp
// index usage
273 $lastOldId = intval( $row->rc_this_oldid
);
276 if ( ( ++
$updated %
$this->getBatchSize() ) == 0 ) {
277 $lbFactory->waitForReplication();
284 * Rebuild pass 3: Insert `recentchanges` entries for action logs.
286 * @param ILBFactory $lbFactory
288 private function rebuildRecentChangesTablePass3( ILBFactory
$lbFactory ) {
289 global $wgLogRestrictions, $wgFilterLogTypes;
291 $dbw = $this->getDB( DB_MASTER
);
292 $commentStore = CommentStore
::getStore();
293 $nonRCLogs = array_merge( array_keys( $wgLogRestrictions ),
294 array_keys( $wgFilterLogTypes ),
297 $this->output( "Loading from user and logging tables...\n" );
299 $commentQuery = $commentStore->getJoin( 'log_comment' );
300 $actorQuery = ActorMigration
::newMigration()->getJoin( 'log_user' );
302 [ 'logging' ] +
$commentQuery['tables'] +
$actorQuery['tables'],
313 ] +
$commentQuery['fields'] +
$actorQuery['fields'],
315 'log_timestamp > ' . $dbw->addQuotes( $dbw->timestamp( $this->cutoffFrom
) ),
316 'log_timestamp < ' . $dbw->addQuotes( $dbw->timestamp( $this->cutoffTo
) ),
317 // Some logs don't go in RC since they are private, or are included in the filterable log types.
318 'log_type' => array_diff( LogPage
::validTypes(), $nonRCLogs ),
321 [ 'ORDER BY' => 'log_timestamp DESC' ],
322 $commentQuery['joins'] +
$actorQuery['joins']
325 $field = $dbw->fieldInfo( 'recentchanges', 'rc_cur_id' );
328 $actorMigration = ActorMigration
::newMigration();
329 foreach ( $res as $row ) {
330 $comment = $commentStore->getComment( 'log_comment', $row );
331 $user = User
::newFromAnyId( $row->log_user
, $row->log_user_text
, $row->log_actor
);
335 'rc_timestamp' => $row->log_timestamp
,
336 'rc_namespace' => $row->log_namespace
,
337 'rc_title' => $row->log_title
,
340 'rc_patrolled' => $row->log_type
== 'upload' ?
0 : 2,
342 'rc_this_oldid' => 0,
343 'rc_last_oldid' => 0,
345 'rc_source' => RecentChange
::SRC_LOG
,
346 'rc_cur_id' => $field->isNullable()
348 : (int)$row->log_page
, // NULL => 0,
349 'rc_log_type' => $row->log_type
,
350 'rc_log_action' => $row->log_action
,
351 'rc_logid' => $row->log_id
,
352 'rc_params' => $row->log_params
,
353 'rc_deleted' => $row->log_deleted
354 ] +
$commentStore->insert( $dbw, 'rc_comment', $comment )
355 +
$actorMigration->getInsertValues( $dbw, 'rc_user', $user ),
359 $rcid = $dbw->insertId();
362 [ 'ct_rc_id' => $rcid ],
363 [ 'ct_log_id' => $row->log_id
],
367 if ( ( ++
$inserted %
$this->getBatchSize() ) == 0 ) {
368 $lbFactory->waitForReplication();
374 * Rebuild pass 4: Mark bot and autopatrolled entries.
376 * @param ILBFactory $lbFactory
378 private function rebuildRecentChangesTablePass4( ILBFactory
$lbFactory ) {
379 global $wgUseRCPatrol, $wgUseNPPatrol, $wgUseFilePatrol, $wgMiserMode;
381 $dbw = $this->getDB( DB_MASTER
);
383 $userQuery = User
::getQueryInfo();
385 # @FIXME: recognize other bot account groups (not the same as users with 'bot' rights)
386 # @NOTE: users with 'bot' rights choose when edits are bot edits or not. That information
387 # may be lost at this point (aside from joining on the patrol log table entries).
388 $botgroups = [ 'bot' ];
389 $autopatrolgroups = ( $wgUseRCPatrol ||
$wgUseNPPatrol ||
$wgUseFilePatrol ) ?
390 MediaWikiServices
::getInstance()->getPermissionManager()
391 ->getGroupsWithPermission( 'autopatrol' ) : [];
393 # Flag our recent bot edits
394 // @phan-suppress-next-line PhanRedundantCondition
396 $this->output( "Flagging bot account edits...\n" );
398 # Find all users that are bots
400 array_merge( [ 'user_groups' ], $userQuery['tables'] ),
401 $userQuery['fields'],
402 [ 'ug_group' => $botgroups ],
405 [ 'user_groups' => [ 'JOIN', 'user_id = ug_user' ] ] +
$userQuery['joins']
409 foreach ( $res as $row ) {
410 $botusers[] = User
::newFromRow( $row );
413 # Fill in the rc_bot field
415 $actorQuery = ActorMigration
::newMigration()->getWhere( $dbw, 'rc_user', $botusers, false );
417 foreach ( $actorQuery['orconds'] as $cond ) {
418 $rcids = array_merge( $rcids, $dbw->selectFieldValues(
419 [ 'recentchanges' ] +
$actorQuery['tables'],
422 "rc_timestamp > " . $dbw->addQuotes( $dbw->timestamp( $this->cutoffFrom
) ),
423 "rc_timestamp < " . $dbw->addQuotes( $dbw->timestamp( $this->cutoffTo
) ),
431 $rcids = array_values( array_unique( $rcids ) );
433 foreach ( array_chunk( $rcids, $this->getBatchSize() ) as $rcidBatch ) {
437 [ 'rc_id' => $rcidBatch ],
440 $lbFactory->waitForReplication();
445 # Flag our recent autopatrolled edits
446 if ( !$wgMiserMode && $autopatrolgroups ) {
449 $this->output( "Flagging auto-patrolled edits...\n" );
451 # Find all users in RC with autopatrol rights
453 array_merge( [ 'user_groups' ], $userQuery['tables'] ),
454 $userQuery['fields'],
455 [ 'ug_group' => $autopatrolgroups ],
458 [ 'user_groups' => [ 'JOIN', 'user_id = ug_user' ] ] +
$userQuery['joins']
461 foreach ( $res as $row ) {
462 $patrolusers[] = User
::newFromRow( $row );
465 # Fill in the rc_patrolled field
466 if ( $patrolusers ) {
467 $actorQuery = ActorMigration
::newMigration()->getWhere( $dbw, 'rc_user', $patrolusers, false );
468 foreach ( $actorQuery['orconds'] as $cond ) {
471 'rc_timestamp > ' . $dbw->addQuotes( $dbw->timestamp( $this->cutoffFrom
) ),
472 'rc_timestamp < ' . $dbw->addQuotes( $dbw->timestamp( $this->cutoffTo
) ),
476 if ( !$wgUseRCPatrol ) {
478 if ( $wgUseNPPatrol ) {
479 $subConds[] = 'rc_source = ' . $dbw->addQuotes( RecentChange
::SRC_NEW
);
481 if ( $wgUseFilePatrol ) {
482 $subConds[] = 'rc_log_type = ' . $dbw->addQuotes( 'upload' );
484 $conds[] = $dbw->makeList( $subConds, IDatabase
::LIST_OR
);
489 [ 'rc_patrolled' => 2 ],
493 $lbFactory->waitForReplication();
500 * Rebuild pass 5: Delete duplicate entries where we generate both a page revision and a log
501 * entry for a single action (upload, move, protect, import, etc.).
503 * @param ILBFactory $lbFactory
505 private function rebuildRecentChangesTablePass5( ILBFactory
$lbFactory ) {
506 $dbw = wfGetDB( DB_MASTER
);
508 $this->output( "Removing duplicate revision and logging entries...\n" );
511 [ 'logging', 'log_search' ],
512 [ 'ls_value', 'ls_log_id' ],
514 'ls_log_id = log_id',
515 'ls_field' => 'associated_rev_id',
516 'log_type != ' . $dbw->addQuotes( 'create' ),
517 'log_timestamp > ' . $dbw->addQuotes( $dbw->timestamp( $this->cutoffFrom
) ),
518 'log_timestamp < ' . $dbw->addQuotes( $dbw->timestamp( $this->cutoffTo
) ),
524 foreach ( $res as $row ) {
525 $rev_id = $row->ls_value
;
526 $log_id = $row->ls_log_id
;
528 // Mark the logging row as having an associated rev id
531 /*SET*/ [ 'rc_this_oldid' => $rev_id ],
532 /*WHERE*/ [ 'rc_logid' => $log_id ],
536 // Delete the revision row
539 /*WHERE*/ [ 'rc_this_oldid' => $rev_id, 'rc_logid' => 0 ],
543 if ( ( ++
$updates %
$this->getBatchSize() ) == 0 ) {
544 $lbFactory->waitForReplication();
550 * Purge cached feeds in $wanCache
552 private function purgeFeeds() {
553 global $wgFeedClasses;
555 $this->output( "Deleting feed timestamps.\n" );
557 $wanCache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
558 foreach ( $wgFeedClasses as $feed => $className ) {
559 $wanCache->delete( $wanCache->makeKey( 'rcfeed', $feed, 'timestamp' ) ); # Good enough for now.
564 $maintClass = RebuildRecentchanges
::class;
565 require_once RUN_MAINTENANCE_IF_MAIN
;