MediaWiki REL1_33
rebuildrecentchanges.php
Go to the documentation of this file.
1<?php
26require_once __DIR__ . '/Maintenance.php';
27
30
38 private $cutoffFrom;
40 private $cutoffTo;
41
42 public function __construct() {
43 parent::__construct();
44 $this->addDescription( 'Rebuild recent changes' );
45
46 $this->addOption(
47 'from',
48 "Only rebuild rows in requested time range (in YYYYMMDDHHMMSS format)",
49 false,
50 true
51 );
52 $this->addOption(
53 'to',
54 "Only rebuild rows in requested time range (in YYYYMMDDHHMMSS format)",
55 false,
56 true
57 );
58 $this->setBatchSize( 200 );
59 }
60
61 public function execute() {
62 if (
63 ( $this->hasOption( 'from' ) && !$this->hasOption( 'to' ) ) ||
64 ( !$this->hasOption( 'from' ) && $this->hasOption( 'to' ) )
65 ) {
66 $this->fatalError( "Both 'from' and 'to' must be given, or neither" );
67 }
68
69 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
70 $this->rebuildRecentChangesTablePass1( $lbFactory );
71 $this->rebuildRecentChangesTablePass2( $lbFactory );
72 $this->rebuildRecentChangesTablePass3( $lbFactory );
73 $this->rebuildRecentChangesTablePass4( $lbFactory );
74 $this->rebuildRecentChangesTablePass5( $lbFactory );
75 if ( !( $this->hasOption( 'from' ) && $this->hasOption( 'to' ) ) ) {
76 $this->purgeFeeds();
77 }
78 $this->output( "Done.\n" );
79 }
80
84 private function rebuildRecentChangesTablePass1( ILBFactory $lbFactory ) {
85 $dbw = $this->getDB( DB_MASTER );
86 $commentStore = CommentStore::getStore();
87
88 if ( $this->hasOption( 'from' ) && $this->hasOption( 'to' ) ) {
89 $this->cutoffFrom = wfTimestamp( TS_UNIX, $this->getOption( 'from' ) );
90 $this->cutoffTo = wfTimestamp( TS_UNIX, $this->getOption( 'to' ) );
91
92 $sec = $this->cutoffTo - $this->cutoffFrom;
93 $days = $sec / 24 / 3600;
94 $this->output( "Rebuilding range of $sec seconds ($days days)\n" );
95 } else {
96 global $wgRCMaxAge;
97
98 $days = $wgRCMaxAge / 24 / 3600;
99 $this->output( "Rebuilding \$wgRCMaxAge=$wgRCMaxAge seconds ($days days)\n" );
100
101 $this->cutoffFrom = time() - $wgRCMaxAge;
102 $this->cutoffTo = time();
103 }
104
105 $this->output( "Clearing recentchanges table for time range...\n" );
106 $rcids = $dbw->selectFieldValues(
107 'recentchanges',
108 'rc_id',
109 [
110 'rc_timestamp > ' . $dbw->addQuotes( $dbw->timestamp( $this->cutoffFrom ) ),
111 'rc_timestamp < ' . $dbw->addQuotes( $dbw->timestamp( $this->cutoffTo ) )
112 ]
113 );
114 foreach ( array_chunk( $rcids, $this->getBatchSize() ) as $rcidBatch ) {
115 $dbw->delete( 'recentchanges', [ 'rc_id' => $rcidBatch ], __METHOD__ );
116 $lbFactory->waitForReplication();
117 }
118
119 $this->output( "Loading from page and revision tables...\n" );
120
121 $commentQuery = $commentStore->getJoin( 'rev_comment' );
122 $actorQuery = ActorMigration::newMigration()->getJoin( 'rev_user' );
123 $res = $dbw->select(
124 [ 'revision', 'page' ] + $commentQuery['tables'] + $actorQuery['tables'],
125 [
126 'rev_timestamp',
127 'rev_minor_edit',
128 'rev_id',
129 'rev_deleted',
130 'page_namespace',
131 'page_title',
132 'page_is_new',
133 'page_id'
134 ] + $commentQuery['fields'] + $actorQuery['fields'],
135 [
136 'rev_timestamp > ' . $dbw->addQuotes( $dbw->timestamp( $this->cutoffFrom ) ),
137 'rev_timestamp < ' . $dbw->addQuotes( $dbw->timestamp( $this->cutoffTo ) )
138 ],
139 __METHOD__,
140 [ 'ORDER BY' => 'rev_timestamp DESC' ],
141 [
142 'page' => [ 'JOIN', 'rev_page=page_id' ],
143 ] + $commentQuery['joins'] + $actorQuery['joins']
144 );
145
146 $this->output( "Inserting from page and revision tables...\n" );
147 $inserted = 0;
148 $actorMigration = ActorMigration::newMigration();
149 foreach ( $res as $row ) {
150 $comment = $commentStore->getComment( 'rev_comment', $row );
151 $user = User::newFromAnyId( $row->rev_user, $row->rev_user_text, $row->rev_actor );
152 $dbw->insert(
153 'recentchanges',
154 [
155 'rc_timestamp' => $row->rev_timestamp,
156 'rc_namespace' => $row->page_namespace,
157 'rc_title' => $row->page_title,
158 'rc_minor' => $row->rev_minor_edit,
159 'rc_bot' => 0,
160 'rc_new' => $row->page_is_new,
161 'rc_cur_id' => $row->page_id,
162 'rc_this_oldid' => $row->rev_id,
163 'rc_last_oldid' => 0, // is this ok?
164 'rc_type' => $row->page_is_new ? RC_NEW : RC_EDIT,
165 'rc_source' => $row->page_is_new ? RecentChange::SRC_NEW : RecentChange::SRC_EDIT,
166 'rc_deleted' => $row->rev_deleted
167 ] + $commentStore->insert( $dbw, 'rc_comment', $comment )
168 + $actorMigration->getInsertValues( $dbw, 'rc_user', $user ),
169 __METHOD__
170 );
171
172 $rcid = $dbw->insertId();
173 $dbw->update(
174 'change_tag',
175 [ 'ct_rc_id' => $rcid ],
176 [ 'ct_rev_id' => $row->rev_id ],
177 __METHOD__
178 );
179
180 if ( ( ++$inserted % $this->getBatchSize() ) == 0 ) {
181 $lbFactory->waitForReplication();
182 }
183 }
184 }
185
190 private function rebuildRecentChangesTablePass2( ILBFactory $lbFactory ) {
191 $dbw = $this->getDB( DB_MASTER );
192
193 $this->output( "Updating links and size differences...\n" );
194
195 # Fill in the rc_last_oldid field, which points to the previous edit
196 $res = $dbw->select(
197 'recentchanges',
198 [ 'rc_cur_id', 'rc_this_oldid', 'rc_timestamp' ],
199 [
200 "rc_timestamp > " . $dbw->addQuotes( $dbw->timestamp( $this->cutoffFrom ) ),
201 "rc_timestamp < " . $dbw->addQuotes( $dbw->timestamp( $this->cutoffTo ) )
202 ],
203 __METHOD__,
204 [ 'ORDER BY' => 'rc_cur_id,rc_timestamp' ]
205 );
206
207 $lastCurId = 0;
208 $lastOldId = 0;
209 $lastSize = null;
210 $updated = 0;
211 foreach ( $res as $obj ) {
212 $new = 0;
213
214 if ( $obj->rc_cur_id != $lastCurId ) {
215 # Switch! Look up the previous last edit, if any
216 $lastCurId = intval( $obj->rc_cur_id );
217 $emit = $obj->rc_timestamp;
218
219 $row = $dbw->selectRow(
220 'revision',
221 [ 'rev_id', 'rev_len' ],
222 [ 'rev_page' => $lastCurId, "rev_timestamp < " . $dbw->addQuotes( $emit ) ],
223 __METHOD__,
224 [ 'ORDER BY' => 'rev_timestamp DESC' ]
225 );
226 if ( $row ) {
227 $lastOldId = intval( $row->rev_id );
228 # Grab the last text size if available
229 $lastSize = !is_null( $row->rev_len ) ? intval( $row->rev_len ) : null;
230 } else {
231 # No previous edit
232 $lastOldId = 0;
233 $lastSize = 0;
234 $new = 1; // probably true
235 }
236 }
237
238 if ( $lastCurId == 0 ) {
239 $this->output( "Uhhh, something wrong? No curid\n" );
240 } else {
241 # Grab the entry's text size
242 $size = (int)$dbw->selectField(
243 'revision',
244 'rev_len',
245 [ 'rev_id' => $obj->rc_this_oldid ],
246 __METHOD__
247 );
248
249 $dbw->update(
250 'recentchanges',
251 [
252 'rc_last_oldid' => $lastOldId,
253 'rc_new' => $new,
254 'rc_type' => $new ? RC_NEW : RC_EDIT,
255 'rc_source' => $new === 1 ? RecentChange::SRC_NEW : RecentChange::SRC_EDIT,
256 'rc_old_len' => $lastSize,
257 'rc_new_len' => $size,
258 ],
259 [
260 'rc_cur_id' => $lastCurId,
261 'rc_this_oldid' => $obj->rc_this_oldid,
262 'rc_timestamp' => $obj->rc_timestamp // index usage
263 ],
264 __METHOD__
265 );
266
267 $lastOldId = intval( $obj->rc_this_oldid );
268 $lastSize = $size;
269
270 if ( ( ++$updated % $this->getBatchSize() ) == 0 ) {
271 $lbFactory->waitForReplication();
272 }
273 }
274 }
275 }
276
280 private function rebuildRecentChangesTablePass3( ILBFactory $lbFactory ) {
282
283 $dbw = $this->getDB( DB_MASTER );
284 $commentStore = CommentStore::getStore();
285 $nonRCLogs = array_merge( array_keys( $wgLogRestrictions ),
286 array_keys( $wgFilterLogTypes ),
287 [ 'create' ] );
288
289 $this->output( "Loading from user and logging tables...\n" );
290
291 $commentQuery = $commentStore->getJoin( 'log_comment' );
292 $actorQuery = ActorMigration::newMigration()->getJoin( 'log_user' );
293 $res = $dbw->select(
294 [ 'logging' ] + $commentQuery['tables'] + $actorQuery['tables'],
295 [
296 'log_timestamp',
297 'log_namespace',
298 'log_title',
299 'log_page',
300 'log_type',
301 'log_action',
302 'log_id',
303 'log_params',
304 'log_deleted'
305 ] + $commentQuery['fields'] + $actorQuery['fields'],
306 [
307 'log_timestamp > ' . $dbw->addQuotes( $dbw->timestamp( $this->cutoffFrom ) ),
308 'log_timestamp < ' . $dbw->addQuotes( $dbw->timestamp( $this->cutoffTo ) ),
309 // Some logs don't go in RC since they are private, or are included in the filterable log types.
310 'log_type' => array_diff( LogPage::validTypes(), $nonRCLogs ),
311 ],
312 __METHOD__,
313 [ 'ORDER BY' => 'log_timestamp DESC' ],
314 $commentQuery['joins'] + $actorQuery['joins']
315 );
316
317 $field = $dbw->fieldInfo( 'recentchanges', 'rc_cur_id' );
318
319 $inserted = 0;
320 $actorMigration = ActorMigration::newMigration();
321 foreach ( $res as $row ) {
322 $comment = $commentStore->getComment( 'log_comment', $row );
323 $user = User::newFromAnyId( $row->log_user, $row->log_user_text, $row->log_actor );
324 $dbw->insert(
325 'recentchanges',
326 [
327 'rc_timestamp' => $row->log_timestamp,
328 'rc_namespace' => $row->log_namespace,
329 'rc_title' => $row->log_title,
330 'rc_minor' => 0,
331 'rc_bot' => 0,
332 'rc_patrolled' => $row->log_type == 'upload' ? 0 : 2,
333 'rc_new' => 0,
334 'rc_this_oldid' => 0,
335 'rc_last_oldid' => 0,
336 'rc_type' => RC_LOG,
337 'rc_source' => RecentChange::SRC_LOG,
338 'rc_cur_id' => $field->isNullable()
339 ? $row->log_page
340 : (int)$row->log_page, // NULL => 0,
341 'rc_log_type' => $row->log_type,
342 'rc_log_action' => $row->log_action,
343 'rc_logid' => $row->log_id,
344 'rc_params' => $row->log_params,
345 'rc_deleted' => $row->log_deleted
346 ] + $commentStore->insert( $dbw, 'rc_comment', $comment )
347 + $actorMigration->getInsertValues( $dbw, 'rc_user', $user ),
348 __METHOD__
349 );
350
351 $rcid = $dbw->insertId();
352 $dbw->update(
353 'change_tag',
354 [ 'ct_rc_id' => $rcid ],
355 [ 'ct_log_id' => $row->log_id ],
356 __METHOD__
357 );
358
359 if ( ( ++$inserted % $this->getBatchSize() ) == 0 ) {
360 $lbFactory->waitForReplication();
361 }
362 }
363 }
364
368 private function rebuildRecentChangesTablePass4( ILBFactory $lbFactory ) {
370
371 $dbw = $this->getDB( DB_MASTER );
372
373 $userQuery = User::getQueryInfo();
374
375 # @FIXME: recognize other bot account groups (not the same as users with 'bot' rights)
376 # @NOTE: users with 'bot' rights choose when edits are bot edits or not. That information
377 # may be lost at this point (aside from joining on the patrol log table entries).
378 $botgroups = [ 'bot' ];
379 $autopatrolgroups = $wgUseRCPatrol ? User::getGroupsWithPermission( 'autopatrol' ) : [];
380
381 # Flag our recent bot edits
382 if ( $botgroups ) {
383 $this->output( "Flagging bot account edits...\n" );
384
385 # Find all users that are bots
386 $res = $dbw->select(
387 array_merge( [ 'user_groups' ], $userQuery['tables'] ),
388 $userQuery['fields'],
389 [ 'ug_group' => $botgroups ],
390 __METHOD__,
391 [ 'DISTINCT' ],
392 [ 'user_groups' => [ 'JOIN', 'user_id = ug_user' ] ] + $userQuery['joins']
393 );
394
395 $botusers = [];
396 foreach ( $res as $obj ) {
397 $botusers[] = User::newFromRow( $obj );
398 }
399
400 # Fill in the rc_bot field
401 if ( $botusers ) {
402 $actorQuery = ActorMigration::newMigration()->getWhere( $dbw, 'rc_user', $botusers, false );
403 $rcids = [];
404 foreach ( $actorQuery['orconds'] as $cond ) {
405 $rcids = array_merge( $rcids, $dbw->selectFieldValues(
406 [ 'recentchanges' ] + $actorQuery['tables'],
407 'rc_id',
408 [
409 "rc_timestamp > " . $dbw->addQuotes( $dbw->timestamp( $this->cutoffFrom ) ),
410 "rc_timestamp < " . $dbw->addQuotes( $dbw->timestamp( $this->cutoffTo ) ),
411 $cond,
412 ],
413 __METHOD__,
414 [],
415 $actorQuery['joins']
416 ) );
417 }
418 $rcids = array_values( array_unique( $rcids ) );
419
420 foreach ( array_chunk( $rcids, $this->getBatchSize() ) as $rcidBatch ) {
421 $dbw->update(
422 'recentchanges',
423 [ 'rc_bot' => 1 ],
424 [ 'rc_id' => $rcidBatch ],
425 __METHOD__
426 );
427 $lbFactory->waitForReplication();
428 }
429 }
430 }
431
432 # Flag our recent autopatrolled edits
433 if ( !$wgMiserMode && $autopatrolgroups ) {
434 $patrolusers = [];
435
436 $this->output( "Flagging auto-patrolled edits...\n" );
437
438 # Find all users in RC with autopatrol rights
439 $res = $dbw->select(
440 array_merge( [ 'user_groups' ], $userQuery['tables'] ),
441 $userQuery['fields'],
442 [ 'ug_group' => $autopatrolgroups ],
443 __METHOD__,
444 [ 'DISTINCT' ],
445 [ 'user_groups' => [ 'JOIN', 'user_id = ug_user' ] ] + $userQuery['joins']
446 );
447
448 foreach ( $res as $obj ) {
449 $patrolusers[] = User::newFromRow( $obj );
450 }
451
452 # Fill in the rc_patrolled field
453 if ( $patrolusers ) {
454 $actorQuery = ActorMigration::newMigration()->getWhere( $dbw, 'rc_user', $patrolusers, false );
455 foreach ( $actorQuery['orconds'] as $cond ) {
456 $dbw->update(
457 'recentchanges',
458 [ 'rc_patrolled' => 2 ],
459 [
460 $cond,
461 'rc_timestamp > ' . $dbw->addQuotes( $dbw->timestamp( $this->cutoffFrom ) ),
462 'rc_timestamp < ' . $dbw->addQuotes( $dbw->timestamp( $this->cutoffTo ) ),
463 'rc_patrolled' => 0
464 ],
465 __METHOD__
466 );
467 $lbFactory->waitForReplication();
468 }
469 }
470 }
471 }
472
477 private function rebuildRecentChangesTablePass5( ILBFactory $lbFactory ) {
478 $dbw = wfGetDB( DB_MASTER );
479
480 $this->output( "Removing duplicate revision and logging entries...\n" );
481
482 $res = $dbw->select(
483 [ 'logging', 'log_search' ],
484 [ 'ls_value', 'ls_log_id' ],
485 [
486 'ls_log_id = log_id',
487 'ls_field' => 'associated_rev_id',
488 'log_type' => 'upload',
489 'log_timestamp > ' . $dbw->addQuotes( $dbw->timestamp( $this->cutoffFrom ) ),
490 'log_timestamp < ' . $dbw->addQuotes( $dbw->timestamp( $this->cutoffTo ) ),
491 ],
492 __METHOD__
493 );
494
495 $updates = 0;
496 foreach ( $res as $obj ) {
497 $rev_id = $obj->ls_value;
498 $log_id = $obj->ls_log_id;
499
500 // Mark the logging row as having an associated rev id
501 $dbw->update(
502 'recentchanges',
503 /*SET*/ [ 'rc_this_oldid' => $rev_id ],
504 /*WHERE*/ [ 'rc_logid' => $log_id ],
505 __METHOD__
506 );
507
508 // Delete the revision row
509 $dbw->delete(
510 'recentchanges',
511 /*WHERE*/ [ 'rc_this_oldid' => $rev_id, 'rc_logid' => 0 ],
512 __METHOD__
513 );
514
515 if ( ( ++$updates % $this->getBatchSize() ) == 0 ) {
516 $lbFactory->waitForReplication();
517 }
518 }
519 }
520
524 private function purgeFeeds() {
525 global $wgFeedClasses;
526
527 $this->output( "Deleting feed timestamps.\n" );
528
529 $wanCache = MediaWikiServices::getInstance()->getMainWANObjectCache();
530 foreach ( $wgFeedClasses as $feed => $className ) {
531 $wanCache->delete( $wanCache->makeKey( 'rcfeed', $feed, 'timestamp' ) ); # Good enough for now.
532 }
533 }
534}
535
536$maintClass = RebuildRecentchanges::class;
537require_once RUN_MAINTENANCE_IF_MAIN;
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
$wgLogRestrictions
This restricts log access to those who have a certain right Users without this will not see it in the...
$wgUseRCPatrol
Use RC Patrolling to check for vandalism (from recent changes and watchlists) New pages and new files...
$wgRCMaxAge
Recentchanges items are periodically purged; entries older than this many seconds will go.
$wgFeedClasses
Available feeds objects.
$wgFilterLogTypes
Show/hide links on Special:Log will be shown for these log types.
$wgMiserMode
Disable database-intensive features.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
static validTypes()
Get the list of valid log types.
Definition LogPage.php:194
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
output( $out, $channel=null)
Throw some output to the user.
getDB( $db, $groups=[], $wiki=false)
Returns a database to be used by current maintenance script.
hasOption( $name)
Checks to see if a particular option exists.
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)
Set the batch size.
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
MediaWikiServices is the service locator for the application scope of MediaWiki.
Maintenance script that rebuilds recent changes from scratch.
execute()
Do the actual work.
rebuildRecentChangesTablePass5(ILBFactory $lbFactory)
Rebuild pass 5: Delete duplicate entries where we generate both a page revision and a log entry for a...
int $cutoffFrom
UNIX timestamp.
rebuildRecentChangesTablePass3(ILBFactory $lbFactory)
Rebuild pass 3: Insert recentchanges entries for action logs.
rebuildRecentChangesTablePass4(ILBFactory $lbFactory)
Rebuild pass 4: Mark bot and autopatrolled entries.
int $cutoffTo
UNIX timestamp.
__construct()
Default constructor.
rebuildRecentChangesTablePass1(ILBFactory $lbFactory)
Rebuild pass 1: Insert recentchanges entries for page revisions.
rebuildRecentChangesTablePass2(ILBFactory $lbFactory)
Rebuild pass 2: Enhance entries for page revisions with references to the previous revision (rc_last_...
purgeFeeds()
Purge cached feeds in $wanCache.
static getQueryInfo()
Return the tables, fields, and join conditions to be selected to create a new user object.
Definition User.php:5643
static newFromAnyId( $userId, $userName, $actorId)
Static factory method for creation from an ID, name, and/or actor ID.
Definition User.php:676
static newFromRow( $row, $data=null)
Create a new user object from a user row.
Definition User.php:772
static getGroupsWithPermission( $role)
Get all the groups who have a given permission.
Definition User.php:5039
$res
Definition database.txt:21
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
const RC_NEW
Definition Defines.php:152
const RC_LOG
Definition Defines.php:153
const RC_EDIT
Definition Defines.php:151
return true to allow those checks to and false if checking is done & $user
Definition hooks.txt:1510
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition injection.txt:37
An interface for generating database load balancers.
waitForReplication(array $opts=[])
Waits for the replica DBs to catch up to the current master position.
require_once RUN_MAINTENANCE_IF_MAIN
const DB_MASTER
Definition defines.php:26