MediaWiki  master
rebuildrecentchanges.php
Go to the documentation of this file.
1 <?php
26 require_once __DIR__ . '/Maintenance.php';
27 
31 
39  private $cutoffFrom;
41  private $cutoffTo;
42 
43  public function __construct() {
44  parent::__construct();
45  $this->addDescription( 'Rebuild recent changes' );
46 
47  $this->addOption(
48  'from',
49  "Only rebuild rows in requested time range (in YYYYMMDDHHMMSS format)",
50  false,
51  true
52  );
53  $this->addOption(
54  'to',
55  "Only rebuild rows in requested time range (in YYYYMMDDHHMMSS format)",
56  false,
57  true
58  );
59  $this->setBatchSize( 200 );
60  }
61 
62  public function execute() {
63  if (
64  ( $this->hasOption( 'from' ) && !$this->hasOption( 'to' ) ) ||
65  ( !$this->hasOption( 'from' ) && $this->hasOption( 'to' ) )
66  ) {
67  $this->fatalError( "Both 'from' and 'to' must be given, or neither" );
68  }
69 
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' ) ) ) {
77  $this->purgeFeeds();
78  }
79  $this->output( "Done.\n" );
80  }
81 
87  private function rebuildRecentChangesTablePass1( ILBFactory $lbFactory ) {
88  $dbw = $this->getDB( DB_PRIMARY );
89  $commentStore = CommentStore::getStore();
90 
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' ) );
94 
95  $sec = $this->cutoffTo - $this->cutoffFrom;
96  $days = $sec / 24 / 3600;
97  $this->output( "Rebuilding range of $sec seconds ($days days)\n" );
98  } else {
99  global $wgRCMaxAge;
100 
101  $days = $wgRCMaxAge / 24 / 3600;
102  $this->output( "Rebuilding \$wgRCMaxAge=$wgRCMaxAge seconds ($days days)\n" );
103 
104  $this->cutoffFrom = time() - $wgRCMaxAge;
105  $this->cutoffTo = time();
106  }
107 
108  $this->output( "Clearing recentchanges table for time range...\n" );
109  $rcids = $dbw->selectFieldValues(
110  'recentchanges',
111  'rc_id',
112  [
113  'rc_timestamp > ' . $dbw->addQuotes( $dbw->timestamp( $this->cutoffFrom ) ),
114  'rc_timestamp < ' . $dbw->addQuotes( $dbw->timestamp( $this->cutoffTo ) )
115  ],
116  __METHOD__
117  );
118  foreach ( array_chunk( $rcids, $this->getBatchSize() ) as $rcidBatch ) {
119  $dbw->delete( 'recentchanges', [ 'rc_id' => $rcidBatch ], __METHOD__ );
120  $lbFactory->waitForReplication();
121  }
122 
123  $this->output( "Loading from page and revision tables...\n" );
124 
125  $commentQuery = $commentStore->getJoin( 'rev_comment' );
126  $actorQuery = ActorMigration::newMigration()->getJoin( 'rev_user' );
127  $res = $dbw->select(
128  [ 'revision', 'page' ] + $commentQuery['tables'] + $actorQuery['tables'],
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  ] + $commentQuery['fields'] + $actorQuery['fields'],
139  [
140  'rev_timestamp > ' . $dbw->addQuotes( $dbw->timestamp( $this->cutoffFrom ) ),
141  'rev_timestamp < ' . $dbw->addQuotes( $dbw->timestamp( $this->cutoffTo ) )
142  ],
143  __METHOD__,
144  [ 'ORDER BY' => 'rev_timestamp DESC' ],
145  [
146  'page' => [ 'JOIN', 'rev_page=page_id' ],
147  ] + $commentQuery['joins'] + $actorQuery['joins']
148  );
149 
150  $this->output( "Inserting from page and revision tables...\n" );
151  $inserted = 0;
152  foreach ( $res as $row ) {
153  $comment = $commentStore->getComment( 'rev_comment', $row );
154  $dbw->insert(
155  'recentchanges',
156  [
157  'rc_timestamp' => $row->rev_timestamp,
158  'rc_actor' => $row->rev_actor,
159  'rc_namespace' => $row->page_namespace,
160  'rc_title' => $row->page_title,
161  'rc_minor' => $row->rev_minor_edit,
162  'rc_bot' => 0,
163  'rc_new' => $row->page_is_new,
164  'rc_cur_id' => $row->page_id,
165  'rc_this_oldid' => $row->rev_id,
166  'rc_last_oldid' => 0, // is this ok?
167  'rc_type' => $row->page_is_new ? RC_NEW : RC_EDIT,
168  'rc_source' => $row->page_is_new ? RecentChange::SRC_NEW : RecentChange::SRC_EDIT,
169  'rc_deleted' => $row->rev_deleted
170  ] + $commentStore->insert( $dbw, 'rc_comment', $comment ),
171  __METHOD__
172  );
173 
174  $rcid = $dbw->insertId();
175  $dbw->update(
176  'change_tag',
177  [ 'ct_rc_id' => $rcid ],
178  [ 'ct_rev_id' => $row->rev_id ],
179  __METHOD__
180  );
181 
182  if ( ( ++$inserted % $this->getBatchSize() ) == 0 ) {
183  $lbFactory->waitForReplication();
184  }
185  }
186  }
187 
194  private function rebuildRecentChangesTablePass2( ILBFactory $lbFactory ) {
195  $dbw = $this->getDB( DB_PRIMARY );
196 
197  $this->output( "Updating links and size differences...\n" );
198 
199  # Fill in the rc_last_oldid field, which points to the previous edit
200  $res = $dbw->select(
201  'recentchanges',
202  [ 'rc_cur_id', 'rc_this_oldid', 'rc_timestamp' ],
203  [
204  "rc_timestamp > " . $dbw->addQuotes( $dbw->timestamp( $this->cutoffFrom ) ),
205  "rc_timestamp < " . $dbw->addQuotes( $dbw->timestamp( $this->cutoffTo ) )
206  ],
207  __METHOD__,
208  [ 'ORDER BY' => [ 'rc_cur_id', 'rc_timestamp' ] ]
209  );
210 
211  $lastCurId = 0;
212  $lastOldId = 0;
213  $lastSize = null;
214  $updated = 0;
215  foreach ( $res as $row ) {
216  $new = 0;
217 
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;
222 
223  $revRow = $dbw->selectRow(
224  'revision',
225  [ 'rev_id', 'rev_len' ],
226  [ 'rev_page' => $lastCurId, "rev_timestamp < " . $dbw->addQuotes( $emit ) ],
227  __METHOD__,
228  [ 'ORDER BY' => 'rev_timestamp DESC' ]
229  );
230  if ( $revRow ) {
231  $lastOldId = intval( $revRow->rev_id );
232  # Grab the last text size if available
233  $lastSize = $revRow->rev_len !== null ? intval( $revRow->rev_len ) : null;
234  } else {
235  # No previous edit
236  $lastOldId = 0;
237  $lastSize = 0;
238  $new = 1; // probably true
239  }
240  }
241 
242  if ( $lastCurId == 0 ) {
243  $this->output( "Uhhh, something wrong? No curid\n" );
244  } else {
245  # Grab the entry's text size
246  $size = (int)$dbw->selectField(
247  'revision',
248  'rev_len',
249  [ 'rev_id' => $row->rc_this_oldid ],
250  __METHOD__
251  );
252 
253  $dbw->update(
254  'recentchanges',
255  [
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  [
264  'rc_cur_id' => $lastCurId,
265  'rc_this_oldid' => $row->rc_this_oldid,
266  'rc_timestamp' => $row->rc_timestamp // index usage
267  ],
268  __METHOD__
269  );
270 
271  $lastOldId = intval( $row->rc_this_oldid );
272  $lastSize = $size;
273 
274  if ( ( ++$updated % $this->getBatchSize() ) == 0 ) {
275  $lbFactory->waitForReplication();
276  }
277  }
278  }
279  }
280 
286  private function rebuildRecentChangesTablePass3( ILBFactory $lbFactory ) {
288 
289  $dbw = $this->getDB( DB_PRIMARY );
290  $commentStore = CommentStore::getStore();
291  $nonRCLogs = array_merge( array_keys( $wgLogRestrictions ),
292  array_keys( $wgFilterLogTypes ),
293  [ 'create' ] );
294 
295  $this->output( "Loading from user and logging tables...\n" );
296 
297  $commentQuery = $commentStore->getJoin( 'log_comment' );
298  $res = $dbw->select(
299  [ 'logging' ] + $commentQuery['tables'],
300  [
301  'log_timestamp',
302  'log_actor',
303  'log_namespace',
304  'log_title',
305  'log_page',
306  'log_type',
307  'log_action',
308  'log_id',
309  'log_params',
310  'log_deleted'
311  ] + $commentQuery['fields'],
312  [
313  'log_timestamp > ' . $dbw->addQuotes( $dbw->timestamp( $this->cutoffFrom ) ),
314  'log_timestamp < ' . $dbw->addQuotes( $dbw->timestamp( $this->cutoffTo ) ),
315  // Some logs don't go in RC since they are private, or are included in the filterable log types.
316  'log_type' => array_diff( LogPage::validTypes(), $nonRCLogs ),
317  ],
318  __METHOD__,
319  [ 'ORDER BY' => 'log_timestamp DESC' ],
320  $commentQuery['joins']
321  );
322 
323  $field = $dbw->fieldInfo( 'recentchanges', 'rc_cur_id' );
324 
325  $inserted = 0;
326  foreach ( $res as $row ) {
327  $comment = $commentStore->getComment( 'log_comment', $row );
328  $dbw->insert(
329  'recentchanges',
330  [
331  'rc_timestamp' => $row->log_timestamp,
332  'rc_actor' => $row->log_actor,
333  'rc_namespace' => $row->log_namespace,
334  'rc_title' => $row->log_title,
335  'rc_minor' => 0,
336  'rc_bot' => 0,
337  'rc_patrolled' => $row->log_type == 'upload' ? 0 : 2,
338  'rc_new' => 0,
339  'rc_this_oldid' => 0,
340  'rc_last_oldid' => 0,
341  'rc_type' => RC_LOG,
342  'rc_source' => RecentChange::SRC_LOG,
343  'rc_cur_id' => $field->isNullable()
344  ? $row->log_page
345  : (int)$row->log_page, // NULL => 0,
346  'rc_log_type' => $row->log_type,
347  'rc_log_action' => $row->log_action,
348  'rc_logid' => $row->log_id,
349  'rc_params' => $row->log_params,
350  'rc_deleted' => $row->log_deleted
351  ] + $commentStore->insert( $dbw, 'rc_comment', $comment ),
352  __METHOD__
353  );
354 
355  $rcid = $dbw->insertId();
356  $dbw->update(
357  'change_tag',
358  [ 'ct_rc_id' => $rcid ],
359  [ 'ct_log_id' => $row->log_id ],
360  __METHOD__
361  );
362 
363  if ( ( ++$inserted % $this->getBatchSize() ) == 0 ) {
364  $lbFactory->waitForReplication();
365  }
366  }
367  }
368 
377  private function findRcIdsWithGroups( $db, $groups, $conds = [] ) {
378  if ( !count( $groups ) ) {
379  return [];
380  }
381  return $db->selectFieldValues(
382  [ 'recentchanges', 'actor', 'user_groups' ],
383  'rc_id',
384  $conds + [
385  "rc_timestamp > " . $db->addQuotes( $db->timestamp( $this->cutoffFrom ) ),
386  "rc_timestamp < " . $db->addQuotes( $db->timestamp( $this->cutoffTo ) ),
387  'ug_group' => $groups
388  ],
389  __METHOD__,
390  [ 'DISTINCT' ],
391  [
392  'actor' => [ 'JOIN', 'actor_id=rc_actor' ],
393  'user_groups' => [ 'JOIN', 'ug_user=actor_user' ]
394  ]
395  );
396  }
397 
403  private function rebuildRecentChangesTablePass4( ILBFactory $lbFactory ) {
405 
406  $dbw = $this->getDB( DB_PRIMARY );
407 
408  # @FIXME: recognize other bot account groups (not the same as users with 'bot' rights)
409  # @NOTE: users with 'bot' rights choose when edits are bot edits or not. That information
410  # may be lost at this point (aside from joining on the patrol log table entries).
411  $botgroups = [ 'bot' ];
412  $autopatrolgroups = ( $wgUseRCPatrol || $wgUseNPPatrol || $wgUseFilePatrol ) ?
413  MediaWikiServices::getInstance()->getGroupPermissionsLookup()
414  ->getGroupsWithPermission( 'autopatrol' ) : [];
415 
416  # Flag our recent bot edits
417  // @phan-suppress-next-line PhanRedundantCondition
418  if ( $botgroups ) {
419  $this->output( "Flagging bot account edits...\n" );
420 
421  # Fill in the rc_bot field
422  $rcids = $this->findRcIdsWithGroups( $dbw, $botgroups );
423 
424  foreach ( array_chunk( $rcids, $this->getBatchSize() ) as $rcidBatch ) {
425  $dbw->update(
426  'recentchanges',
427  [ 'rc_bot' => 1 ],
428  [ 'rc_id' => $rcidBatch ],
429  __METHOD__
430  );
431  $lbFactory->waitForReplication();
432  }
433  }
434 
435  # Flag our recent autopatrolled edits
436  if ( !$wgMiserMode && $autopatrolgroups ) {
437  $this->output( "Flagging auto-patrolled edits...\n" );
438 
439  $conds = [ 'rc_patrolled' => 0 ];
440  if ( !$wgUseRCPatrol ) {
441  $subConds = [];
442  if ( $wgUseNPPatrol ) {
443  $subConds[] = 'rc_source = ' . $dbw->addQuotes( RecentChange::SRC_NEW );
444  }
445  if ( $wgUseFilePatrol ) {
446  $subConds[] = 'rc_log_type = ' . $dbw->addQuotes( 'upload' );
447  }
448  $conds[] = $dbw->makeList( $subConds, IDatabase::LIST_OR );
449  }
450 
451  $rcids = $this->findRcIdsWithGroups( $dbw, $autopatrolgroups, $conds );
452  foreach ( array_chunk( $rcids, $this->getBatchSize() ) as $rcidBatch ) {
453  $dbw->update(
454  'recentchanges',
455  [ 'rc_patrolled' => 2 ],
456  [ 'rc_id' => $rcidBatch ],
457  __METHOD__
458  );
459  $lbFactory->waitForReplication();
460  }
461  }
462  }
463 
470  private function rebuildRecentChangesTablePass5( ILBFactory $lbFactory ) {
471  $dbw = $this->getDB( DB_PRIMARY );
472 
473  $this->output( "Removing duplicate revision and logging entries...\n" );
474 
475  $res = $dbw->select(
476  [ 'logging', 'log_search' ],
477  [ 'ls_value', 'ls_log_id' ],
478  [
479  'ls_log_id = log_id',
480  'ls_field' => 'associated_rev_id',
481  'log_type != ' . $dbw->addQuotes( 'create' ),
482  'log_timestamp > ' . $dbw->addQuotes( $dbw->timestamp( $this->cutoffFrom ) ),
483  'log_timestamp < ' . $dbw->addQuotes( $dbw->timestamp( $this->cutoffTo ) ),
484  ],
485  __METHOD__
486  );
487 
488  $updates = 0;
489  foreach ( $res as $row ) {
490  $rev_id = $row->ls_value;
491  $log_id = $row->ls_log_id;
492 
493  // Mark the logging row as having an associated rev id
494  $dbw->update(
495  'recentchanges',
496  /*SET*/ [ 'rc_this_oldid' => $rev_id ],
497  /*WHERE*/ [ 'rc_logid' => $log_id ],
498  __METHOD__
499  );
500 
501  // Delete the revision row
502  $dbw->delete(
503  'recentchanges',
504  /*WHERE*/ [ 'rc_this_oldid' => $rev_id, 'rc_logid' => 0 ],
505  __METHOD__
506  );
507 
508  if ( ( ++$updates % $this->getBatchSize() ) == 0 ) {
509  $lbFactory->waitForReplication();
510  }
511  }
512  }
513 
517  private function purgeFeeds() {
518  global $wgFeedClasses;
519 
520  $this->output( "Deleting feed timestamps.\n" );
521 
522  $wanCache = MediaWikiServices::getInstance()->getMainWANObjectCache();
523  foreach ( $wgFeedClasses as $feed => $className ) {
524  $wanCache->delete( $wanCache->makeKey( 'rcfeed', $feed, 'timestamp' ) ); # Good enough for now.
525  }
526  }
527 }
528 
529 $maintClass = RebuildRecentchanges::class;
530 require_once RUN_MAINTENANCE_IF_MAIN;
RebuildRecentchanges\$cutoffTo
int $cutoffTo
UNIX timestamp.
Definition: rebuildrecentchanges.php:41
LIST_OR
const LIST_OR
Definition: Defines.php:46
LogPage\validTypes
static validTypes()
Get the list of valid log types.
Definition: LogPage.php:206
RC_EDIT
const RC_EDIT
Definition: Defines.php:115
RebuildRecentchanges\rebuildRecentChangesTablePass3
rebuildRecentChangesTablePass3(ILBFactory $lbFactory)
Rebuild pass 3: Insert recentchanges entries for action logs.
Definition: rebuildrecentchanges.php:286
Wikimedia\Rdbms\ILBFactory\waitForReplication
waitForReplication(array $opts=[])
Waits for the replica DBs to catch up to the current primary position.
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:193
Maintenance\fatalError
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
Definition: Maintenance.php:489
Maintenance\addDescription
addDescription( $text)
Set the description text.
Definition: Maintenance.php:329
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1668
RebuildRecentchanges\execute
execute()
Do the actual work.
Definition: rebuildrecentchanges.php:62
Maintenance
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: Maintenance.php:59
RC_NEW
const RC_NEW
Definition: Defines.php:116
$res
$res
Definition: testCompression.php:57
$wgUseRCPatrol
$wgUseRCPatrol
Use RC Patrolling to check for vandalism (from recent changes and watchlists) New pages and new files...
Definition: DefaultSettings.php:8034
$wgUseNPPatrol
$wgUseNPPatrol
Use new page patrolling to check new pages on Special:Newpages.
Definition: DefaultSettings.php:8050
RecentChange\SRC_LOG
const SRC_LOG
Definition: RecentChange.php:87
ActorMigration\newMigration
static newMigration()
Static constructor.
Definition: ActorMigration.php:76
Wikimedia\Rdbms\IDatabase
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:38
RC_LOG
const RC_LOG
Definition: Defines.php:117
RebuildRecentchanges\rebuildRecentChangesTablePass4
rebuildRecentChangesTablePass4(ILBFactory $lbFactory)
Rebuild pass 4: Mark bot and autopatrolled entries.
Definition: rebuildrecentchanges.php:403
RebuildRecentchanges\findRcIdsWithGroups
findRcIdsWithGroups( $db, $groups, $conds=[])
Find rc_id values that have a user with one of the specified groups.
Definition: rebuildrecentchanges.php:377
$wgFilterLogTypes
$wgFilterLogTypes
Show/hide links on Special:Log will be shown for these log types.
Definition: DefaultSettings.php:8938
$maintClass
$maintClass
Definition: rebuildrecentchanges.php:529
Maintenance\addOption
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
Definition: Maintenance.php:249
RecentChange\SRC_EDIT
const SRC_EDIT
Definition: RecentChange.php:85
RecentChange\SRC_NEW
const SRC_NEW
Definition: RecentChange.php:86
$wgFeedClasses
$wgFeedClasses
Available feeds objects.
Definition: DefaultSettings.php:8109
$wgUseFilePatrol
$wgUseFilePatrol
Use file patrolling to check new files on Special:Newfiles.
Definition: DefaultSettings.php:8061
RebuildRecentchanges
Maintenance script that rebuilds recent changes from scratch.
Definition: rebuildrecentchanges.php:37
RebuildRecentchanges\rebuildRecentChangesTablePass2
rebuildRecentChangesTablePass2(ILBFactory $lbFactory)
Rebuild pass 2: Enhance entries for page revisions with references to the previous revision (rc_last_...
Definition: rebuildrecentchanges.php:194
$wgLogRestrictions
$wgLogRestrictions
This restricts log access to those who have a certain right Users without this will not see it in the...
Definition: DefaultSettings.php:8915
DB_PRIMARY
const DB_PRIMARY
Definition: defines.php:27
$wgRCMaxAge
$wgRCMaxAge
Recentchanges items are periodically purged; entries older than this many seconds will go.
Definition: DefaultSettings.php:7901
Maintenance\getDB
getDB( $db, $groups=[], $dbDomain=false)
Returns a database to be used by current maintenance script.
Definition: Maintenance.php:1362
$wgMiserMode
$wgMiserMode
Disable database-intensive features.
Definition: DefaultSettings.php:2618
Maintenance\getOption
getOption( $name, $default=null)
Get an option, or return the default.
Definition: Maintenance.php:286
RebuildRecentchanges\$cutoffFrom
int $cutoffFrom
UNIX timestamp.
Definition: rebuildrecentchanges.php:39
Maintenance\getBatchSize
getBatchSize()
Returns batch size.
Definition: Maintenance.php:368
RebuildRecentchanges\rebuildRecentChangesTablePass5
rebuildRecentChangesTablePass5(ILBFactory $lbFactory)
Rebuild pass 5: Delete duplicate entries where we generate both a page revision and a log entry for a...
Definition: rebuildrecentchanges.php:470
Maintenance\output
output( $out, $channel=null)
Throw some output to the user.
Definition: Maintenance.php:435
Maintenance\hasOption
hasOption( $name)
Checks to see if a particular option was set.
Definition: Maintenance.php:271
CommentStore\getStore
static getStore()
Definition: CommentStore.php:120
RebuildRecentchanges\__construct
__construct()
Default constructor.
Definition: rebuildrecentchanges.php:43
RebuildRecentchanges\purgeFeeds
purgeFeeds()
Purge cached feeds in $wanCache.
Definition: rebuildrecentchanges.php:517
Maintenance\setBatchSize
setBatchSize( $s=0)
Definition: Maintenance.php:375
Wikimedia\Rdbms\ILBFactory
An interface for generating database load balancers.
Definition: ILBFactory.php:33
RebuildRecentchanges\rebuildRecentChangesTablePass1
rebuildRecentChangesTablePass1(ILBFactory $lbFactory)
Rebuild pass 1: Insert recentchanges entries for page revisions.
Definition: rebuildrecentchanges.php:87