MediaWiki master
rebuildrecentchanges.php
Go to the documentation of this file.
1<?php
26// @codeCoverageIgnoreStart
27require_once __DIR__ . '/Maintenance.php';
28// @codeCoverageIgnoreEnd
29
36
44 private $cutoffFrom;
46 private $cutoffTo;
47
48 public function __construct() {
49 parent::__construct();
50 $this->addDescription( 'Rebuild recent changes' );
51
52 $this->addOption(
53 'from',
54 "Only rebuild rows in requested time range (in YYYYMMDDHHMMSS format)",
55 false,
56 true
57 );
58 $this->addOption(
59 'to',
60 "Only rebuild rows in requested time range (in YYYYMMDDHHMMSS format)",
61 false,
62 true
63 );
64 $this->setBatchSize( 200 );
65 }
66
67 public function execute() {
68 if (
69 ( $this->hasOption( 'from' ) && !$this->hasOption( 'to' ) ) ||
70 ( !$this->hasOption( 'from' ) && $this->hasOption( 'to' ) )
71 ) {
72 $this->fatalError( "Both 'from' and 'to' must be given, or neither" );
73 }
74
75 $this->rebuildRecentChangesTablePass1();
76 $this->rebuildRecentChangesTablePass2();
77 $this->rebuildRecentChangesTablePass3();
78 $this->rebuildRecentChangesTablePass4();
79 $this->rebuildRecentChangesTablePass5();
80 if ( !( $this->hasOption( 'from' ) && $this->hasOption( 'to' ) ) ) {
81 $this->purgeFeeds();
82 }
83 $this->output( "Done.\n" );
84 }
85
89 private function rebuildRecentChangesTablePass1() {
90 $dbw = $this->getPrimaryDB();
91 $commentStore = $this->getServiceContainer()->getCommentStore();
92
93 if ( $this->hasOption( 'from' ) && $this->hasOption( 'to' ) ) {
94 $this->cutoffFrom = (int)wfTimestamp( TS_UNIX, $this->getOption( 'from' ) );
95 $this->cutoffTo = (int)wfTimestamp( TS_UNIX, $this->getOption( 'to' ) );
96
97 $sec = $this->cutoffTo - $this->cutoffFrom;
98 $days = $sec / 24 / 3600;
99 $this->output( "Rebuilding range of $sec seconds ($days days)\n" );
100 } else {
101 global $wgRCMaxAge;
102
103 $days = $wgRCMaxAge / 24 / 3600;
104 $this->output( "Rebuilding \$wgRCMaxAge=$wgRCMaxAge seconds ($days days)\n" );
105
106 $this->cutoffFrom = time() - $wgRCMaxAge;
107 $this->cutoffTo = time();
108 }
109
110 $this->output( "Clearing recentchanges table for time range...\n" );
111 $rcids = $dbw->newSelectQueryBuilder()
112 ->select( 'rc_id' )
113 ->from( 'recentchanges' )
114 ->where( $dbw->expr( 'rc_timestamp', '>', $dbw->timestamp( $this->cutoffFrom ) ) )
115 ->andWhere( $dbw->expr( 'rc_timestamp', '<', $dbw->timestamp( $this->cutoffTo ) ) )
116 ->caller( __METHOD__ )->fetchFieldValues();
117 foreach ( array_chunk( $rcids, $this->getBatchSize() ) as $rcidBatch ) {
118 $dbw->newDeleteQueryBuilder()
119 ->deleteFrom( 'recentchanges' )
120 ->where( [ 'rc_id' => $rcidBatch ] )
121 ->caller( __METHOD__ )->execute();
122 $this->waitForReplication();
123 }
124
125 $this->output( "Loading from page and revision tables...\n" );
126
127 $res = $dbw->newSelectQueryBuilder()
128 ->select(
129 [
130 'rev_timestamp',
131 'rev_minor_edit',
132 'rev_id',
133 'rev_deleted',
134 'page_namespace',
135 'page_title',
136 'page_is_new',
137 'page_id',
138 'rev_comment_text' => 'comment_rev_comment.comment_text',
139 'rev_comment_data' => 'comment_rev_comment.comment_data',
140 'rev_comment_cid' => 'comment_rev_comment.comment_id',
141 'rev_user' => 'actor_rev_user.actor_user',
142 'rev_user_text' => 'actor_rev_user.actor_name',
143 'rev_actor' => 'rev_actor',
144 ]
145 )
146 ->from( 'revision' )
147 ->join( 'page', null, 'rev_page=page_id' )
148 ->join( 'comment', 'comment_rev_comment', 'comment_rev_comment.comment_id = rev_comment_id' )
149 ->join( 'actor', 'actor_rev_user', 'actor_rev_user.actor_id = rev_actor' )
150 ->where(
151 [
152 $dbw->expr( 'rev_timestamp', '>', $dbw->timestamp( $this->cutoffFrom ) ),
153 $dbw->expr( 'rev_timestamp', '<', $dbw->timestamp( $this->cutoffTo ) )
154 ]
155 )
156 ->orderBy( 'rev_timestamp', SelectQueryBuilder::SORT_DESC )
157 ->caller( __METHOD__ )->fetchResultSet();
158
159 $this->output( "Inserting from page and revision tables...\n" );
160 $inserted = 0;
161 foreach ( $res as $row ) {
162 $comment = $commentStore->getComment( 'rev_comment', $row );
163 $dbw->newInsertQueryBuilder()
164 ->insertInto( 'recentchanges' )
165 ->row( [
166 'rc_timestamp' => $row->rev_timestamp,
167 'rc_actor' => $row->rev_actor,
168 'rc_namespace' => $row->page_namespace,
169 'rc_title' => $row->page_title,
170 'rc_minor' => $row->rev_minor_edit,
171 'rc_bot' => 0,
172 'rc_new' => $row->page_is_new,
173 'rc_cur_id' => $row->page_id,
174 'rc_this_oldid' => $row->rev_id,
175 'rc_last_oldid' => 0, // is this ok?
176 'rc_type' => $row->page_is_new ? RC_NEW : RC_EDIT,
177 'rc_source' => $row->page_is_new ? RecentChange::SRC_NEW : RecentChange::SRC_EDIT,
178 'rc_deleted' => $row->rev_deleted
179 ] + $commentStore->insert( $dbw, 'rc_comment', $comment ) )
180 ->caller( __METHOD__ )->execute();
181
182 $rcid = $dbw->insertId();
183 $dbw->newUpdateQueryBuilder()
184 ->update( 'change_tag' )
185 ->set( [ 'ct_rc_id' => $rcid ] )
186 ->where( [ 'ct_rev_id' => $row->rev_id ] )
187 ->caller( __METHOD__ )->execute();
188
189 if ( ( ++$inserted % $this->getBatchSize() ) == 0 ) {
190 $this->waitForReplication();
191 }
192 }
193 }
194
199 private function rebuildRecentChangesTablePass2() {
200 $dbw = $this->getPrimaryDB();
201
202 $this->output( "Updating links and size differences...\n" );
203
204 # Fill in the rc_last_oldid field, which points to the previous edit
205 $res = $dbw->newSelectQueryBuilder()
206 ->select( [ 'rc_cur_id', 'rc_this_oldid', 'rc_timestamp' ] )
207 ->from( 'recentchanges' )
208 ->where( $dbw->expr( 'rc_timestamp', '>', $dbw->timestamp( $this->cutoffFrom ) ) )
209 ->andWhere( $dbw->expr( 'rc_timestamp', '<', $dbw->timestamp( $this->cutoffTo ) ) )
210 ->orderBy( [ 'rc_cur_id', 'rc_timestamp' ] )
211 ->caller( __METHOD__ )->fetchResultSet();
212
213 $lastCurId = 0;
214 $lastOldId = 0;
215 $lastSize = null;
216 $updated = 0;
217 foreach ( $res as $row ) {
218 $new = 0;
219
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;
224
225 $revRow = $dbw->newSelectQueryBuilder()
226 ->select( [ 'rev_id', 'rev_len' ] )
227 ->from( 'revision' )
228 ->where( [ 'rev_page' => $lastCurId, $dbw->expr( 'rev_timestamp', '<', $emit ) ] )
229 ->orderBy( 'rev_timestamp DESC' )
230 ->caller( __METHOD__ )->fetchRow();
231 if ( $revRow ) {
232 $lastOldId = intval( $revRow->rev_id );
233 # Grab the last text size if available
234 $lastSize = $revRow->rev_len !== null ? intval( $revRow->rev_len ) : null;
235 } else {
236 # No previous edit
237 $lastOldId = 0;
238 $lastSize = 0;
239 $new = 1; // probably true
240 }
241 }
242
243 if ( $lastCurId == 0 ) {
244 $this->output( "Uhhh, something wrong? No curid\n" );
245 } else {
246 # Grab the entry's text size
247 $size = (int)$dbw->newSelectQueryBuilder()
248 ->select( 'rev_len' )
249 ->from( 'revision' )
250 ->where( [ 'rev_id' => $row->rc_this_oldid ] )
251 ->caller( __METHOD__ )->fetchField();
252
253 $dbw->newUpdateQueryBuilder()
254 ->update( 'recentchanges' )
255 ->set( [
256 'rc_last_oldid' => $lastOldId,
257 'rc_new' => $new,
258 'rc_type' => $new ? RC_NEW : RC_EDIT,
259 'rc_source' => $new === 1 ? RecentChange::SRC_NEW : RecentChange::SRC_EDIT,
260 'rc_old_len' => $lastSize,
261 'rc_new_len' => $size,
262 ] )
263 ->where( [
264 'rc_cur_id' => $lastCurId,
265 'rc_this_oldid' => $row->rc_this_oldid,
266 // index usage
267 'rc_timestamp' => $row->rc_timestamp,
268 ] )
269 ->caller( __METHOD__ )->execute();
270
271 $lastOldId = intval( $row->rc_this_oldid );
272 $lastSize = $size;
273
274 if ( ( ++$updated % $this->getBatchSize() ) == 0 ) {
275 $this->waitForReplication();
276 }
277 }
278 }
279 }
280
284 private function rebuildRecentChangesTablePass3() {
286
287 $dbw = $this->getDB( DB_PRIMARY );
288 $commentStore = $this->getServiceContainer()->getCommentStore();
289 $nonRCLogs = array_merge(
290 array_keys( $wgLogRestrictions ),
291 array_keys( $wgFilterLogTypes ),
292 [ 'create' ]
293 );
294
295 $this->output( "Loading from user and logging tables...\n" );
296
297 $res = $dbw->newSelectQueryBuilder()
298 ->select(
299 [
300 'log_timestamp',
301 'log_actor',
302 'log_namespace',
303 'log_title',
304 'log_page',
305 'log_type',
306 'log_action',
307 'log_id',
308 'log_params',
309 'log_deleted',
310 'log_comment_text' => 'comment_log_comment.comment_text',
311 'log_comment_data' => 'comment_log_comment.comment_data',
312 'log_comment_cid' => 'comment_log_comment.comment_id',
313 ]
314 )
315 ->from( 'logging' )
316 ->join( 'comment', 'comment_log_comment', 'comment_log_comment.comment_id = log_comment_id' )
317 ->where(
318 [
319 $dbw->expr( 'log_timestamp', '>', $dbw->timestamp( $this->cutoffFrom ) ),
320 $dbw->expr( 'log_timestamp', '<', $dbw->timestamp( $this->cutoffTo ) ),
321 // Some logs don't go in RC since they are private, or are included in the filterable log types.
322 'log_type' => array_diff( LogPage::validTypes(), $nonRCLogs ),
323 ]
324 )
325 ->orderBy( [ 'log_timestamp DESC', 'log_id DESC' ] )
326 ->caller( __METHOD__ )->fetchResultSet();
327
328 $field = $dbw->fieldInfo( 'recentchanges', 'rc_cur_id' );
329
330 $inserted = 0;
331 foreach ( $res as $row ) {
332 $comment = $commentStore->getComment( 'log_comment', $row );
333 $dbw->newInsertQueryBuilder()
334 ->insertInto( 'recentchanges' )
335 ->row( [
336 'rc_timestamp' => $row->log_timestamp,
337 'rc_actor' => $row->log_actor,
338 'rc_namespace' => $row->log_namespace,
339 'rc_title' => $row->log_title,
340 'rc_minor' => 0,
341 'rc_bot' => 0,
342 'rc_patrolled' => $row->log_type == 'upload' ? 0 : 2,
343 'rc_new' => 0,
344 'rc_this_oldid' => 0,
345 'rc_last_oldid' => 0,
346 'rc_type' => RC_LOG,
347 'rc_source' => RecentChange::SRC_LOG,
348 'rc_cur_id' => $field->isNullable()
349 ? $row->log_page
350 : (int)$row->log_page, // NULL => 0,
351 'rc_log_type' => $row->log_type,
352 'rc_log_action' => $row->log_action,
353 'rc_logid' => $row->log_id,
354 'rc_params' => $row->log_params,
355 'rc_deleted' => $row->log_deleted
356 ] + $commentStore->insert( $dbw, 'rc_comment', $comment ) )
357 ->caller( __METHOD__ )->execute();
358
359 $rcid = $dbw->insertId();
360 $dbw->newUpdateQueryBuilder()
361 ->update( 'change_tag' )
362 ->set( [ 'ct_rc_id' => $rcid ] )
363 ->where( [ 'ct_log_id' => $row->log_id ] )
364 ->caller( __METHOD__ )->execute();
365
366 if ( ( ++$inserted % $this->getBatchSize() ) == 0 ) {
367 $this->waitForReplication();
368 }
369 }
370 }
371
380 private function findRcIdsWithGroups( $db, $groups, $conds = [] ) {
381 if ( !count( $groups ) ) {
382 return [];
383 }
384 return $db->newSelectQueryBuilder()
385 ->select( 'rc_id' )
386 ->distinct()
387 ->from( 'recentchanges' )
388 ->join( 'actor', null, 'actor_id=rc_actor' )
389 ->join( 'user_groups', null, 'ug_user=actor_user' )
390 ->where( $conds )
391 ->andWhere( [
392 $db->expr( 'rc_timestamp', '>', $db->timestamp( $this->cutoffFrom ) ),
393 $db->expr( 'rc_timestamp', '<', $db->timestamp( $this->cutoffTo ) ),
394 'ug_group' => $groups
395 ] )
396 ->caller( __METHOD__ )->fetchFieldValues();
397 }
398
402 private function rebuildRecentChangesTablePass4() {
404
405 $dbw = $this->getPrimaryDB();
406
407 # @FIXME: recognize other bot account groups (not the same as users with 'bot' rights)
408 # @NOTE: users with 'bot' rights choose when edits are bot edits or not. That information
409 # may be lost at this point (aside from joining on the patrol log table entries).
410 $botgroups = [ 'bot' ];
411 $autopatrolgroups = ( $wgUseRCPatrol || $wgUseNPPatrol || $wgUseFilePatrol ) ?
412 $this->getServiceContainer()->getGroupPermissionsLookup()
413 ->getGroupsWithPermission( 'autopatrol' ) : [];
414
415 # Flag our recent bot edits
416 // @phan-suppress-next-line PhanRedundantCondition
417 if ( $botgroups ) {
418 $this->output( "Flagging bot account edits...\n" );
419
420 # Fill in the rc_bot field
421 $rcids = $this->findRcIdsWithGroups( $dbw, $botgroups );
422
423 foreach ( array_chunk( $rcids, $this->getBatchSize() ) as $rcidBatch ) {
424 $dbw->newUpdateQueryBuilder()
425 ->update( 'recentchanges' )
426 ->set( [ 'rc_bot' => 1 ] )
427 ->where( [ 'rc_id' => $rcidBatch ] )
428 ->caller( __METHOD__ )->execute();
429 $this->waitForReplication();
430 }
431 }
432
433 # Flag our recent autopatrolled edits
434 if ( !$wgMiserMode && $autopatrolgroups ) {
435 $this->output( "Flagging auto-patrolled edits...\n" );
436
437 $conds = [ 'rc_patrolled' => 0 ];
438 if ( !$wgUseRCPatrol ) {
439 $subConds = [];
440 if ( $wgUseNPPatrol ) {
441 $subConds[] = $dbw->expr( 'rc_source', '=', RecentChange::SRC_NEW );
442 }
443 if ( $wgUseFilePatrol ) {
444 $subConds[] = $dbw->expr( 'rc_log_type', '=', 'upload' );
445 }
446 $conds[] = $dbw->makeList( $subConds, IDatabase::LIST_OR );
447 }
448
449 $rcids = $this->findRcIdsWithGroups( $dbw, $autopatrolgroups, $conds );
450 foreach ( array_chunk( $rcids, $this->getBatchSize() ) as $rcidBatch ) {
451 $dbw->newUpdateQueryBuilder()
452 ->update( 'recentchanges' )
453 ->set( [ 'rc_patrolled' => 2 ] )
454 ->where( [ 'rc_id' => $rcidBatch ] )
455 ->caller( __METHOD__ )->execute();
456 $this->waitForReplication();
457 }
458 }
459 }
460
465 private function rebuildRecentChangesTablePass5() {
466 $dbw = $this->getPrimaryDB();
467
468 $this->output( "Removing duplicate revision and logging entries...\n" );
469
470 $res = $dbw->newSelectQueryBuilder()
471 ->select( [ 'ls_value', 'ls_log_id' ] )
472 ->from( 'logging' )
473 ->join( 'log_search', null, 'ls_log_id = log_id' )
474 ->where( [
475 'ls_field' => 'associated_rev_id',
476 $dbw->expr( 'log_type', '!=', 'create' ),
477 $dbw->expr( 'log_timestamp', '>', $dbw->timestamp( $this->cutoffFrom ) ),
478 $dbw->expr( 'log_timestamp', '<', $dbw->timestamp( $this->cutoffTo ) ),
479 ] )
480 ->caller( __METHOD__ )->fetchResultSet();
481
482 $updates = 0;
483 foreach ( $res as $row ) {
484 $rev_id = $row->ls_value;
485 $log_id = $row->ls_log_id;
486
487 // Mark the logging row as having an associated rev id
488 $dbw->newUpdateQueryBuilder()
489 ->update( 'recentchanges' )
490 ->set( [ 'rc_this_oldid' => $rev_id ] )
491 ->where( [ 'rc_logid' => $log_id ] )
492 ->caller( __METHOD__ )->execute();
493
494 // Delete the revision row
495 $dbw->newDeleteQueryBuilder()
496 ->deleteFrom( 'recentchanges' )
497 ->where( [ 'rc_this_oldid' => $rev_id, 'rc_logid' => 0 ] )
498 ->caller( __METHOD__ )->execute();
499
500 if ( ( ++$updates % $this->getBatchSize() ) == 0 ) {
501 $this->waitForReplication();
502 }
503 }
504 }
505
509 private function purgeFeeds() {
510 global $wgFeedClasses;
511
512 $this->output( "Deleting feed timestamps.\n" );
513
514 $wanCache = $this->getServiceContainer()->getMainWANObjectCache();
515 foreach ( $wgFeedClasses as $feed => $className ) {
516 $wanCache->delete( $wanCache->makeKey( 'rcfeed', $feed, 'timestamp' ) ); # Good enough for now.
517 }
518 }
519}
520
521// @codeCoverageIgnoreStart
522$maintClass = RebuildRecentchanges::class;
523require_once RUN_MAINTENANCE_IF_MAIN;
524// @codeCoverageIgnoreEnd
const RC_NEW
Definition Defines.php:118
const RC_LOG
Definition Defines.php:119
const RC_EDIT
Definition Defines.php:117
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Class to simplify the use of log pages.
Definition LogPage.php:50
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
getBatchSize()
Returns batch size.
output( $out, $channel=null)
Throw some output to the user.
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
getDB( $db, $groups=[], $dbDomain=false)
Returns a database to be used by current maintenance script.
waitForReplication()
Wait for replica DB servers to catch up.
hasOption( $name)
Checks to see if a particular option was set.
getOption( $name, $default=null)
Get an option, or return the default.
getServiceContainer()
Returns the main service container.
addDescription( $text)
Set the description text.
Utility class for creating and reading rows in the recentchanges table.
Maintenance script that rebuilds recent changes from scratch.
execute()
Do the actual work.
__construct()
Default constructor.
Build SELECT queries with a fluent interface.
$wgUseFilePatrol
Config variable stub for the UseFilePatrol setting, for use by phpdoc and IDEs.
$wgLogRestrictions
Config variable stub for the LogRestrictions setting, for use by phpdoc and IDEs.
$wgUseRCPatrol
Config variable stub for the UseRCPatrol setting, for use by phpdoc and IDEs.
$wgUseNPPatrol
Config variable stub for the UseNPPatrol setting, for use by phpdoc and IDEs.
$wgRCMaxAge
Config variable stub for the RCMaxAge setting, for use by phpdoc and IDEs.
$wgFeedClasses
Config variable stub for the FeedClasses setting, for use by phpdoc and IDEs.
$wgFilterLogTypes
Config variable stub for the FilterLogTypes setting, for use by phpdoc and IDEs.
$wgMiserMode
Config variable stub for the MiserMode setting, for use by phpdoc and IDEs.
Interface to a relational database.
Definition IDatabase.php:45
A database connection without write operations.
const DB_PRIMARY
Definition defines.php:28