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