Merge ".mailmap: Correct two contributor names"
[mediawiki.git] / maintenance / cleanupInvalidDbKeys.php
blob209a6c23f3978a192f51a62cfa39a684a75ff2db
1 <?php
2 /**
3 * Cleans up invalid titles in various tables.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
21 * @ingroup Maintenance
24 // @codeCoverageIgnoreStart
25 require_once __DIR__ . '/Maintenance.php';
26 // @codeCoverageIgnoreEnd
28 use MediaWiki\Maintenance\Maintenance;
29 use MediaWiki\Title\Title;
30 use MediaWiki\WikiMap\WikiMap;
31 use Wikimedia\Rdbms\IExpression;
32 use Wikimedia\Rdbms\LikeValue;
34 /**
35 * Maintenance script that cleans up invalid titles in various tables.
37 * @since 1.29
38 * @ingroup Maintenance
40 class CleanupInvalidDbKeys extends Maintenance {
41 /** @var array[] List of tables to clean up, and the field prefix for that table */
42 protected static $tables = [
43 // Data tables
44 [ 'page', 'page' ],
45 [ 'redirect', 'rd', 'idField' => 'rd_from' ],
46 [ 'archive', 'ar' ],
47 [ 'logging', 'log' ],
48 [ 'protected_titles', 'pt', 'idField' => 0 ],
49 [ 'category', 'cat', 'nsField' => 14 ],
50 [ 'recentchanges', 'rc' ],
51 [ 'watchlist', 'wl' ],
52 // The querycache tables' qc(c)_title and qcc_titletwo may contain titles,
53 // but also usernames or other things like that, so we leave them alone
55 // Links tables
56 [ 'pagelinks', 'pl', 'idField' => 'pl_from' ],
57 [ 'templatelinks', 'tl', 'idField' => 'tl_from' ],
58 [ 'categorylinks', 'cl', 'idField' => 'cl_from', 'nsField' => 14, 'titleField' => 'cl_to' ],
59 [ 'imagelinks', 'il', 'idField' => 'il_from', 'nsField' => 6, 'titleField' => 'il_to' ],
62 public function __construct() {
63 parent::__construct();
64 $this->addDescription( <<<'TEXT'
65 This script cleans up the title fields in various tables to remove entries that
66 will be rejected by the constructor of TitleValue. This constructor throws an
67 exception when invalid data is encountered, which will not normally occur on
68 regular page views, but can happen on query special pages.
70 The script targets titles matching the regular expression /^_|[ \r\n\t]|_$/.
71 Because any foreign key relationships involving these titles will already be
72 broken, the titles are corrected to a valid version or the rows are deleted
73 entirely, depending on the table.
75 The script runs with the expectation that STDOUT is redirected to a file.
76 TEXT
78 $this->addOption( 'fix', 'Actually clean up invalid titles. If this parameter is ' .
79 'not specified, the script will report invalid titles but not clean them up.',
80 false, false );
81 $this->addOption( 'table', 'The table(s) to process. This option can be specified ' .
82 'more than once (e.g. -t category -t watchlist). If not specified, all available ' .
83 'tables will be processed. Available tables are: ' .
84 implode( ', ', array_column( static::$tables, 0 ) ), false, true, 't', true );
86 $this->setBatchSize( 500 );
89 public function execute() {
90 $tablesToProcess = $this->getOption( 'table' );
91 foreach ( static::$tables as $tableParams ) {
92 if ( !$tablesToProcess || in_array( $tableParams[0], $tablesToProcess ) ) {
93 $this->cleanupTable( $tableParams );
97 $this->outputStatus( 'Done!' );
98 if ( $this->hasOption( 'fix' ) ) {
99 $dbDomain = WikiMap::getCurrentWikiDbDomain()->getId();
100 $this->outputStatus( " Cleaned up invalid DB keys on $dbDomain!\n" );
105 * Prints text to STDOUT, and STDERR if STDOUT was redirected to a file.
106 * Used for progress reporting.
108 * @param string $str Text to write to both places
109 * @param string|null $channel Ignored
111 protected function outputStatus( $str, $channel = null ) {
112 // Make it easier to find progress lines in the STDOUT log
113 if ( trim( $str ) ) {
114 fwrite( STDOUT, '*** ' . trim( $str ) . "\n" );
116 fwrite( STDERR, $str );
120 * Prints text to STDOUT. Used for logging output.
122 * @param string $str Text to write
124 protected function writeToReport( $str ) {
125 fwrite( STDOUT, $str );
129 * Identifies, and optionally cleans up, invalid titles.
131 * @param array $tableParams A child array of self::$tables
133 protected function cleanupTable( $tableParams ) {
134 [ $table, $prefix ] = $tableParams;
135 $idField = $tableParams['idField'] ?? "{$prefix}_id";
136 $nsField = $tableParams['nsField'] ?? "{$prefix}_namespace";
137 $titleField = $tableParams['titleField'] ?? "{$prefix}_title";
139 $this->outputStatus( "Looking for invalid $titleField entries in $table...\n" );
141 // Do all the select queries on the replicas, as they are slow (they use
142 // unanchored LIKEs). Naturally this could cause problems if rows are
143 // modified after selecting and before deleting/updating, but working on
144 // the hypothesis that invalid rows will be old and in all likelihood
145 // unreferenced, we should be fine to do it like this.
146 $dbr = $this->getDB( DB_REPLICA, 'vslow' );
147 $linksMigration = $this->getServiceContainer()->getLinksMigration();
148 $joinConds = [];
149 $tables = [ $table ];
150 if ( isset( $linksMigration::$mapping[$table] ) ) {
151 [ $nsField, $titleField ] = $linksMigration->getTitleFields( $table );
152 $joinConds = $linksMigration->getQueryInfo( $table )['joins'];
153 $tables = $linksMigration->getQueryInfo( $table )['tables'];
156 // Find all TitleValue-invalid titles.
157 $percent = $dbr->anyString();
158 // The REGEXP operator is not cross-DBMS, so we have to use lots of LIKEs
159 $likeExpr = $dbr
160 ->expr( $titleField, IExpression::LIKE, new LikeValue( $percent, ' ', $percent ) )
161 ->or( $titleField, IExpression::LIKE, new LikeValue( $percent, "\r", $percent ) )
162 ->or( $titleField, IExpression::LIKE, new LikeValue( $percent, "\n", $percent ) )
163 ->or( $titleField, IExpression::LIKE, new LikeValue( $percent, "\t", $percent ) )
164 ->or( $titleField, IExpression::LIKE, new LikeValue( '_', $percent ) )
165 ->or( $titleField, IExpression::LIKE, new LikeValue( $percent, '_' ) );
166 $res = $dbr->newSelectQueryBuilder()
167 ->select( [
168 'id' => $idField,
169 'ns' => $nsField,
170 'title' => $titleField,
172 ->tables( $tables )
173 ->where( $likeExpr )
174 ->joinConds( $joinConds )
175 ->limit( $this->getBatchSize() )
176 ->caller( __METHOD__ )
177 ->fetchResultSet();
179 $this->outputStatus( "Number of invalid rows: " . $res->numRows() . "\n" );
180 if ( !$res->numRows() ) {
181 $this->outputStatus( "\n" );
182 return;
185 // Write a table of titles to the report file. Also keep a list of the found
186 // IDs, as we might need it later for DB updates
187 $this->writeToReport( sprintf( "%10s | ns | dbkey\n", $idField ) );
188 $ids = [];
189 foreach ( $res as $row ) {
190 $this->writeToReport( sprintf( "%10d | %3d | %s\n", $row->id, $row->ns, $row->title ) );
191 $ids[] = $row->id;
194 // If we're doing a dry run, output the new titles we would use for the UPDATE
195 // queries (if relevant), and finish
196 if ( !$this->hasOption( 'fix' ) ) {
197 if ( $table === 'logging' || $table === 'archive' ) {
198 $this->writeToReport( "The following updates would be run with the --fix flag:\n" );
199 foreach ( $res as $row ) {
200 $newTitle = self::makeValidTitle( $row->title );
201 $this->writeToReport(
202 "$idField={$row->id}: update '{$row->title}' to '$newTitle'\n" );
206 if ( $table !== 'page' && $table !== 'redirect' ) {
207 $this->outputStatus( "Run with --fix to clean up these rows\n" );
209 $this->outputStatus( "\n" );
210 return;
213 $services = $this->getServiceContainer();
215 // Fix the bad data, using different logic for the various tables
216 $dbw = $this->getPrimaryDB();
217 switch ( $table ) {
218 case 'page':
219 case 'redirect':
220 // This shouldn't happen on production wikis, and we already have a script
221 // to handle 'page' rows anyway, so just notify the user and let them decide
222 // what to do next.
223 $this->outputStatus( <<<TEXT
224 IMPORTANT: This script does not fix invalid entries in the $table table.
225 Consider repairing these rows, and rows in related tables, by hand.
226 You may like to run, or borrow logic from, the cleanupTitles.php script.
228 TEXT
230 break;
232 case 'archive':
233 case 'logging':
234 // Rename the title to a corrected equivalent. Any foreign key relationships
235 // to the page_title field are already broken, so this will just make sure
236 // users can still access the log entries/deleted revisions from the interface
237 // using a valid page title.
238 $this->outputStatus(
239 "Updating these rows, setting $titleField to the closest valid DB key...\n" );
240 $affectedRowCount = 0;
241 foreach ( $res as $row ) {
242 $newTitle = self::makeValidTitle( $row->title );
243 $this->writeToReport(
244 "$idField={$row->id}: updating '{$row->title}' to '$newTitle'\n" );
246 $dbw->newUpdateQueryBuilder()
247 ->update( $table )
248 ->set( [ $titleField => $newTitle ] )
249 ->where( [ $idField => $row->id ] )
250 ->caller( __METHOD__ )
251 ->execute();
252 $affectedRowCount += $dbw->affectedRows();
254 $this->waitForReplication();
255 $this->outputStatus( "Updated $affectedRowCount rows on $table.\n" );
257 break;
259 case 'recentchanges':
260 case 'watchlist':
261 case 'category':
262 // Since these broken titles can't exist, there's really nothing to watch,
263 // nothing can be categorised in them, and they can't have been changed
264 // recently, so we can just remove these rows.
265 $this->outputStatus( "Deleting invalid $table rows...\n" );
266 $dbw->newDeleteQueryBuilder()
267 ->deleteFrom( $table )
268 ->where( [ $idField => $ids ] )
269 ->caller( __METHOD__ )->execute();
270 $this->waitForReplication();
271 $this->outputStatus( 'Deleted ' . $dbw->affectedRows() . " rows from $table.\n" );
272 break;
274 case 'protected_titles':
275 // Since these broken titles can't exist, there's really nothing to protect,
276 // so we can just remove these rows. Made more complicated by this table
277 // not having an ID field
278 $this->outputStatus( "Deleting invalid $table rows...\n" );
279 $affectedRowCount = 0;
280 foreach ( $res as $row ) {
281 $dbw->newDeleteQueryBuilder()
282 ->deleteFrom( $table )
283 ->where( [ $nsField => $row->ns, $titleField => $row->title ] )
284 ->caller( __METHOD__ )->execute();
285 $affectedRowCount += $dbw->affectedRows();
287 $this->waitForReplication();
288 $this->outputStatus( "Deleted $affectedRowCount rows from $table.\n" );
289 break;
291 case 'pagelinks':
292 case 'templatelinks':
293 case 'categorylinks':
294 case 'imagelinks':
295 // Update links tables for each page where these bogus links are supposedly
296 // located. If the invalid rows don't go away after these jobs go through,
297 // they're probably being added by a buggy hook.
298 $this->outputStatus( "Queueing link update jobs for the pages in $idField...\n" );
299 $linksMigration = $this->getServiceContainer()->getLinksMigration();
300 $wikiPageFactory = $services->getWikiPageFactory();
301 foreach ( $res as $row ) {
302 $wp = $wikiPageFactory->newFromID( $row->id );
303 if ( $wp ) {
304 RefreshLinks::fixLinksFromArticle( $row->id );
305 } else {
306 if ( isset( $linksMigration::$mapping[$table] ) ) {
307 $conds = $linksMigration->getLinksConditions(
308 $table,
309 Title::makeTitle( $row->ns, $row->title )
311 } else {
312 $conds = [ $nsField => $row->ns, $titleField => $row->title ];
314 // This link entry points to a nonexistent page, so just get rid of it
315 $dbw->newDeleteQueryBuilder()
316 ->deleteFrom( $table )
317 ->where( array_merge( [ $idField => $row->id ], $conds ) )
318 ->caller( __METHOD__ )->execute();
321 $this->waitForReplication();
322 $this->outputStatus( "Link update jobs have been added to the job queue.\n" );
323 break;
326 $this->outputStatus( "\n" );
330 * Fix possible validation issues in the given title (DB key).
332 * @param string $invalidTitle
333 * @return string
335 protected static function makeValidTitle( $invalidTitle ) {
336 return strtr( trim( $invalidTitle, '_' ),
337 [ ' ' => '_', "\r" => '', "\n" => '', "\t" => '_' ] );
341 // @codeCoverageIgnoreStart
342 $maintClass = CleanupInvalidDbKeys::class;
343 require_once RUN_MAINTENANCE_IF_MAIN;
344 // @codeCoverageIgnoreEnd