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 // @codeCoverageIgnoreStart
27 require_once __DIR__
. '/Maintenance.php';
28 // @codeCoverageIgnoreEnd
30 use MediaWiki\Maintenance\Maintenance
;
31 use Wikimedia\Rdbms\IDatabase
;
32 use Wikimedia\Rdbms\IReadableDatabase
;
33 use Wikimedia\Rdbms\SelectQueryBuilder
;
36 * Maintenance script that rebuilds recent changes from scratch.
38 * @ingroup Maintenance
40 class RebuildRecentchanges
extends Maintenance
{
41 /** @var int UNIX timestamp */
43 /** @var int UNIX timestamp */
46 public function __construct() {
47 parent
::__construct();
48 $this->addDescription( 'Rebuild recent changes' );
52 "Only rebuild rows in requested time range (in YYYYMMDDHHMMSS format)",
58 "Only rebuild rows in requested time range (in YYYYMMDDHHMMSS format)",
62 $this->setBatchSize( 200 );
65 public function execute() {
67 ( $this->hasOption( 'from' ) && !$this->hasOption( 'to' ) ) ||
68 ( !$this->hasOption( 'from' ) && $this->hasOption( 'to' ) )
70 $this->fatalError( "Both 'from' and 'to' must be given, or neither" );
73 $this->rebuildRecentChangesTablePass1();
74 $this->rebuildRecentChangesTablePass2();
75 $this->rebuildRecentChangesTablePass3();
76 $this->rebuildRecentChangesTablePass4();
77 $this->rebuildRecentChangesTablePass5();
78 if ( !( $this->hasOption( 'from' ) && $this->hasOption( 'to' ) ) ) {
81 $this->output( "Done.\n" );
85 * Rebuild pass 1: Insert `recentchanges` entries for page revisions.
87 private function rebuildRecentChangesTablePass1() {
88 $dbw = $this->getPrimaryDB();
89 $commentStore = $this->getServiceContainer()->getCommentStore();
91 if ( $this->hasOption( 'from' ) && $this->hasOption( 'to' ) ) {
92 $this->cutoffFrom
= (int)wfTimestamp( TS_UNIX
, $this->getOption( 'from' ) );
93 $this->cutoffTo
= (int)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->newSelectQueryBuilder()
111 ->from( 'recentchanges' )
112 ->where( $dbw->expr( 'rc_timestamp', '>', $dbw->timestamp( $this->cutoffFrom
) ) )
113 ->andWhere( $dbw->expr( 'rc_timestamp', '<', $dbw->timestamp( $this->cutoffTo
) ) )
114 ->caller( __METHOD__
)->fetchFieldValues();
115 foreach ( array_chunk( $rcids, $this->getBatchSize() ) as $rcidBatch ) {
116 $dbw->newDeleteQueryBuilder()
117 ->deleteFrom( 'recentchanges' )
118 ->where( [ 'rc_id' => $rcidBatch ] )
119 ->caller( __METHOD__
)->execute();
120 $this->waitForReplication();
123 $this->output( "Loading from page and revision tables...\n" );
125 $res = $dbw->newSelectQueryBuilder()
136 'rev_comment_text' => 'comment_rev_comment.comment_text',
137 'rev_comment_data' => 'comment_rev_comment.comment_data',
138 'rev_comment_cid' => 'comment_rev_comment.comment_id',
139 'rev_user' => 'actor_rev_user.actor_user',
140 'rev_user_text' => 'actor_rev_user.actor_name',
141 'rev_actor' => 'rev_actor',
145 ->join( 'page', null, 'rev_page=page_id' )
146 ->join( 'comment', 'comment_rev_comment', 'comment_rev_comment.comment_id = rev_comment_id' )
147 ->join( 'actor', 'actor_rev_user', 'actor_rev_user.actor_id = rev_actor' )
150 $dbw->expr( 'rev_timestamp', '>', $dbw->timestamp( $this->cutoffFrom
) ),
151 $dbw->expr( 'rev_timestamp', '<', $dbw->timestamp( $this->cutoffTo
) )
154 ->orderBy( 'rev_timestamp', SelectQueryBuilder
::SORT_DESC
)
155 ->caller( __METHOD__
)->fetchResultSet();
157 $this->output( "Inserting from page and revision tables...\n" );
159 foreach ( $res as $row ) {
160 $comment = $commentStore->getComment( 'rev_comment', $row );
161 $dbw->newInsertQueryBuilder()
162 ->insertInto( 'recentchanges' )
164 'rc_timestamp' => $row->rev_timestamp
,
165 'rc_actor' => $row->rev_actor
,
166 'rc_namespace' => $row->page_namespace
,
167 'rc_title' => $row->page_title
,
168 'rc_minor' => $row->rev_minor_edit
,
170 'rc_new' => $row->page_is_new
,
171 'rc_cur_id' => $row->page_id
,
172 'rc_this_oldid' => $row->rev_id
,
173 'rc_last_oldid' => 0, // is this ok?
174 'rc_type' => $row->page_is_new ? RC_NEW
: RC_EDIT
,
175 'rc_source' => $row->page_is_new ? RecentChange
::SRC_NEW
: RecentChange
::SRC_EDIT
,
176 'rc_deleted' => $row->rev_deleted
177 ] +
$commentStore->insert( $dbw, 'rc_comment', $comment ) )
178 ->caller( __METHOD__
)->execute();
180 $rcid = $dbw->insertId();
181 $dbw->newUpdateQueryBuilder()
182 ->update( 'change_tag' )
183 ->set( [ 'ct_rc_id' => $rcid ] )
184 ->where( [ 'ct_rev_id' => $row->rev_id
] )
185 ->caller( __METHOD__
)->execute();
187 if ( ( ++
$inserted %
$this->getBatchSize() ) == 0 ) {
188 $this->waitForReplication();
194 * Rebuild pass 2: Enhance entries for page revisions with references to the previous revision
195 * (rc_last_oldid, rc_new etc.) and size differences (rc_old_len, rc_new_len).
197 private function rebuildRecentChangesTablePass2() {
198 $dbw = $this->getPrimaryDB();
200 $this->output( "Updating links and size differences...\n" );
202 # Fill in the rc_last_oldid field, which points to the previous edit
203 $res = $dbw->newSelectQueryBuilder()
204 ->select( [ 'rc_cur_id', 'rc_this_oldid', 'rc_timestamp' ] )
205 ->from( 'recentchanges' )
206 ->where( $dbw->expr( 'rc_timestamp', '>', $dbw->timestamp( $this->cutoffFrom
) ) )
207 ->andWhere( $dbw->expr( 'rc_timestamp', '<', $dbw->timestamp( $this->cutoffTo
) ) )
208 ->orderBy( [ 'rc_cur_id', 'rc_timestamp' ] )
209 ->caller( __METHOD__
)->fetchResultSet();
215 foreach ( $res as $row ) {
218 if ( $row->rc_cur_id
!= $lastCurId ) {
219 # Switch! Look up the previous last edit, if any
220 $lastCurId = intval( $row->rc_cur_id
);
221 $emit = $row->rc_timestamp
;
223 $revRow = $dbw->newSelectQueryBuilder()
224 ->select( [ 'rev_id', 'rev_len' ] )
226 ->where( [ 'rev_page' => $lastCurId, $dbw->expr( 'rev_timestamp', '<', $emit ) ] )
227 ->orderBy( 'rev_timestamp DESC' )
228 ->caller( __METHOD__
)->fetchRow();
230 $lastOldId = intval( $revRow->rev_id
);
231 # Grab the last text size if available
232 $lastSize = $revRow->rev_len
!== null ?
intval( $revRow->rev_len
) : null;
237 $new = 1; // probably true
241 if ( $lastCurId == 0 ) {
242 $this->output( "Uhhh, something wrong? No curid\n" );
244 # Grab the entry's text size
245 $size = (int)$dbw->newSelectQueryBuilder()
246 ->select( 'rev_len' )
248 ->where( [ 'rev_id' => $row->rc_this_oldid
] )
249 ->caller( __METHOD__
)->fetchField();
251 $dbw->newUpdateQueryBuilder()
252 ->update( 'recentchanges' )
254 'rc_last_oldid' => $lastOldId,
256 'rc_type' => $new ? RC_NEW
: RC_EDIT
,
257 'rc_source' => $new === 1 ? RecentChange
::SRC_NEW
: RecentChange
::SRC_EDIT
,
258 'rc_old_len' => $lastSize,
259 'rc_new_len' => $size,
262 'rc_cur_id' => $lastCurId,
263 'rc_this_oldid' => $row->rc_this_oldid
,
265 'rc_timestamp' => $row->rc_timestamp
,
267 ->caller( __METHOD__
)->execute();
269 $lastOldId = intval( $row->rc_this_oldid
);
272 if ( ( ++
$updated %
$this->getBatchSize() ) == 0 ) {
273 $this->waitForReplication();
280 * Rebuild pass 3: Insert `recentchanges` entries for action logs.
282 private function rebuildRecentChangesTablePass3() {
283 global $wgLogRestrictions, $wgFilterLogTypes;
285 $dbw = $this->getDB( DB_PRIMARY
);
286 $commentStore = $this->getServiceContainer()->getCommentStore();
287 $nonRCLogs = array_merge(
288 array_keys( $wgLogRestrictions ),
289 array_keys( $wgFilterLogTypes ),
293 $this->output( "Loading from user and logging tables...\n" );
295 $res = $dbw->newSelectQueryBuilder()
308 'log_comment_text' => 'comment_log_comment.comment_text',
309 'log_comment_data' => 'comment_log_comment.comment_data',
310 'log_comment_cid' => 'comment_log_comment.comment_id',
314 ->join( 'comment', 'comment_log_comment', 'comment_log_comment.comment_id = log_comment_id' )
317 $dbw->expr( 'log_timestamp', '>', $dbw->timestamp( $this->cutoffFrom
) ),
318 $dbw->expr( 'log_timestamp', '<', $dbw->timestamp( $this->cutoffTo
) ),
319 // Some logs don't go in RC since they are private, or are included in the filterable log types.
320 'log_type' => array_diff( LogPage
::validTypes(), $nonRCLogs ),
323 ->orderBy( [ 'log_timestamp DESC', 'log_id DESC' ] )
324 ->caller( __METHOD__
)->fetchResultSet();
326 $field = $dbw->fieldInfo( 'recentchanges', 'rc_cur_id' );
329 foreach ( $res as $row ) {
330 $comment = $commentStore->getComment( 'log_comment', $row );
331 $dbw->newInsertQueryBuilder()
332 ->insertInto( 'recentchanges' )
334 'rc_timestamp' => $row->log_timestamp
,
335 'rc_actor' => $row->log_actor
,
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 ->caller( __METHOD__
)->execute();
357 $rcid = $dbw->insertId();
358 $dbw->newUpdateQueryBuilder()
359 ->update( 'change_tag' )
360 ->set( [ 'ct_rc_id' => $rcid ] )
361 ->where( [ 'ct_log_id' => $row->log_id
] )
362 ->caller( __METHOD__
)->execute();
364 if ( ( ++
$inserted %
$this->getBatchSize() ) == 0 ) {
365 $this->waitForReplication();
371 * Find rc_id values that have a user with one of the specified groups
373 * @param IReadableDatabase $db
374 * @param string[] $groups
375 * @param array $conds Extra query conditions
378 private function findRcIdsWithGroups( $db, $groups, $conds = [] ) {
379 if ( !count( $groups ) ) {
382 return $db->newSelectQueryBuilder()
385 ->from( 'recentchanges' )
386 ->join( 'actor', null, 'actor_id=rc_actor' )
387 ->join( 'user_groups', null, 'ug_user=actor_user' )
390 $db->expr( 'rc_timestamp', '>', $db->timestamp( $this->cutoffFrom
) ),
391 $db->expr( 'rc_timestamp', '<', $db->timestamp( $this->cutoffTo
) ),
392 'ug_group' => $groups
394 ->caller( __METHOD__
)->fetchFieldValues();
398 * Rebuild pass 4: Mark bot and autopatrolled entries.
400 private function rebuildRecentChangesTablePass4() {
401 global $wgUseRCPatrol, $wgUseNPPatrol, $wgUseFilePatrol, $wgMiserMode;
403 $dbw = $this->getPrimaryDB();
405 # @FIXME: recognize other bot account groups (not the same as users with 'bot' rights)
406 # @NOTE: users with 'bot' rights choose when edits are bot edits or not. That information
407 # may be lost at this point (aside from joining on the patrol log table entries).
408 $botgroups = [ 'bot' ];
409 $autopatrolgroups = ( $wgUseRCPatrol ||
$wgUseNPPatrol ||
$wgUseFilePatrol ) ?
410 $this->getServiceContainer()->getGroupPermissionsLookup()
411 ->getGroupsWithPermission( 'autopatrol' ) : [];
413 # Flag our recent bot edits
414 // @phan-suppress-next-line PhanRedundantCondition
416 $this->output( "Flagging bot account edits...\n" );
418 # Fill in the rc_bot field
419 $rcids = $this->findRcIdsWithGroups( $dbw, $botgroups );
421 foreach ( array_chunk( $rcids, $this->getBatchSize() ) as $rcidBatch ) {
422 $dbw->newUpdateQueryBuilder()
423 ->update( 'recentchanges' )
424 ->set( [ 'rc_bot' => 1 ] )
425 ->where( [ 'rc_id' => $rcidBatch ] )
426 ->caller( __METHOD__
)->execute();
427 $this->waitForReplication();
431 # Flag our recent autopatrolled edits
432 if ( !$wgMiserMode && $autopatrolgroups ) {
433 $this->output( "Flagging auto-patrolled edits...\n" );
435 $conds = [ 'rc_patrolled' => 0 ];
436 if ( !$wgUseRCPatrol ) {
438 if ( $wgUseNPPatrol ) {
439 $subConds[] = $dbw->expr( 'rc_source', '=', RecentChange
::SRC_NEW
);
441 if ( $wgUseFilePatrol ) {
442 $subConds[] = $dbw->expr( 'rc_log_type', '=', 'upload' );
444 $conds[] = $dbw->makeList( $subConds, IDatabase
::LIST_OR
);
447 $rcids = $this->findRcIdsWithGroups( $dbw, $autopatrolgroups, $conds );
448 foreach ( array_chunk( $rcids, $this->getBatchSize() ) as $rcidBatch ) {
449 $dbw->newUpdateQueryBuilder()
450 ->update( 'recentchanges' )
451 ->set( [ 'rc_patrolled' => 2 ] )
452 ->where( [ 'rc_id' => $rcidBatch ] )
453 ->caller( __METHOD__
)->execute();
454 $this->waitForReplication();
460 * Rebuild pass 5: Delete duplicate entries where we generate both a page revision and a log
461 * entry for a single action (upload, move, protect, import, etc.).
463 private function rebuildRecentChangesTablePass5() {
464 $dbw = $this->getPrimaryDB();
466 $this->output( "Removing duplicate revision and logging entries...\n" );
468 $res = $dbw->newSelectQueryBuilder()
469 ->select( [ 'ls_value', 'ls_log_id' ] )
471 ->join( 'log_search', null, 'ls_log_id = log_id' )
473 'ls_field' => 'associated_rev_id',
474 $dbw->expr( 'log_type', '!=', 'create' ),
475 $dbw->expr( 'log_timestamp', '>', $dbw->timestamp( $this->cutoffFrom
) ),
476 $dbw->expr( 'log_timestamp', '<', $dbw->timestamp( $this->cutoffTo
) ),
478 ->caller( __METHOD__
)->fetchResultSet();
481 foreach ( $res as $row ) {
482 $rev_id = $row->ls_value
;
483 $log_id = $row->ls_log_id
;
485 // Mark the logging row as having an associated rev id
486 $dbw->newUpdateQueryBuilder()
487 ->update( 'recentchanges' )
488 ->set( [ 'rc_this_oldid' => $rev_id ] )
489 ->where( [ 'rc_logid' => $log_id ] )
490 ->caller( __METHOD__
)->execute();
492 // Delete the revision row
493 $dbw->newDeleteQueryBuilder()
494 ->deleteFrom( 'recentchanges' )
495 ->where( [ 'rc_this_oldid' => $rev_id, 'rc_logid' => 0 ] )
496 ->caller( __METHOD__
)->execute();
498 if ( ( ++
$updates %
$this->getBatchSize() ) == 0 ) {
499 $this->waitForReplication();
505 * Purge cached feeds in $wanCache
507 private function purgeFeeds() {
508 global $wgFeedClasses;
510 $this->output( "Deleting feed timestamps.\n" );
512 $wanCache = $this->getServiceContainer()->getMainWANObjectCache();
513 foreach ( $wgFeedClasses as $feed => $className ) {
514 $wanCache->delete( $wanCache->makeKey( 'rcfeed', $feed, 'timestamp' ) ); # Good enough for now.
519 // @codeCoverageIgnoreStart
520 $maintClass = RebuildRecentchanges
::class;
521 require_once RUN_MAINTENANCE_IF_MAIN
;
522 // @codeCoverageIgnoreEnd