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\IReadableDatabase;
30use Wikimedia\Rdbms\SelectQueryBuilder;
31
32/**
33 * Maintenance script that rebuilds recent changes from scratch.
34 *
35 * @ingroup Maintenance
36 */
37class RebuildRecentchanges extends Maintenance {
38    /** @var int UNIX timestamp */
39    private $cutoffFrom;
40    /** @var int UNIX timestamp */
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        $this->rebuildRecentChangesTablePass1();
71        $this->rebuildRecentChangesTablePass2();
72        $this->rebuildRecentChangesTablePass3();
73        $this->rebuildRecentChangesTablePass4();
74        $this->rebuildRecentChangesTablePass5();
75        if ( !( $this->hasOption( 'from' ) && $this->hasOption( 'to' ) ) ) {
76            $this->purgeFeeds();
77        }
78        $this->output( "Done.\n" );
79    }
80
81    /**
82     * Rebuild pass 1: Insert `recentchanges` entries for page revisions.
83     */
84    private function rebuildRecentChangesTablePass1() {
85        $dbw = $this->getPrimaryDB();
86        $commentStore = $this->getServiceContainer()->getCommentStore();
87
88        if ( $this->hasOption( 'from' ) && $this->hasOption( 'to' ) ) {
89            $this->cutoffFrom = (int)wfTimestamp( TS_UNIX, $this->getOption( 'from' ) );
90            $this->cutoffTo = (int)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->newSelectQueryBuilder()
107            ->select( 'rc_id' )
108            ->from( 'recentchanges' )
109            ->where( $dbw->expr( 'rc_timestamp', '>', $dbw->timestamp( $this->cutoffFrom ) ) )
110            ->andWhere( $dbw->expr( 'rc_timestamp', '<', $dbw->timestamp( $this->cutoffTo ) ) )
111            ->caller( __METHOD__ )->fetchFieldValues();
112        foreach ( array_chunk( $rcids, $this->getBatchSize() ) as $rcidBatch ) {
113            $dbw->newDeleteQueryBuilder()
114                ->deleteFrom( 'recentchanges' )
115                ->where( [ 'rc_id' => $rcidBatch ] )
116                ->caller( __METHOD__ )->execute();
117            $this->waitForReplication();
118        }
119
120        $this->output( "Loading from page and revision tables...\n" );
121
122        $res = $dbw->newSelectQueryBuilder()
123            ->select(
124                [
125                    'rev_timestamp',
126                    'rev_minor_edit',
127                    'rev_id',
128                    'rev_deleted',
129                    'page_namespace',
130                    'page_title',
131                    'page_is_new',
132                    'page_id',
133                    'rev_comment_text' => 'comment_rev_comment.comment_text',
134                    'rev_comment_data' => 'comment_rev_comment.comment_data',
135                    'rev_comment_cid' => 'comment_rev_comment.comment_id',
136                    'rev_user' => 'actor_rev_user.actor_user',
137                    'rev_user_text' => 'actor_rev_user.actor_name',
138                    'rev_actor' => 'rev_actor',
139                ]
140            )
141            ->from( 'revision' )
142            ->join( 'page', null, 'rev_page=page_id' )
143            ->join( 'comment', 'comment_rev_comment', 'comment_rev_comment.comment_id = rev_comment_id' )
144            ->join( 'actor', 'actor_rev_user', 'actor_rev_user.actor_id = rev_actor' )
145            ->where(
146                [
147                    $dbw->expr( 'rev_timestamp', '>', $dbw->timestamp( $this->cutoffFrom ) ),
148                    $dbw->expr( 'rev_timestamp', '<', $dbw->timestamp( $this->cutoffTo ) )
149                ]
150            )
151            ->orderBy( 'rev_timestamp', SelectQueryBuilder::SORT_DESC )
152            ->caller( __METHOD__ )->fetchResultSet();
153
154        $this->output( "Inserting from page and revision tables...\n" );
155        $inserted = 0;
156        foreach ( $res as $row ) {
157            $comment = $commentStore->getComment( 'rev_comment', $row );
158            $dbw->newInsertQueryBuilder()
159                ->insertInto( 'recentchanges' )
160                ->row( [
161                    'rc_timestamp' => $row->rev_timestamp,
162                    'rc_actor' => $row->rev_actor,
163                    'rc_namespace' => $row->page_namespace,
164                    'rc_title' => $row->page_title,
165                    'rc_minor' => $row->rev_minor_edit,
166                    'rc_bot' => 0,
167                    'rc_new' => $row->page_is_new,
168                    'rc_cur_id' => $row->page_id,
169                    'rc_this_oldid' => $row->rev_id,
170                    'rc_last_oldid' => 0, // is this ok?
171                    'rc_type' => $row->page_is_new ? RC_NEW : RC_EDIT,
172                    'rc_source' => $row->page_is_new ? RecentChange::SRC_NEW : RecentChange::SRC_EDIT,
173                    'rc_deleted' => $row->rev_deleted
174                    ] + $commentStore->insert( $dbw, 'rc_comment', $comment ) )
175                ->caller( __METHOD__ )->execute();
176
177            $rcid = $dbw->insertId();
178            $dbw->newUpdateQueryBuilder()
179                ->update( 'change_tag' )
180                ->set( [ 'ct_rc_id' => $rcid ] )
181                ->where( [ 'ct_rev_id' => $row->rev_id ] )
182                ->caller( __METHOD__ )->execute();
183
184            if ( ( ++$inserted % $this->getBatchSize() ) == 0 ) {
185                $this->waitForReplication();
186            }
187        }
188    }
189
190    /**
191     * Rebuild pass 2: Enhance entries for page revisions with references to the previous revision
192     * (rc_last_oldid, rc_new etc.) and size differences (rc_old_len, rc_new_len).
193     */
194    private function rebuildRecentChangesTablePass2() {
195        $dbw = $this->getPrimaryDB();
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->newSelectQueryBuilder()
201            ->select( [ 'rc_cur_id', 'rc_this_oldid', 'rc_timestamp' ] )
202            ->from( 'recentchanges' )
203            ->where( $dbw->expr( 'rc_timestamp', '>', $dbw->timestamp( $this->cutoffFrom ) ) )
204            ->andWhere( $dbw->expr( 'rc_timestamp', '<', $dbw->timestamp( $this->cutoffTo ) ) )
205            ->orderBy( [ 'rc_cur_id', 'rc_timestamp' ] )
206            ->caller( __METHOD__ )->fetchResultSet();
207
208        $lastCurId = 0;
209        $lastOldId = 0;
210        $lastSize = null;
211        $updated = 0;
212        foreach ( $res as $row ) {
213            $new = 0;
214
215            if ( $row->rc_cur_id != $lastCurId ) {
216                # Switch! Look up the previous last edit, if any
217                $lastCurId = intval( $row->rc_cur_id );
218                $emit = $row->rc_timestamp;
219
220                $revRow = $dbw->newSelectQueryBuilder()
221                    ->select( [ 'rev_id', 'rev_len' ] )
222                    ->from( 'revision' )
223                    ->where( [ 'rev_page' => $lastCurId, $dbw->expr( 'rev_timestamp', '<', $emit ) ] )
224                    ->orderBy( 'rev_timestamp DESC' )
225                    ->caller( __METHOD__ )->fetchRow();
226                if ( $revRow ) {
227                    $lastOldId = intval( $revRow->rev_id );
228                    # Grab the last text size if available
229                    $lastSize = $revRow->rev_len !== null ? intval( $revRow->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->newSelectQueryBuilder()
243                    ->select( 'rev_len' )
244                    ->from( 'revision' )
245                    ->where( [ 'rev_id' => $row->rc_this_oldid ] )
246                    ->caller( __METHOD__ )->fetchField();
247
248                $dbw->newUpdateQueryBuilder()
249                    ->update( 'recentchanges' )
250                    ->set( [
251                        'rc_last_oldid' => $lastOldId,
252                        'rc_new' => $new,
253                        'rc_type' => $new ? RC_NEW : RC_EDIT,
254                        'rc_source' => $new === 1 ? RecentChange::SRC_NEW : RecentChange::SRC_EDIT,
255                        'rc_old_len' => $lastSize,
256                        'rc_new_len' => $size,
257                    ] )
258                    ->where( [
259                        'rc_cur_id' => $lastCurId,
260                        'rc_this_oldid' => $row->rc_this_oldid,
261                        // index usage
262                        'rc_timestamp' => $row->rc_timestamp,
263                    ] )
264                    ->caller( __METHOD__ )->execute();
265
266                $lastOldId = intval( $row->rc_this_oldid );
267                $lastSize = $size;
268
269                if ( ( ++$updated % $this->getBatchSize() ) == 0 ) {
270                    $this->waitForReplication();
271                }
272            }
273        }
274    }
275
276    /**
277     * Rebuild pass 3: Insert `recentchanges` entries for action logs.
278     */
279    private function rebuildRecentChangesTablePass3() {
280        global $wgLogRestrictions, $wgFilterLogTypes;
281
282        $dbw = $this->getDB( DB_PRIMARY );
283        $commentStore = $this->getServiceContainer()->getCommentStore();
284        $nonRCLogs = array_merge(
285            array_keys( $wgLogRestrictions ),
286            array_keys( $wgFilterLogTypes ),
287            [ 'create' ]
288        );
289
290        $this->output( "Loading from user and logging tables...\n" );
291
292        $res = $dbw->newSelectQueryBuilder()
293            ->select(
294                [
295                    'log_timestamp',
296                    'log_actor',
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                    'log_comment_text' => 'comment_log_comment.comment_text',
306                    'log_comment_data' => 'comment_log_comment.comment_data',
307                    'log_comment_cid' => 'comment_log_comment.comment_id',
308                ]
309            )
310            ->from( 'logging' )
311            ->join( 'comment', 'comment_log_comment', 'comment_log_comment.comment_id = log_comment_id' )
312            ->where(
313                [
314                    $dbw->expr( 'log_timestamp', '>', $dbw->timestamp( $this->cutoffFrom ) ),
315                    $dbw->expr( 'log_timestamp', '<', $dbw->timestamp( $this->cutoffTo ) ),
316                    // Some logs don't go in RC since they are private, or are included in the filterable log types.
317                    'log_type' => array_diff( LogPage::validTypes(), $nonRCLogs ),
318                ]
319            )
320            ->orderBy( [ 'log_timestamp DESC', 'log_id DESC' ] )
321            ->caller( __METHOD__ )->fetchResultSet();
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->newInsertQueryBuilder()
329                ->insertInto( 'recentchanges' )
330                ->row( [
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                ->caller( __METHOD__ )->execute();
353
354            $rcid = $dbw->insertId();
355            $dbw->newUpdateQueryBuilder()
356                ->update( 'change_tag' )
357                ->set( [ 'ct_rc_id' => $rcid ] )
358                ->where( [ 'ct_log_id' => $row->log_id ] )
359                ->caller( __METHOD__ )->execute();
360
361            if ( ( ++$inserted % $this->getBatchSize() ) == 0 ) {
362                $this->waitForReplication();
363            }
364        }
365    }
366
367    /**
368     * Find rc_id values that have a user with one of the specified groups
369     *
370     * @param IReadableDatabase $db
371     * @param string[] $groups
372     * @param array $conds Extra query conditions
373     * @return int[]
374     */
375    private function findRcIdsWithGroups( $db, $groups, $conds = [] ) {
376        if ( !count( $groups ) ) {
377            return [];
378        }
379        return $db->newSelectQueryBuilder()
380            ->select( 'rc_id' )
381            ->distinct()
382            ->from( 'recentchanges' )
383            ->join( 'actor', null, 'actor_id=rc_actor' )
384            ->join( 'user_groups', null, 'ug_user=actor_user' )
385            ->where( $conds )
386            ->andWhere( [
387                $db->expr( 'rc_timestamp', '>', $db->timestamp( $this->cutoffFrom ) ),
388                $db->expr( 'rc_timestamp', '<', $db->timestamp( $this->cutoffTo ) ),
389                'ug_group' => $groups
390            ] )
391            ->caller( __METHOD__ )->fetchFieldValues();
392    }
393
394    /**
395     * Rebuild pass 4: Mark bot and autopatrolled entries.
396     */
397    private function rebuildRecentChangesTablePass4() {
398        global $wgUseRCPatrol, $wgUseNPPatrol, $wgUseFilePatrol, $wgMiserMode;
399
400        $dbw = $this->getPrimaryDB();
401
402        # @FIXME: recognize other bot account groups (not the same as users with 'bot' rights)
403        # @NOTE: users with 'bot' rights choose when edits are bot edits or not. That information
404        # may be lost at this point (aside from joining on the patrol log table entries).
405        $botgroups = [ 'bot' ];
406        $autopatrolgroups = ( $wgUseRCPatrol || $wgUseNPPatrol || $wgUseFilePatrol ) ?
407            $this->getServiceContainer()->getGroupPermissionsLookup()
408            ->getGroupsWithPermission( 'autopatrol' ) : [];
409
410        # Flag our recent bot edits
411        // @phan-suppress-next-line PhanRedundantCondition
412        if ( $botgroups ) {
413            $this->output( "Flagging bot account edits...\n" );
414
415            # Fill in the rc_bot field
416            $rcids = $this->findRcIdsWithGroups( $dbw, $botgroups );
417
418            foreach ( array_chunk( $rcids, $this->getBatchSize() ) as $rcidBatch ) {
419                $dbw->newUpdateQueryBuilder()
420                    ->update( 'recentchanges' )
421                    ->set( [ 'rc_bot' => 1 ] )
422                    ->where( [ 'rc_id' => $rcidBatch ] )
423                    ->caller( __METHOD__ )->execute();
424                $this->waitForReplication();
425            }
426        }
427
428        # Flag our recent autopatrolled edits
429        if ( !$wgMiserMode && $autopatrolgroups ) {
430            $this->output( "Flagging auto-patrolled edits...\n" );
431
432            $conds = [ 'rc_patrolled' => 0 ];
433            if ( !$wgUseRCPatrol ) {
434                $subConds = [];
435                if ( $wgUseNPPatrol ) {
436                    $subConds[] = $dbw->expr( 'rc_source', '=', RecentChange::SRC_NEW );
437                }
438                if ( $wgUseFilePatrol ) {
439                    $subConds[] = $dbw->expr( 'rc_log_type', '=', 'upload' );
440                }
441                $conds[] = $dbw->makeList( $subConds, IDatabase::LIST_OR );
442            }
443
444            $rcids = $this->findRcIdsWithGroups( $dbw, $autopatrolgroups, $conds );
445            foreach ( array_chunk( $rcids, $this->getBatchSize() ) as $rcidBatch ) {
446                $dbw->newUpdateQueryBuilder()
447                    ->update( 'recentchanges' )
448                    ->set( [ 'rc_patrolled' => 2 ] )
449                    ->where( [ 'rc_id' => $rcidBatch ] )
450                    ->caller( __METHOD__ )->execute();
451                $this->waitForReplication();
452            }
453        }
454    }
455
456    /**
457     * Rebuild pass 5: Delete duplicate entries where we generate both a page revision and a log
458     * entry for a single action (upload, move, protect, import, etc.).
459     */
460    private function rebuildRecentChangesTablePass5() {
461        $dbw = $this->getPrimaryDB();
462
463        $this->output( "Removing duplicate revision and logging entries...\n" );
464
465        $res = $dbw->newSelectQueryBuilder()
466            ->select( [ 'ls_value', 'ls_log_id' ] )
467            ->from( 'logging' )
468            ->join( 'log_search', null, 'ls_log_id = log_id' )
469            ->where( [
470                'ls_field' => 'associated_rev_id',
471                $dbw->expr( 'log_type', '!=', 'create' ),
472                $dbw->expr( 'log_timestamp', '>', $dbw->timestamp( $this->cutoffFrom ) ),
473                $dbw->expr( 'log_timestamp', '<', $dbw->timestamp( $this->cutoffTo ) ),
474            ] )
475            ->caller( __METHOD__ )->fetchResultSet();
476
477        $updates = 0;
478        foreach ( $res as $row ) {
479            $rev_id = $row->ls_value;
480            $log_id = $row->ls_log_id;
481
482            // Mark the logging row as having an associated rev id
483            $dbw->newUpdateQueryBuilder()
484                ->update( 'recentchanges' )
485                ->set( [ 'rc_this_oldid' => $rev_id ] )
486                ->where( [ 'rc_logid' => $log_id ] )
487                ->caller( __METHOD__ )->execute();
488
489            // Delete the revision row
490            $dbw->newDeleteQueryBuilder()
491                ->deleteFrom( 'recentchanges' )
492                ->where( [ 'rc_this_oldid' => $rev_id, 'rc_logid' => 0 ] )
493                ->caller( __METHOD__ )->execute();
494
495            if ( ( ++$updates % $this->getBatchSize() ) == 0 ) {
496                $this->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 = $this->getServiceContainer()->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;
517require_once RUN_MAINTENANCE_IF_MAIN;