MediaWiki master
cleanupInvalidDbKeys.php
Go to the documentation of this file.
1<?php
10// @codeCoverageIgnoreStart
11require_once __DIR__ . '/Maintenance.php';
12// @codeCoverageIgnoreEnd
13
23
32 protected static $tables = [
33 // Data tables
34 [ 'page', 'page' ],
35 [ 'redirect', 'rd', 'idField' => 'rd_from' ],
36 [ 'archive', 'ar' ],
37 [ 'logging', 'log' ],
38 [ 'protected_titles', 'pt', 'idField' => 0 ],
39 [ 'category', 'cat', 'nsField' => 14 ],
40 [ 'recentchanges', 'rc' ],
41 [ 'watchlist', 'wl' ],
42 // The querycache tables' qc(c)_title and qcc_titletwo may contain titles,
43 // but also usernames or other things like that, so we leave them alone
44
45 // Links tables
46 [ 'pagelinks', 'pl', 'idField' => 'pl_from', 'virtualDomain' => PageLinksTable::VIRTUAL_DOMAIN ],
47 [ 'templatelinks', 'tl', 'idField' => 'tl_from', 'virtualDomain' => TemplateLinksTable::VIRTUAL_DOMAIN ],
48 [ 'categorylinks', 'cl', 'idField' => 'cl_from', 'virtualDomain' => CategoryLinksTable::VIRTUAL_DOMAIN ],
49 [ 'imagelinks', 'il', 'idField' => 'il_from', 'nsField' => 6, 'titleField' => 'il_to',
50 'virtualDomain' => ImageLinksTable::VIRTUAL_DOMAIN ],
51 ];
52
53 public function __construct() {
54 parent::__construct();
55 $this->addDescription( <<<'TEXT'
56This script cleans up the title fields in various tables to remove entries that
57will be rejected by the constructor of TitleValue. This constructor throws an
58exception when invalid data is encountered, which will not normally occur on
59regular page views, but can happen on query special pages.
60
61The script targets titles matching the regular expression /^_|[ \r\n\t]|_$/.
62Because any foreign key relationships involving these titles will already be
63broken, the titles are corrected to a valid version or the rows are deleted
64entirely, depending on the table.
65
66The script runs with the expectation that STDOUT is redirected to a file.
67TEXT
68 );
69 $this->addOption( 'fix', 'Actually clean up invalid titles. If this parameter is ' .
70 'not specified, the script will report invalid titles but not clean them up.',
71 false, false );
72 $this->addOption( 'table', 'The table(s) to process. This option can be specified ' .
73 'more than once (e.g. -t category -t watchlist). If not specified, all available ' .
74 'tables will be processed. Available tables are: ' .
75 implode( ', ', array_column( static::$tables, 0 ) ), false, true, 't', true );
76
77 $this->setBatchSize( 500 );
78 }
79
80 public function execute() {
81 $tablesToProcess = $this->getOption( 'table' );
82 foreach ( static::$tables as $tableParams ) {
83 if ( !$tablesToProcess || in_array( $tableParams[0], $tablesToProcess ) ) {
84 $this->cleanupTable( $tableParams );
85 }
86 }
87
88 $this->outputStatus( 'Done!' );
89 if ( $this->hasOption( 'fix' ) ) {
90 $dbDomain = WikiMap::getCurrentWikiDbDomain()->getId();
91 $this->outputStatus( " Cleaned up invalid DB keys on $dbDomain!\n" );
92 }
93 }
94
102 protected function outputStatus( $str, $channel = null ) {
103 // Make it easier to find progress lines in the STDOUT log
104 if ( trim( $str ) ) {
105 fwrite( STDOUT, '*** ' . trim( $str ) . "\n" );
106 }
107 fwrite( STDERR, $str );
108 }
109
115 protected function writeToReport( $str ) {
116 fwrite( STDOUT, $str );
117 }
118
124 protected function cleanupTable( $tableParams ) {
125 [ $table, $prefix ] = $tableParams;
126 $idField = $tableParams['idField'] ?? "{$prefix}_id";
127 $nsField = $tableParams['nsField'] ?? "{$prefix}_namespace";
128 $titleField = $tableParams['titleField'] ?? "{$prefix}_title";
129
130 $this->outputStatus( "Looking for invalid $titleField entries in $table...\n" );
131
132 // Do all the select queries on the replicas, as they are slow (they use
133 // unanchored LIKEs). Naturally this could cause problems if rows are
134 // modified after selecting and before deleting/updating, but working on
135 // the hypothesis that invalid rows will be old and in all likelihood
136 // unreferenced, we should be fine to do it like this.
137 if ( isset( $tableParams['virtualDomain'] ) ) {
138 $dbr = $this->getServiceContainer()->getConnectionProvider()->getReplicaDatabase(
139 $tableParams['virtualDomain'],
140 'vslow'
141 );
142 } else {
143 $dbr = $this->getDB( DB_REPLICA, 'vslow' );
144 }
145
146 $linksMigration = $this->getServiceContainer()->getLinksMigration();
147 $joinConds = [];
148 $tables = [ $table ];
149 if ( isset( $linksMigration::$mapping[$table] ) ) {
150 [ $nsField, $titleField ] = $linksMigration->getTitleFields( $table );
151 $joinConds = $linksMigration->getQueryInfo( $table )['joins'];
152 $tables = $linksMigration->getQueryInfo( $table )['tables'];
153 }
154
155 // Find all TitleValue-invalid titles.
156 $percent = $dbr->anyString();
157 // The REGEXP operator is not cross-DBMS, so we have to use lots of LIKEs
158 $likeExpr = $dbr
159 ->expr( $titleField, IExpression::LIKE, new LikeValue( $percent, ' ', $percent ) )
160 ->or( $titleField, IExpression::LIKE, new LikeValue( $percent, "\r", $percent ) )
161 ->or( $titleField, IExpression::LIKE, new LikeValue( $percent, "\n", $percent ) )
162 ->or( $titleField, IExpression::LIKE, new LikeValue( $percent, "\t", $percent ) )
163 ->or( $titleField, IExpression::LIKE, new LikeValue( '_', $percent ) )
164 ->or( $titleField, IExpression::LIKE, new LikeValue( $percent, '_' ) );
165 $res = $dbr->newSelectQueryBuilder()
166 ->select( [
167 'id' => $idField,
168 'ns' => $nsField,
169 'title' => $titleField,
170 ] )
171 ->tables( $tables )
172 ->where( $likeExpr )
173 ->joinConds( $joinConds )
174 ->limit( $this->getBatchSize() )
175 ->caller( __METHOD__ )
176 ->fetchResultSet();
177
178 $this->outputStatus( "Number of invalid rows: " . $res->numRows() . "\n" );
179 if ( !$res->numRows() ) {
180 $this->outputStatus( "\n" );
181 return;
182 }
183
184 // Write a table of titles to the report file. Also keep a list of the found
185 // IDs, as we might need it later for DB updates
186 $this->writeToReport( sprintf( "%10s | ns | dbkey\n", $idField ) );
187 $ids = [];
188 foreach ( $res as $row ) {
189 $this->writeToReport( sprintf( "%10d | %3d | %s\n", $row->id, $row->ns, $row->title ) );
190 $ids[] = $row->id;
191 }
192
193 // If we're doing a dry run, output the new titles we would use for the UPDATE
194 // queries (if relevant), and finish
195 if ( !$this->hasOption( 'fix' ) ) {
196 if ( $table === 'logging' || $table === 'archive' ) {
197 $this->writeToReport( "The following updates would be run with the --fix flag:\n" );
198 foreach ( $res as $row ) {
199 $newTitle = self::makeValidTitle( $row->title );
200 $this->writeToReport(
201 "$idField={$row->id}: update '{$row->title}' to '$newTitle'\n" );
202 }
203 }
204
205 if ( $table !== 'page' && $table !== 'redirect' ) {
206 $this->outputStatus( "Run with --fix to clean up these rows\n" );
207 }
208 $this->outputStatus( "\n" );
209 return;
210 }
211
212 $services = $this->getServiceContainer();
213
214 // Fix the bad data, using different logic for the various tables
215 if ( isset( $tableParams['virtualDomain'] ) ) {
216 $dbw = $this->getServiceContainer()->getConnectionProvider()->getPrimaryDatabase(
217 $tableParams['virtualDomain']
218 );
219 } else {
220 $dbw = $this->getPrimaryDB();
221 }
222
223 switch ( $table ) {
224 case 'page':
225 case 'redirect':
226 // This shouldn't happen on production wikis, and we already have a script
227 // to handle 'page' rows anyway, so just notify the user and let them decide
228 // what to do next.
229 $this->outputStatus( <<<TEXT
230IMPORTANT: This script does not fix invalid entries in the $table table.
231Consider repairing these rows, and rows in related tables, by hand.
232You may like to run, or borrow logic from, the cleanupTitles.php script.
233
234TEXT
235 );
236 break;
237
238 case 'archive':
239 case 'logging':
240 // Rename the title to a corrected equivalent. Any foreign key relationships
241 // to the page_title field are already broken, so this will just make sure
242 // users can still access the log entries/deleted revisions from the interface
243 // using a valid page title.
244 $this->outputStatus(
245 "Updating these rows, setting $titleField to the closest valid DB key...\n" );
246 $affectedRowCount = 0;
247 foreach ( $res as $row ) {
248 $newTitle = self::makeValidTitle( $row->title );
249 $this->writeToReport(
250 "$idField={$row->id}: updating '{$row->title}' to '$newTitle'\n" );
251
252 $dbw->newUpdateQueryBuilder()
253 ->update( $table )
254 ->set( [ $titleField => $newTitle ] )
255 ->where( [ $idField => $row->id ] )
256 ->caller( __METHOD__ )
257 ->execute();
258 $affectedRowCount += $dbw->affectedRows();
259 }
260 $this->waitForReplication();
261 $this->outputStatus( "Updated $affectedRowCount rows on $table.\n" );
262
263 break;
264
265 case 'recentchanges':
266 case 'watchlist':
267 case 'category':
268 // Since these broken titles can't exist, there's really nothing to watch,
269 // nothing can be categorised in them, and they can't have been changed
270 // recently, so we can just remove these rows.
271 $this->outputStatus( "Deleting invalid $table rows...\n" );
272 $dbw->newDeleteQueryBuilder()
273 ->deleteFrom( $table )
274 ->where( [ $idField => $ids ] )
275 ->caller( __METHOD__ )->execute();
276 $this->waitForReplication();
277 $this->outputStatus( 'Deleted ' . $dbw->affectedRows() . " rows from $table.\n" );
278 break;
279
280 case 'protected_titles':
281 // Since these broken titles can't exist, there's really nothing to protect,
282 // so we can just remove these rows. Made more complicated by this table
283 // not having an ID field
284 $this->outputStatus( "Deleting invalid $table rows...\n" );
285 $affectedRowCount = 0;
286 foreach ( $res as $row ) {
287 $dbw->newDeleteQueryBuilder()
288 ->deleteFrom( $table )
289 ->where( [ $nsField => $row->ns, $titleField => $row->title ] )
290 ->caller( __METHOD__ )->execute();
291 $affectedRowCount += $dbw->affectedRows();
292 }
293 $this->waitForReplication();
294 $this->outputStatus( "Deleted $affectedRowCount rows from $table.\n" );
295 break;
296
297 case 'pagelinks':
298 case 'templatelinks':
299 case 'categorylinks':
300 case 'imagelinks':
301 // Update links tables for each page where these bogus links are supposedly
302 // located. If the invalid rows don't go away after these jobs go through,
303 // they're probably being added by a buggy hook.
304 $this->outputStatus( "Queueing link update jobs for the pages in $idField...\n" );
305 $linksMigration = $this->getServiceContainer()->getLinksMigration();
306 $wikiPageFactory = $services->getWikiPageFactory();
307 foreach ( $res as $row ) {
308 $wp = $wikiPageFactory->newFromID( $row->id );
309 if ( $wp ) {
310 RefreshLinks::fixLinksFromArticle( $row->id );
311 } else {
312 if ( isset( $linksMigration::$mapping[$table] ) ) {
313 $conds = $linksMigration->getLinksConditions(
314 $table,
315 Title::makeTitle( $row->ns, $row->title )
316 );
317 } else {
318 $conds = [ $nsField => $row->ns, $titleField => $row->title ];
319 }
320 // This link entry points to a nonexistent page, so just get rid of it
321 $dbw->newDeleteQueryBuilder()
322 ->deleteFrom( $table )
323 ->where( array_merge( [ $idField => $row->id ], $conds ) )
324 ->caller( __METHOD__ )->execute();
325 }
326 }
327 $this->waitForReplication();
328 $this->outputStatus( "Link update jobs have been added to the job queue.\n" );
329 break;
330 }
331
332 $this->outputStatus( "\n" );
333 }
334
341 protected static function makeValidTitle( $invalidTitle ) {
342 return strtr( trim( $invalidTitle, '_' ),
343 [ ' ' => '_', "\r" => '', "\n" => '', "\t" => '_' ] );
344 }
345}
346
347// @codeCoverageIgnoreStart
348$maintClass = CleanupInvalidDbKeys::class;
349require_once RUN_MAINTENANCE_IF_MAIN;
350// @codeCoverageIgnoreEnd
const DB_REPLICA
Definition defines.php:26
Maintenance script that cleans up invalid titles in various tables.
static makeValidTitle( $invalidTitle)
Fix possible validation issues in the given title (DB key).
static array[] $tables
List of tables to clean up, and the field prefix for that table.
cleanupTable( $tableParams)
Identifies, and optionally cleans up, invalid titles.
outputStatus( $str, $channel=null)
Prints text to STDOUT, and STDERR if STDOUT was redirected to a file.
writeToReport( $str)
Prints text to STDOUT.
__construct()
Default constructor.
execute()
Do the actual work.
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
getBatchSize()
Returns batch size.
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
getDB( $db, $groups=[], $dbDomain=false)
Returns a database to be used by current maintenance script.
waitForReplication()
Wait for replica DB servers to catch up.
hasOption( $name)
Checks to see if a particular option was set.
getOption( $name, $default=null)
Get an option, or return the default.
getServiceContainer()
Returns the main service container.
getPrimaryDB(string|false $virtualDomain=false)
addDescription( $text)
Set the description text.
Represents a title within MediaWiki.
Definition Title.php:69
Tools for dealing with other locally-hosted wikis.
Definition WikiMap.php:19
Content of like value.
Definition LikeValue.php:14