Merge "Add support for 'hu-formal'"
[lhc/web/wiklou.git] / maintenance / rebuildrecentchanges.php
1 <?php
2 /**
3 * Rebuild recent changes from scratch. This takes several hours,
4 * depending on the database size and server configuration.
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
20 *
21 * @file
22 * @ingroup Maintenance
23 * @todo Document
24 */
25
26 require_once __DIR__ . '/Maintenance.php';
27 use MediaWiki\MediaWikiServices;
28
29 /**
30 * Maintenance script that rebuilds recent changes from scratch.
31 *
32 * @ingroup Maintenance
33 */
34 class RebuildRecentchanges extends Maintenance {
35 /** @var int UNIX timestamp */
36 private $cutoffFrom;
37 /** @var int UNIX timestamp */
38 private $cutoffTo;
39
40 public function __construct() {
41 parent::__construct();
42 $this->addDescription( 'Rebuild recent changes' );
43
44 $this->addOption(
45 'from',
46 "Only rebuild rows in requested time range (in YYYYMMDDHHMMSS format)",
47 false,
48 true
49 );
50 $this->addOption(
51 'to',
52 "Only rebuild rows in requested time range (in YYYYMMDDHHMMSS format)",
53 false,
54 true
55 );
56 $this->setBatchSize( 200 );
57 }
58
59 public function execute() {
60 if (
61 ( $this->hasOption( 'from' ) && !$this->hasOption( 'to' ) ) ||
62 ( !$this->hasOption( 'from' ) && $this->hasOption( 'to' ) )
63 ) {
64 $this->fatalError( "Both 'from' and 'to' must be given, or neither" );
65 }
66
67 $this->rebuildRecentChangesTablePass1();
68 $this->rebuildRecentChangesTablePass2();
69 $this->rebuildRecentChangesTablePass3();
70 $this->rebuildRecentChangesTablePass4();
71 $this->rebuildRecentChangesTablePass5();
72 if ( !( $this->hasOption( 'from' ) && $this->hasOption( 'to' ) ) ) {
73 $this->purgeFeeds();
74 }
75 $this->output( "Done.\n" );
76 }
77
78 /**
79 * Rebuild pass 1: Insert `recentchanges` entries for page revisions.
80 */
81 private function rebuildRecentChangesTablePass1() {
82 $dbw = $this->getDB( DB_MASTER );
83 $commentStore = CommentStore::getStore();
84
85 if ( $this->hasOption( 'from' ) && $this->hasOption( 'to' ) ) {
86 $this->cutoffFrom = wfTimestamp( TS_UNIX, $this->getOption( 'from' ) );
87 $this->cutoffTo = wfTimestamp( TS_UNIX, $this->getOption( 'to' ) );
88
89 $sec = $this->cutoffTo - $this->cutoffFrom;
90 $days = $sec / 24 / 3600;
91 $this->output( "Rebuilding range of $sec seconds ($days days)\n" );
92 } else {
93 global $wgRCMaxAge;
94
95 $days = $wgRCMaxAge / 24 / 3600;
96 $this->output( "Rebuilding \$wgRCMaxAge=$wgRCMaxAge seconds ($days days)\n" );
97
98 $this->cutoffFrom = time() - $wgRCMaxAge;
99 $this->cutoffTo = time();
100 }
101
102 $this->output( "Clearing recentchanges table for time range...\n" );
103 $rcids = $dbw->selectFieldValues(
104 'recentchanges',
105 'rc_id',
106 [
107 'rc_timestamp > ' . $dbw->addQuotes( $dbw->timestamp( $this->cutoffFrom ) ),
108 'rc_timestamp < ' . $dbw->addQuotes( $dbw->timestamp( $this->cutoffTo ) )
109 ]
110 );
111 foreach ( array_chunk( $rcids, $this->getBatchSize() ) as $rcidBatch ) {
112 $dbw->delete( 'recentchanges', [ 'rc_id' => $rcidBatch ], __METHOD__ );
113 wfGetLBFactory()->waitForReplication();
114 }
115
116 $this->output( "Loading from page and revision tables...\n" );
117
118 $commentQuery = $commentStore->getJoin( 'rev_comment' );
119 $actorQuery = ActorMigration::newMigration()->getJoin( 'rev_user' );
120 $res = $dbw->select(
121 [ 'revision', 'page' ] + $commentQuery['tables'] + $actorQuery['tables'],
122 [
123 'rev_timestamp',
124 'rev_minor_edit',
125 'rev_id',
126 'rev_deleted',
127 'page_namespace',
128 'page_title',
129 'page_is_new',
130 'page_id'
131 ] + $commentQuery['fields'] + $actorQuery['fields'],
132 [
133 'rev_timestamp > ' . $dbw->addQuotes( $dbw->timestamp( $this->cutoffFrom ) ),
134 'rev_timestamp < ' . $dbw->addQuotes( $dbw->timestamp( $this->cutoffTo ) )
135 ],
136 __METHOD__,
137 [ 'ORDER BY' => 'rev_timestamp DESC' ],
138 [
139 'page' => [ 'JOIN', 'rev_page=page_id' ],
140 ] + $commentQuery['joins'] + $actorQuery['joins']
141 );
142
143 $this->output( "Inserting from page and revision tables...\n" );
144 $inserted = 0;
145 $actorMigration = ActorMigration::newMigration();
146 foreach ( $res as $row ) {
147 $comment = $commentStore->getComment( 'rev_comment', $row );
148 $user = User::newFromAnyId( $row->rev_user, $row->rev_user_text, $row->rev_actor );
149 $dbw->insert(
150 'recentchanges',
151 [
152 'rc_timestamp' => $row->rev_timestamp,
153 'rc_namespace' => $row->page_namespace,
154 'rc_title' => $row->page_title,
155 'rc_minor' => $row->rev_minor_edit,
156 'rc_bot' => 0,
157 'rc_new' => $row->page_is_new,
158 'rc_cur_id' => $row->page_id,
159 'rc_this_oldid' => $row->rev_id,
160 'rc_last_oldid' => 0, // is this ok?
161 'rc_type' => $row->page_is_new ? RC_NEW : RC_EDIT,
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 + $actorMigration->getInsertValues( $dbw, 'rc_user', $user ),
166 __METHOD__
167 );
168 if ( ( ++$inserted % $this->getBatchSize() ) == 0 ) {
169 wfGetLBFactory()->waitForReplication();
170 }
171 }
172 }
173
174 /**
175 * Rebuild pass 2: Enhance entries for page revisions with references to the previous revision
176 * (rc_last_oldid, rc_new etc.) and size differences (rc_old_len, rc_new_len).
177 */
178 private function rebuildRecentChangesTablePass2() {
179 $dbw = $this->getDB( DB_MASTER );
180
181 $this->output( "Updating links and size differences...\n" );
182
183 # Fill in the rc_last_oldid field, which points to the previous edit
184 $res = $dbw->select(
185 'recentchanges',
186 [ 'rc_cur_id', 'rc_this_oldid', 'rc_timestamp' ],
187 [
188 "rc_timestamp > " . $dbw->addQuotes( $dbw->timestamp( $this->cutoffFrom ) ),
189 "rc_timestamp < " . $dbw->addQuotes( $dbw->timestamp( $this->cutoffTo ) )
190 ],
191 __METHOD__,
192 [ 'ORDER BY' => 'rc_cur_id,rc_timestamp' ]
193 );
194
195 $lastCurId = 0;
196 $lastOldId = 0;
197 $lastSize = null;
198 $updated = 0;
199 foreach ( $res as $obj ) {
200 $new = 0;
201
202 if ( $obj->rc_cur_id != $lastCurId ) {
203 # Switch! Look up the previous last edit, if any
204 $lastCurId = intval( $obj->rc_cur_id );
205 $emit = $obj->rc_timestamp;
206
207 $row = $dbw->selectRow(
208 'revision',
209 [ 'rev_id', 'rev_len' ],
210 [ 'rev_page' => $lastCurId, "rev_timestamp < " . $dbw->addQuotes( $emit ) ],
211 __METHOD__,
212 [ 'ORDER BY' => 'rev_timestamp DESC' ]
213 );
214 if ( $row ) {
215 $lastOldId = intval( $row->rev_id );
216 # Grab the last text size if available
217 $lastSize = !is_null( $row->rev_len ) ? intval( $row->rev_len ) : null;
218 } else {
219 # No previous edit
220 $lastOldId = 0;
221 $lastSize = null;
222 $new = 1; // probably true
223 }
224 }
225
226 if ( $lastCurId == 0 ) {
227 $this->output( "Uhhh, something wrong? No curid\n" );
228 } else {
229 # Grab the entry's text size
230 $size = (int)$dbw->selectField(
231 'revision',
232 'rev_len',
233 [ 'rev_id' => $obj->rc_this_oldid ],
234 __METHOD__
235 );
236
237 $dbw->update(
238 'recentchanges',
239 [
240 'rc_last_oldid' => $lastOldId,
241 'rc_new' => $new,
242 'rc_type' => $new ? RC_NEW : RC_EDIT,
243 'rc_source' => $new === 1 ? RecentChange::SRC_NEW : RecentChange::SRC_EDIT,
244 'rc_old_len' => $lastSize,
245 'rc_new_len' => $size,
246 ],
247 [
248 'rc_cur_id' => $lastCurId,
249 'rc_this_oldid' => $obj->rc_this_oldid,
250 'rc_timestamp' => $obj->rc_timestamp // index usage
251 ],
252 __METHOD__
253 );
254
255 $lastOldId = intval( $obj->rc_this_oldid );
256 $lastSize = $size;
257
258 if ( ( ++$updated % $this->getBatchSize() ) == 0 ) {
259 wfGetLBFactory()->waitForReplication();
260 }
261 }
262 }
263 }
264
265 /**
266 * Rebuild pass 3: Insert `recentchanges` entries for action logs.
267 */
268 private function rebuildRecentChangesTablePass3() {
269 global $wgLogTypes, $wgLogRestrictions;
270
271 $dbw = $this->getDB( DB_MASTER );
272 $commentStore = CommentStore::getStore();
273
274 $this->output( "Loading from user, page, and logging tables...\n" );
275
276 $commentQuery = $commentStore->getJoin( 'log_comment' );
277 $actorQuery = ActorMigration::newMigration()->getJoin( 'log_user' );
278 $res = $dbw->select(
279 [ 'logging', 'page' ] + $commentQuery['tables'] + $actorQuery['tables'],
280 [
281 'log_timestamp',
282 'log_namespace',
283 'log_title',
284 'page_id',
285 'log_type',
286 'log_action',
287 'log_id',
288 'log_params',
289 'log_deleted'
290 ] + $commentQuery['fields'] + $actorQuery['fields'],
291 [
292 'log_timestamp > ' . $dbw->addQuotes( $dbw->timestamp( $this->cutoffFrom ) ),
293 'log_timestamp < ' . $dbw->addQuotes( $dbw->timestamp( $this->cutoffTo ) ),
294 // Some logs don't go in RC since they are private.
295 // @FIXME: core/extensions also have spammy logs that don't go in RC.
296 'log_type' => array_diff( $wgLogTypes, array_keys( $wgLogRestrictions ) ),
297 ],
298 __METHOD__,
299 [ 'ORDER BY' => 'log_timestamp DESC' ],
300 [
301 'page' =>
302 [ 'LEFT JOIN', [ 'log_namespace=page_namespace', 'log_title=page_title' ] ]
303 ] + $commentQuery['joins'] + $actorQuery['joins']
304 );
305
306 $field = $dbw->fieldInfo( 'recentchanges', 'rc_cur_id' );
307
308 $inserted = 0;
309 $actorMigration = ActorMigration::newMigration();
310 foreach ( $res as $row ) {
311 $comment = $commentStore->getComment( 'log_comment', $row );
312 $user = User::newFromAnyId( $row->log_user, $row->log_user_text, $row->log_actor );
313 $dbw->insert(
314 'recentchanges',
315 [
316 'rc_timestamp' => $row->log_timestamp,
317 'rc_namespace' => $row->log_namespace,
318 'rc_title' => $row->log_title,
319 'rc_minor' => 0,
320 'rc_bot' => 0,
321 'rc_patrolled' => 1,
322 'rc_new' => 0,
323 'rc_this_oldid' => 0,
324 'rc_last_oldid' => 0,
325 'rc_type' => RC_LOG,
326 'rc_source' => RecentChange::SRC_LOG,
327 'rc_cur_id' => $field->isNullable()
328 ? $row->page_id
329 : (int)$row->page_id, // NULL => 0,
330 'rc_log_type' => $row->log_type,
331 'rc_log_action' => $row->log_action,
332 'rc_logid' => $row->log_id,
333 'rc_params' => $row->log_params,
334 'rc_deleted' => $row->log_deleted
335 ] + $commentStore->insert( $dbw, 'rc_comment', $comment )
336 + $actorMigration->getInsertValues( $dbw, 'rc_user', $user ),
337 __METHOD__
338 );
339
340 if ( ( ++$inserted % $this->getBatchSize() ) == 0 ) {
341 wfGetLBFactory()->waitForReplication();
342 }
343 }
344 }
345
346 /**
347 * Rebuild pass 4: Mark bot and autopatrolled entries.
348 */
349 private function rebuildRecentChangesTablePass4() {
350 global $wgUseRCPatrol, $wgMiserMode;
351
352 $dbw = $this->getDB( DB_MASTER );
353
354 $userQuery = User::getQueryInfo();
355
356 # @FIXME: recognize other bot account groups (not the same as users with 'bot' rights)
357 # @NOTE: users with 'bot' rights choose when edits are bot edits or not. That information
358 # may be lost at this point (aside from joining on the patrol log table entries).
359 $botgroups = [ 'bot' ];
360 $autopatrolgroups = $wgUseRCPatrol ? User::getGroupsWithPermission( 'autopatrol' ) : [];
361
362 # Flag our recent bot edits
363 if ( $botgroups ) {
364 $this->output( "Flagging bot account edits...\n" );
365
366 # Find all users that are bots
367 $res = $dbw->select(
368 array_merge( [ 'user_groups' ], $userQuery['tables'] ),
369 $userQuery['fields'],
370 [ 'ug_group' => $botgroups ],
371 __METHOD__,
372 [ 'DISTINCT' ],
373 [ 'user_group' => [ 'JOIN', 'user_id = ug_user' ] ] + $userQuery['joins']
374 );
375
376 $botusers = [];
377 foreach ( $res as $obj ) {
378 $botusers[] = User::newFromRow( $obj );
379 }
380
381 # Fill in the rc_bot field
382 if ( $botusers ) {
383 $actorQuery = ActorMigration::newMigration()->getWhere( $dbw, 'rc_user', $botusers, false );
384 $rcids = [];
385 foreach ( $actorQuery['orconds'] as $cond ) {
386 $rcids = array_merge( $rcids, $dbw->selectFieldValues(
387 [ 'recentchanges' ] + $actorQuery['tables'],
388 'rc_id',
389 [
390 "rc_timestamp > " . $dbw->addQuotes( $dbw->timestamp( $this->cutoffFrom ) ),
391 "rc_timestamp < " . $dbw->addQuotes( $dbw->timestamp( $this->cutoffTo ) ),
392 $cond,
393 ],
394 __METHOD__,
395 [],
396 $actorQuery['joins']
397 ) );
398 }
399 $rcids = array_values( array_unique( $rcids ) );
400
401 foreach ( array_chunk( $rcids, $this->getBatchSize() ) as $rcidBatch ) {
402 $dbw->update(
403 'recentchanges',
404 [ 'rc_bot' => 1 ],
405 [ 'rc_id' => $rcidBatch ],
406 __METHOD__
407 );
408 wfGetLBFactory()->waitForReplication();
409 }
410 }
411 }
412
413 # Flag our recent autopatrolled edits
414 if ( !$wgMiserMode && $autopatrolgroups ) {
415 $patrolusers = [];
416
417 $this->output( "Flagging auto-patrolled edits...\n" );
418
419 # Find all users in RC with autopatrol rights
420 $res = $dbw->select(
421 array_merge( [ 'user_groups' ], $userQuery['tables'] ),
422 $userQuery['fields'],
423 [ 'ug_group' => $autopatrolgroups ],
424 __METHOD__,
425 [ 'DISTINCT' ],
426 [ 'user_group' => [ 'JOIN', 'user_id = ug_user' ] ] + $userQuery['joins']
427 );
428
429 foreach ( $res as $obj ) {
430 $patrolusers[] = User::newFromRow( $obj );
431 }
432
433 # Fill in the rc_patrolled field
434 if ( $patrolusers ) {
435 $actorQuery = ActorMigration::newMigration()->getWhere( $dbw, 'rc_user', $patrolusers, false );
436 foreach ( $actorQuery['orconds'] as $cond ) {
437 $dbw->update(
438 'recentchanges',
439 [ 'rc_patrolled' => 1 ],
440 [
441 $cond,
442 'rc_timestamp > ' . $dbw->addQuotes( $dbw->timestamp( $this->cutoffFrom ) ),
443 'rc_timestamp < ' . $dbw->addQuotes( $dbw->timestamp( $this->cutoffTo ) ),
444 ],
445 __METHOD__
446 );
447 wfGetLBFactory()->waitForReplication();
448 }
449 }
450 }
451 }
452
453 /**
454 * Rebuild pass 5: Delete duplicate entries where we generate both a page revision and a log entry
455 * for a single action (upload only, at the moment, but potentially also move, protect, ...).
456 */
457 private function rebuildRecentChangesTablePass5() {
458 $dbw = wfGetDB( DB_MASTER );
459
460 $this->output( "Removing duplicate revision and logging entries...\n" );
461
462 $res = $dbw->select(
463 [ 'logging', 'log_search' ],
464 [ 'ls_value', 'ls_log_id' ],
465 [
466 'ls_log_id = log_id',
467 'ls_field' => 'associated_rev_id',
468 'log_type' => 'upload',
469 'log_timestamp > ' . $dbw->addQuotes( $dbw->timestamp( $this->cutoffFrom ) ),
470 'log_timestamp < ' . $dbw->addQuotes( $dbw->timestamp( $this->cutoffTo ) ),
471 ],
472 __METHOD__
473 );
474
475 $updates = 0;
476 foreach ( $res as $obj ) {
477 $rev_id = $obj->ls_value;
478 $log_id = $obj->ls_log_id;
479
480 // Mark the logging row as having an associated rev id
481 $dbw->update(
482 'recentchanges',
483 /*SET*/ [ 'rc_this_oldid' => $rev_id ],
484 /*WHERE*/ [ 'rc_logid' => $log_id ],
485 __METHOD__
486 );
487
488 // Delete the revision row
489 $dbw->delete(
490 'recentchanges',
491 /*WHERE*/ [ 'rc_this_oldid' => $rev_id, 'rc_logid' => 0 ],
492 __METHOD__
493 );
494
495 if ( ( ++$updates % $this->getBatchSize() ) == 0 ) {
496 wfGetLBFactory()->waitForReplication();
497 }
498 }
499 }
500
501 /**
502 * Purge cached feeds in $wanCache
503 */
504 private function purgeFeeds() {
505 global $wgFeedClasses;
506
507 $this->output( "Deleting feed timestamps.\n" );
508
509 $wanCache = MediaWikiServices::getInstance()->getMainWANObjectCache();
510 foreach ( $wgFeedClasses as $feed => $className ) {
511 $wanCache->delete( $wanCache->makeKey( 'rcfeed', $feed, 'timestamp' ) ); # Good enough for now.
512 }
513 }
514 }
515
516 $maintClass = RebuildRecentchanges::class;
517 require_once RUN_MAINTENANCE_IF_MAIN;