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