Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 332
0.00% covered (danger)
0.00%
0 / 9
CRAP
0.00% covered (danger)
0.00%
0 / 1
RebuildRecentchanges
0.00% covered (danger)
0.00%
0 / 329
0.00% covered (danger)
0.00%
0 / 9
2450
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
2
 execute
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
56
 rebuildRecentChangesTablePass1
0.00% covered (danger)
0.00%
0 / 88
0.00% covered (danger)
0.00%
0 / 1
72
 rebuildRecentChangesTablePass2
0.00% covered (danger)
0.00%
0 / 57
0.00% covered (danger)
0.00%
0 / 1
90
 rebuildRecentChangesTablePass3
0.00% covered (danger)
0.00%
0 / 75
0.00% covered (danger)
0.00%
0 / 1
30
 findRcIdsWithGroups
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
6
 rebuildRecentChangesTablePass4
0.00% covered (danger)
0.00%
0 / 34
0.00% covered (danger)
0.00%
0 / 1
156
 rebuildRecentChangesTablePass5
0.00% covered (danger)
0.00%
0 / 28
0.00% covered (danger)
0.00%
0 / 1
12
 purgeFeeds
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
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
26require_once __DIR__ . '/Maintenance.php';
27
28use Wikimedia\Rdbms\IDatabase;
29use Wikimedia\Rdbms\SelectQueryBuilder;
30
31/**
32 * Maintenance script that rebuilds recent changes from scratch.
33 *
34 * @ingroup Maintenance
35 */
36class RebuildRecentchanges extends Maintenance {
37    /** @var int UNIX timestamp */
38    private $cutoffFrom;
39    /** @var int UNIX timestamp */
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        $this->rebuildRecentChangesTablePass1();
70        $this->rebuildRecentChangesTablePass2();
71        $this->rebuildRecentChangesTablePass3();
72        $this->rebuildRecentChangesTablePass4();
73        $this->rebuildRecentChangesTablePass5();
74        if ( !( $this->hasOption( 'from' ) && $this->hasOption( 'to' ) ) ) {
75            $this->purgeFeeds();
76        }
77        $this->output( "Done.\n" );
78    }
79
80    /**
81     * Rebuild pass 1: Insert `recentchanges` entries for page revisions.
82     */
83    private function rebuildRecentChangesTablePass1() {
84        $dbw = $this->getPrimaryDB();
85        $commentStore = $this->getServiceContainer()->getCommentStore();
86
87        if ( $this->hasOption( 'from' ) && $this->hasOption( 'to' ) ) {
88            $this->cutoffFrom = (int)wfTimestamp( TS_UNIX, $this->getOption( 'from' ) );
89            $this->cutoffTo = (int)wfTimestamp( TS_UNIX, $this->getOption( 'to' ) );
90
91            $sec = $this->cutoffTo - $this->cutoffFrom;
92            $days = $sec / 24 / 3600;
93            $this->output( "Rebuilding range of $sec seconds ($days days)\n" );
94        } else {
95            global $wgRCMaxAge;
96
97            $days = $wgRCMaxAge / 24 / 3600;
98            $this->output( "Rebuilding \$wgRCMaxAge=$wgRCMaxAge seconds ($days days)\n" );
99
100            $this->cutoffFrom = time() - $wgRCMaxAge;
101            $this->cutoffTo = time();
102        }
103
104        $this->output( "Clearing recentchanges table for time range...\n" );
105        $rcids = $dbw->newSelectQueryBuilder()
106            ->select( 'rc_id' )
107            ->from( 'recentchanges' )
108            ->where( $dbw->expr( 'rc_timestamp', '>', $dbw->timestamp( $this->cutoffFrom ) ) )
109            ->andWhere( $dbw->expr( 'rc_timestamp', '<', $dbw->timestamp( $this->cutoffTo ) ) )
110            ->caller( __METHOD__ )->fetchFieldValues();
111        foreach ( array_chunk( $rcids, $this->getBatchSize() ) as $rcidBatch ) {
112            $dbw->newDeleteQueryBuilder()
113                ->deleteFrom( 'recentchanges' )
114                ->where( [ 'rc_id' => $rcidBatch ] )
115                ->caller( __METHOD__ )->execute();
116            $this->waitForReplication();
117        }
118
119        $this->output( "Loading from page and revision tables...\n" );
120
121        $res = $dbw->newSelectQueryBuilder()
122            ->select(
123                [
124                    'rev_timestamp',
125                    'rev_minor_edit',
126                    'rev_id',
127                    'rev_deleted',
128                    'page_namespace',
129                    'page_title',
130                    'page_is_new',
131                    'page_id',
132                    'rev_comment_text' => 'comment_rev_comment.comment_text',
133                    'rev_comment_data' => 'comment_rev_comment.comment_data',
134                    'rev_comment_cid' => 'comment_rev_comment.comment_id',
135                    'rev_user' => 'actor_rev_user.actor_user',
136                    'rev_user_text' => 'actor_rev_user.actor_name',
137                    'rev_actor' => 'rev_actor',
138                ]
139            )
140            ->from( 'revision' )
141            ->join( 'page', null, 'rev_page=page_id' )
142            ->join( 'comment', 'comment_rev_comment', 'comment_rev_comment.comment_id = rev_comment_id' )
143            ->join( 'actor', 'actor_rev_user', 'actor_rev_user.actor_id = rev_actor' )
144            ->where(
145                [
146                    $dbw->expr( 'rev_timestamp', '>', $dbw->timestamp( $this->cutoffFrom ) ),
147                    $dbw->expr( 'rev_timestamp', '<', $dbw->timestamp( $this->cutoffTo ) )
148                ]
149            )
150            ->orderBy( 'rev_timestamp', SelectQueryBuilder::SORT_DESC )
151            ->caller( __METHOD__ )->fetchResultSet();
152
153        $this->output( "Inserting from page and revision tables...\n" );
154        $inserted = 0;
155        foreach ( $res as $row ) {
156            $comment = $commentStore->getComment( 'rev_comment', $row );
157            $dbw->newInsertQueryBuilder()
158                ->insertInto( 'recentchanges' )
159                ->row( [
160                    'rc_timestamp' => $row->rev_timestamp,
161                    'rc_actor' => $row->rev_actor,
162                    'rc_namespace' => $row->page_namespace,
163                    'rc_title' => $row->page_title,
164                    'rc_minor' => $row->rev_minor_edit,
165                    'rc_bot' => 0,
166                    'rc_new' => $row->page_is_new,
167                    'rc_cur_id' => $row->page_id,
168                    'rc_this_oldid' => $row->rev_id,
169                    'rc_last_oldid' => 0, // is this ok?
170                    'rc_type' => $row->page_is_new ? RC_NEW : RC_EDIT,
171                    'rc_source' => $row->page_is_new ? RecentChange::SRC_NEW : RecentChange::SRC_EDIT,
172                    'rc_deleted' => $row->rev_deleted
173                    ] + $commentStore->insert( $dbw, 'rc_comment', $comment ) )
174                ->caller( __METHOD__ )->execute();
175
176            $rcid = $dbw->insertId();
177            $dbw->newUpdateQueryBuilder()
178                ->update( 'change_tag' )
179                ->set( [ 'ct_rc_id' => $rcid ] )
180                ->where( [ 'ct_rev_id' => $row->rev_id ] )
181                ->caller( __METHOD__ )->execute();
182
183            if ( ( ++$inserted % $this->getBatchSize() ) == 0 ) {
184                $this->waitForReplication();
185            }
186        }
187    }
188
189    /**
190     * Rebuild pass 2: Enhance entries for page revisions with references to the previous revision
191     * (rc_last_oldid, rc_new etc.) and size differences (rc_old_len, rc_new_len).
192     */
193    private function rebuildRecentChangesTablePass2() {
194        $dbw = $this->getPrimaryDB();
195
196        $this->output( "Updating links and size differences...\n" );
197
198        # Fill in the rc_last_oldid field, which points to the previous edit
199        $res = $dbw->newSelectQueryBuilder()
200            ->select( [ 'rc_cur_id', 'rc_this_oldid', 'rc_timestamp' ] )
201            ->from( 'recentchanges' )
202            ->where( $dbw->expr( 'rc_timestamp', '>', $dbw->timestamp( $this->cutoffFrom ) ) )
203            ->andWhere( $dbw->expr( 'rc_timestamp', '<', $dbw->timestamp( $this->cutoffTo ) ) )
204            ->orderBy( [ 'rc_cur_id', 'rc_timestamp' ] )
205            ->caller( __METHOD__ )->fetchResultSet();
206
207        $lastCurId = 0;
208        $lastOldId = 0;
209        $lastSize = null;
210        $updated = 0;
211        foreach ( $res as $row ) {
212            $new = 0;
213
214            if ( $row->rc_cur_id != $lastCurId ) {
215                # Switch! Look up the previous last edit, if any
216                $lastCurId = intval( $row->rc_cur_id );
217                $emit = $row->rc_timestamp;
218
219                $revRow = $dbw->newSelectQueryBuilder()
220                    ->select( [ 'rev_id', 'rev_len' ] )
221                    ->from( 'revision' )
222                    ->where( [ 'rev_page' => $lastCurId, $dbw->expr( 'rev_timestamp', '<', $emit ) ] )
223                    ->orderBy( 'rev_timestamp DESC' )
224                    ->caller( __METHOD__ )->fetchRow();
225                if ( $revRow ) {
226                    $lastOldId = intval( $revRow->rev_id );
227                    # Grab the last text size if available
228                    $lastSize = $revRow->rev_len !== null ? intval( $revRow->rev_len ) : null;
229                } else {
230                    # No previous edit
231                    $lastOldId = 0;
232                    $lastSize = 0;
233                    $new = 1; // probably true
234                }
235            }
236
237            if ( $lastCurId == 0 ) {
238                $this->output( "Uhhh, something wrong? No curid\n" );
239            } else {
240                # Grab the entry's text size
241                $size = (int)$dbw->newSelectQueryBuilder()
242                    ->select( 'rev_len' )
243                    ->from( 'revision' )
244                    ->where( [ 'rev_id' => $row->rc_this_oldid ] )
245                    ->caller( __METHOD__ )->fetchField();
246
247                $dbw->newUpdateQueryBuilder()
248                    ->update( 'recentchanges' )
249                    ->set( [
250                        'rc_last_oldid' => $lastOldId,
251                        'rc_new' => $new,
252                        'rc_type' => $new ? RC_NEW : RC_EDIT,
253                        'rc_source' => $new === 1 ? RecentChange::SRC_NEW : RecentChange::SRC_EDIT,
254                        'rc_old_len' => $lastSize,
255                        'rc_new_len' => $size,
256                    ] )
257                    ->where( [
258                        'rc_cur_id' => $lastCurId,
259                        'rc_this_oldid' => $row->rc_this_oldid,
260                        // index usage
261                        'rc_timestamp' => $row->rc_timestamp,
262                    ] )
263                    ->caller( __METHOD__ )->execute();
264
265                $lastOldId = intval( $row->rc_this_oldid );
266                $lastSize = $size;
267
268                if ( ( ++$updated % $this->getBatchSize() ) == 0 ) {
269                    $this->waitForReplication();
270                }
271            }
272        }
273    }
274
275    /**
276     * Rebuild pass 3: Insert `recentchanges` entries for action logs.
277     */
278    private function rebuildRecentChangesTablePass3() {
279        global $wgLogRestrictions, $wgFilterLogTypes;
280
281        $dbw = $this->getDB( DB_PRIMARY );
282        $commentStore = $this->getServiceContainer()->getCommentStore();
283        $nonRCLogs = array_merge(
284            array_keys( $wgLogRestrictions ),
285            array_keys( $wgFilterLogTypes ),
286            [ 'create' ]
287        );
288
289        $this->output( "Loading from user and logging tables...\n" );
290
291        $res = $dbw->newSelectQueryBuilder()
292            ->select(
293                [
294                    'log_timestamp',
295                    'log_actor',
296                    'log_namespace',
297                    'log_title',
298                    'log_page',
299                    'log_type',
300                    'log_action',
301                    'log_id',
302                    'log_params',
303                    'log_deleted',
304                    'log_comment_text' => 'comment_log_comment.comment_text',
305                    'log_comment_data' => 'comment_log_comment.comment_data',
306                    'log_comment_cid' => 'comment_log_comment.comment_id',
307                ]
308            )
309            ->from( 'logging' )
310            ->join( 'comment', 'comment_log_comment', 'comment_log_comment.comment_id = log_comment_id' )
311            ->where(
312                [
313                    $dbw->expr( 'log_timestamp', '>', $dbw->timestamp( $this->cutoffFrom ) ),
314                    $dbw->expr( 'log_timestamp', '<', $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            )
319            ->orderBy( [ 'log_timestamp DESC', 'log_id DESC' ] )
320            ->caller( __METHOD__ )->fetchResultSet();
321
322        $field = $dbw->fieldInfo( 'recentchanges', 'rc_cur_id' );
323
324        $inserted = 0;
325        foreach ( $res as $row ) {
326            $comment = $commentStore->getComment( 'log_comment', $row );
327            $dbw->newInsertQueryBuilder()
328                ->insertInto( 'recentchanges' )
329                ->row( [
330                    'rc_timestamp' => $row->log_timestamp,
331                    'rc_actor' => $row->log_actor,
332                    'rc_namespace' => $row->log_namespace,
333                    'rc_title' => $row->log_title,
334                    'rc_minor' => 0,
335                    'rc_bot' => 0,
336                    'rc_patrolled' => $row->log_type == 'upload' ? 0 : 2,
337                    'rc_new' => 0,
338                    'rc_this_oldid' => 0,
339                    'rc_last_oldid' => 0,
340                    'rc_type' => RC_LOG,
341                    'rc_source' => RecentChange::SRC_LOG,
342                    'rc_cur_id' => $field->isNullable()
343                        ? $row->log_page
344                        : (int)$row->log_page, // NULL => 0,
345                    'rc_log_type' => $row->log_type,
346                    'rc_log_action' => $row->log_action,
347                    'rc_logid' => $row->log_id,
348                    'rc_params' => $row->log_params,
349                    'rc_deleted' => $row->log_deleted
350                    ] + $commentStore->insert( $dbw, 'rc_comment', $comment ) )
351                ->caller( __METHOD__ )->execute();
352
353            $rcid = $dbw->insertId();
354            $dbw->newUpdateQueryBuilder()
355                ->update( 'change_tag' )
356                ->set( [ 'ct_rc_id' => $rcid ] )
357                ->where( [ 'ct_log_id' => $row->log_id ] )
358                ->caller( __METHOD__ )->execute();
359
360            if ( ( ++$inserted % $this->getBatchSize() ) == 0 ) {
361                $this->waitForReplication();
362            }
363        }
364    }
365
366    /**
367     * Find rc_id values that have a user with one of the specified groups
368     *
369     * @param IDatabase $db
370     * @param string[] $groups
371     * @param array $conds Extra query conditions
372     * @return int[]
373     */
374    private function findRcIdsWithGroups( $db, $groups, $conds = [] ) {
375        if ( !count( $groups ) ) {
376            return [];
377        }
378        return $db->newSelectQueryBuilder()
379            ->select( 'rc_id' )
380            ->distinct()
381            ->from( 'recentchanges' )
382            ->join( 'actor', null, 'actor_id=rc_actor' )
383            ->join( 'user_groups', null, 'ug_user=actor_user' )
384            ->where( $conds )
385            ->andWhere( [
386                $db->expr( 'rc_timestamp', '>', $db->timestamp( $this->cutoffFrom ) ),
387                $db->expr( 'rc_timestamp', '<', $db->timestamp( $this->cutoffTo ) ),
388                'ug_group' => $groups
389            ] )
390            ->caller( __METHOD__ )->fetchFieldValues();
391    }
392
393    /**
394     * Rebuild pass 4: Mark bot and autopatrolled entries.
395     */
396    private function rebuildRecentChangesTablePass4() {
397        global $wgUseRCPatrol, $wgUseNPPatrol, $wgUseFilePatrol, $wgMiserMode;
398
399        $dbw = $this->getPrimaryDB();
400
401        # @FIXME: recognize other bot account groups (not the same as users with 'bot' rights)
402        # @NOTE: users with 'bot' rights choose when edits are bot edits or not. That information
403        # may be lost at this point (aside from joining on the patrol log table entries).
404        $botgroups = [ 'bot' ];
405        $autopatrolgroups = ( $wgUseRCPatrol || $wgUseNPPatrol || $wgUseFilePatrol ) ?
406            $this->getServiceContainer()->getGroupPermissionsLookup()
407            ->getGroupsWithPermission( 'autopatrol' ) : [];
408
409        # Flag our recent bot edits
410        // @phan-suppress-next-line PhanRedundantCondition
411        if ( $botgroups ) {
412            $this->output( "Flagging bot account edits...\n" );
413
414            # Fill in the rc_bot field
415            $rcids = $this->findRcIdsWithGroups( $dbw, $botgroups );
416
417            foreach ( array_chunk( $rcids, $this->getBatchSize() ) as $rcidBatch ) {
418                $dbw->newUpdateQueryBuilder()
419                    ->update( 'recentchanges' )
420                    ->set( [ 'rc_bot' => 1 ] )
421                    ->where( [ 'rc_id' => $rcidBatch ] )
422                    ->caller( __METHOD__ )->execute();
423                $this->waitForReplication();
424            }
425        }
426
427        # Flag our recent autopatrolled edits
428        if ( !$wgMiserMode && $autopatrolgroups ) {
429            $this->output( "Flagging auto-patrolled edits...\n" );
430
431            $conds = [ 'rc_patrolled' => 0 ];
432            if ( !$wgUseRCPatrol ) {
433                $subConds = [];
434                if ( $wgUseNPPatrol ) {
435                    $subConds[] = $dbw->expr( 'rc_source', '=', RecentChange::SRC_NEW );
436                }
437                if ( $wgUseFilePatrol ) {
438                    $subConds[] = $dbw->expr( 'rc_log_type', '=', 'upload' );
439                }
440                $conds[] = $dbw->makeList( $subConds, IDatabase::LIST_OR );
441            }
442
443            $rcids = $this->findRcIdsWithGroups( $dbw, $autopatrolgroups, $conds );
444            foreach ( array_chunk( $rcids, $this->getBatchSize() ) as $rcidBatch ) {
445                $dbw->newUpdateQueryBuilder()
446                    ->update( 'recentchanges' )
447                    ->set( [ 'rc_patrolled' => 2 ] )
448                    ->where( [ 'rc_id' => $rcidBatch ] )
449                    ->caller( __METHOD__ )->execute();
450                $this->waitForReplication();
451            }
452        }
453    }
454
455    /**
456     * Rebuild pass 5: Delete duplicate entries where we generate both a page revision and a log
457     * entry for a single action (upload, move, protect, import, etc.).
458     */
459    private function rebuildRecentChangesTablePass5() {
460        $dbw = $this->getPrimaryDB();
461
462        $this->output( "Removing duplicate revision and logging entries...\n" );
463
464        $res = $dbw->newSelectQueryBuilder()
465            ->select( [ 'ls_value', 'ls_log_id' ] )
466            ->from( 'logging' )
467            ->join( 'log_search', null, 'ls_log_id = log_id' )
468            ->where( [
469                'ls_field' => 'associated_rev_id',
470                $dbw->expr( 'log_type', '!=', 'create' ),
471                $dbw->expr( 'log_timestamp', '>', $dbw->timestamp( $this->cutoffFrom ) ),
472                $dbw->expr( 'log_timestamp', '<', $dbw->timestamp( $this->cutoffTo ) ),
473            ] )
474            ->caller( __METHOD__ )->fetchResultSet();
475
476        $updates = 0;
477        foreach ( $res as $row ) {
478            $rev_id = $row->ls_value;
479            $log_id = $row->ls_log_id;
480
481            // Mark the logging row as having an associated rev id
482            $dbw->newUpdateQueryBuilder()
483                ->update( 'recentchanges' )
484                ->set( [ 'rc_this_oldid' => $rev_id ] )
485                ->where( [ 'rc_logid' => $log_id ] )
486                ->caller( __METHOD__ )->execute();
487
488            // Delete the revision row
489            $dbw->newDeleteQueryBuilder()
490                ->deleteFrom( 'recentchanges' )
491                ->where( [ 'rc_this_oldid' => $rev_id, 'rc_logid' => 0 ] )
492                ->caller( __METHOD__ )->execute();
493
494            if ( ( ++$updates % $this->getBatchSize() ) == 0 ) {
495                $this->waitForReplication();
496            }
497        }
498    }
499
500    /**
501     * Purge cached feeds in $wanCache
502     */
503    private function purgeFeeds() {
504        global $wgFeedClasses;
505
506        $this->output( "Deleting feed timestamps.\n" );
507
508        $wanCache = $this->getServiceContainer()->getMainWANObjectCache();
509        foreach ( $wgFeedClasses as $feed => $className ) {
510            $wanCache->delete( $wanCache->makeKey( 'rcfeed', $feed, 'timestamp' ) ); # Good enough for now.
511        }
512    }
513}
514
515$maintClass = RebuildRecentchanges::class;
516require_once RUN_MAINTENANCE_IF_MAIN;