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