MediaWiki REL1_37
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
141 // Find all TitleValue-invalid titles.
142 $percent = $dbr->anyString();
143 $res = $dbr->select(
144 $table,
145 [
146 'id' => $idField,
147 'ns' => $nsField,
148 'title' => $titleField,
149 ],
150 // The REGEXP operator is not cross-DBMS, so we have to use lots of LIKEs
151 [ $dbr->makeList( [
152 $titleField . $dbr->buildLike( $percent, ' ', $percent ),
153 $titleField . $dbr->buildLike( $percent, "\r", $percent ),
154 $titleField . $dbr->buildLike( $percent, "\n", $percent ),
155 $titleField . $dbr->buildLike( $percent, "\t", $percent ),
156 $titleField . $dbr->buildLike( '_', $percent ),
157 $titleField . $dbr->buildLike( $percent, '_' ),
158 ], LIST_OR ) ],
159 __METHOD__,
160 [ 'LIMIT' => $this->getBatchSize() ]
161 );
162
163 $this->outputStatus( "Number of invalid rows: " . $res->numRows() . "\n" );
164 if ( !$res->numRows() ) {
165 $this->outputStatus( "\n" );
166 return;
167 }
168
169 // Write a table of titles to the report file. Also keep a list of the found
170 // IDs, as we might need it later for DB updates
171 $this->writeToReport( sprintf( "%10s | ns | dbkey\n", $idField ) );
172 $ids = [];
173 foreach ( $res as $row ) {
174 $this->writeToReport( sprintf( "%10d | %3d | %s\n", $row->id, $row->ns, $row->title ) );
175 $ids[] = $row->id;
176 }
177
178 // If we're doing a dry run, output the new titles we would use for the UPDATE
179 // queries (if relevant), and finish
180 if ( !$this->hasOption( 'fix' ) ) {
181 if ( $table === 'logging' || $table === 'archive' ) {
182 $this->writeToReport( "The following updates would be run with the --fix flag:\n" );
183 foreach ( $res as $row ) {
184 $newTitle = self::makeValidTitle( $row->title );
185 $this->writeToReport(
186 "$idField={$row->id}: update '{$row->title}' to '$newTitle'\n" );
187 }
188 }
189
190 if ( $table !== 'page' && $table !== 'redirect' ) {
191 $this->outputStatus( "Run with --fix to clean up these rows\n" );
192 }
193 $this->outputStatus( "\n" );
194 return;
195 }
196
197 $services = MediaWikiServices::getInstance();
198 $lbFactory = $services->getDBLoadBalancerFactory();
199
200 // Fix the bad data, using different logic for the various tables
201 $dbw = $this->getDB( DB_PRIMARY );
202 switch ( $table ) {
203 case 'page':
204 case 'redirect':
205 // This shouldn't happen on production wikis, and we already have a script
206 // to handle 'page' rows anyway, so just notify the user and let them decide
207 // what to do next.
208 $this->outputStatus( <<<TEXT
209IMPORTANT: This script does not fix invalid entries in the $table table.
210Consider repairing these rows, and rows in related tables, by hand.
211You may like to run, or borrow logic from, the cleanupTitles.php script.
212
213TEXT
214 );
215 break;
216
217 case 'archive':
218 case 'logging':
219 // Rename the title to a corrected equivalent. Any foreign key relationships
220 // to the page_title field are already broken, so this will just make sure
221 // users can still access the log entries/deleted revisions from the interface
222 // using a valid page title.
223 $this->outputStatus(
224 "Updating these rows, setting $titleField to the closest valid DB key...\n" );
225 $affectedRowCount = 0;
226 foreach ( $res as $row ) {
227 $newTitle = self::makeValidTitle( $row->title );
228 $this->writeToReport(
229 "$idField={$row->id}: updating '{$row->title}' to '$newTitle'\n" );
230
231 $dbw->update( $table,
232 [ $titleField => $newTitle ],
233 [ $idField => $row->id ],
234 __METHOD__ );
235 $affectedRowCount += $dbw->affectedRows();
236 }
237 $lbFactory->waitForReplication();
238 $this->outputStatus( "Updated $affectedRowCount rows on $table.\n" );
239
240 break;
241
242 case 'recentchanges':
243 case 'watchlist':
244 case 'category':
245 // Since these broken titles can't exist, there's really nothing to watch,
246 // nothing can be categorised in them, and they can't have been changed
247 // recently, so we can just remove these rows.
248 $this->outputStatus( "Deleting invalid $table rows...\n" );
249 $dbw->delete( $table, [ $idField => $ids ], __METHOD__ );
250 $lbFactory->waitForReplication();
251 $this->outputStatus( 'Deleted ' . $dbw->affectedRows() . " rows from $table.\n" );
252 break;
253
254 case 'protected_titles':
255 // Since these broken titles can't exist, there's really nothing to protect,
256 // so we can just remove these rows. Made more complicated by this table
257 // not having an ID field
258 $this->outputStatus( "Deleting invalid $table rows...\n" );
259 $affectedRowCount = 0;
260 foreach ( $res as $row ) {
261 $dbw->delete( $table,
262 [ $nsField => $row->ns, $titleField => $row->title ],
263 __METHOD__ );
264 $affectedRowCount += $dbw->affectedRows();
265 }
266 $lbFactory->waitForReplication();
267 $this->outputStatus( "Deleted $affectedRowCount rows from $table.\n" );
268 break;
269
270 case 'pagelinks':
271 case 'templatelinks':
272 case 'categorylinks':
273 // Update links tables for each page where these bogus links are supposedly
274 // located. If the invalid rows don't go away after these jobs go through,
275 // they're probably being added by a buggy hook.
276 $this->outputStatus( "Queueing link update jobs for the pages in $idField...\n" );
277 $wikiPageFactory = $services->getWikiPageFactory();
278 foreach ( $res as $row ) {
279 $wp = $wikiPageFactory->newFromID( $row->id );
280 if ( $wp ) {
281 RefreshLinks::fixLinksFromArticle( $row->id );
282 } else {
283 // This link entry points to a nonexistent page, so just get rid of it
284 $dbw->delete( $table,
285 [ $idField => $row->id, $nsField => $row->ns, $titleField => $row->title ],
286 __METHOD__ );
287 }
288 }
289 $lbFactory->waitForReplication();
290 $this->outputStatus( "Link update jobs have been added to the job queue.\n" );
291 break;
292 }
293
294 $this->outputStatus( "\n" );
295 }
296
303 protected static function makeValidTitle( $invalidTitle ) {
304 return strtr( trim( $invalidTitle, '_' ),
305 [ ' ' => '_', "\r" => '', "\n" => '', "\t" => '_' ] );
306 }
307}
308
309$maintClass = CleanupInvalidDbKeys::class;
310require_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.
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)
MediaWikiServices is the service locator for the application scope of MediaWiki.
Represents a page (or page fragment) title within MediaWiki.
const DB_REPLICA
Definition defines.php:25
const DB_PRIMARY
Definition defines.php:27