Revised styling of sister-search sidebar.
[lhc/web/wiklou.git] / maintenance / cleanupInvalidDbKeys.php
1 <?php
2 /**
3 * Cleans up invalid titles in various tables.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Maintenance
22 */
23
24 require_once __DIR__ . '/Maintenance.php';
25
26 /**
27 * Maintenance script that cleans up invalid titles in various tables.
28 *
29 * @since 1.29
30 * @ingroup Maintenance
31 */
32 class CleanupInvalidDbKeys extends Maintenance {
33 /** @var array List of tables to clean up, and the field prefix for that table */
34 protected static $tables = [
35 // Data tables
36 [ 'page', 'page' ],
37 [ 'redirect', 'rd', 'idField' => 'rd_from' ],
38 [ 'archive', 'ar' ],
39 [ 'logging', 'log' ],
40 [ 'protected_titles', 'pt', 'idField' => 0 ],
41 [ 'category', 'cat', 'nsField' => 14 ],
42 [ 'recentchanges', 'rc' ],
43 [ 'watchlist', 'wl' ],
44 // The querycache tables' qc(c)_title and qcc_titletwo may contain titles,
45 // but also usernames or other things like that, so we leave them alone
46
47 // Links tables
48 [ 'pagelinks', 'pl', 'idField' => 'pl_from' ],
49 [ 'templatelinks', 'tl', 'idField' => 'tl_from' ],
50 [ 'categorylinks', 'cl', 'idField' => 'cl_from', 'nsField' => 14, 'titleField' => 'cl_to' ],
51 ];
52
53 public function __construct() {
54 parent::__construct();
55 $this->addDescription( <<<'TEXT'
56 This script cleans up the title fields in various tables to remove entries that
57 will be rejected by the constructor of TitleValue. This constructor throws an
58 exception when invalid data is encountered, which will not normally occur on
59 regular page views, but can happen on query special pages.
60
61 The script targets titles matching the regular expression /^_|[ \r\n\t]|_$/.
62 Because any foreign key relationships involving these titles will already be
63 broken, the titles are corrected to a valid version or the rows are deleted
64 entirely, depending on the table.
65
66 Key progress output is printed to STDERR, while a full log of all entries that
67 are deleted is sent to STDOUT. You are strongly advised to capture STDOUT into
68 a file.
69 TEXT
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->output( 'Done! Cleaned up invalid DB keys on ' . wfWikiID() . "!\n" );
91 }
92
93 /**
94 * Prints text to STDOUT, and STDERR if STDOUT was redirected to a file.
95 * Used for progress reporting.
96 *
97 * @param string $str Text to write to both places
98 * @param string|null $channel Ignored
99 */
100 protected function output( $str, $channel = null ) {
101 // Make it easier to find progress lines in the STDOUT log
102 if ( trim( $str ) ) {
103 fwrite( STDOUT, '*** ' );
104 }
105 fwrite( STDERR, $str );
106 }
107
108 /**
109 * Prints text to STDOUT. Used for logging output.
110 *
111 * @param string $str Text to write
112 */
113 protected function writeToReport( $str ) {
114 fwrite( STDOUT, $str );
115 }
116
117 /**
118 * Identifies, and optionally cleans up, invalid titles.
119 *
120 * @param array $tableParams A child array of self::$tables
121 */
122 protected function cleanupTable( $tableParams ) {
123 $table = $tableParams[0];
124 $prefix = $tableParams[1];
125 $idField = isset( $tableParams['idField'] ) ?
126 $tableParams['idField'] :
127 "{$prefix}_id";
128 $nsField = isset( $tableParams['nsField'] ) ?
129 $tableParams['nsField'] :
130 "{$prefix}_namespace";
131 $titleField = isset( $tableParams['titleField'] ) ?
132 $tableParams['titleField'] :
133 "{$prefix}_title";
134
135 $this->output( "Looking for invalid $titleField entries in $table...\n" );
136
137 // Do all the select queries on the replicas, as they are slow (they use
138 // unanchored LIKEs). Naturally this could cause problems if rows are
139 // modified after selecting and before deleting/updating, but working on
140 // the hypothesis that invalid rows will be old and in all likelihood
141 // unreferenced, we should be fine to do it like this.
142 $dbr = $this->getDB( DB_REPLICA, 'vslow' );
143
144 // Find all TitleValue-invalid titles.
145 $percent = $dbr->anyString(); // DBMS-agnostic equivalent of '%' LIKE wildcard
146 $res = $dbr->select(
147 $table,
148 [
149 'id' => $idField,
150 'ns' => $nsField,
151 'title' => $titleField,
152 ],
153 // The REGEXP operator is not cross-DBMS, so we have to use lots of LIKEs
154 [ $dbr->makeList( [
155 $titleField . $dbr->buildLike( $percent, ' ', $percent ),
156 $titleField . $dbr->buildLike( $percent, '\r', $percent ),
157 $titleField . $dbr->buildLike( $percent, '\n', $percent ),
158 $titleField . $dbr->buildLike( $percent, '\t', $percent ),
159 $titleField . $dbr->buildLike( '_', $percent ),
160 $titleField . $dbr->buildLike( $percent, '_' ),
161 ], LIST_OR ) ],
162 __METHOD__,
163 [ 'LIMIT' => $this->mBatchSize ]
164 );
165
166 $this->output( "Number of invalid rows: " . $res->numRows() . "\n" );
167 if ( !$res->numRows() ) {
168 $this->output( "\n" );
169 return;
170 }
171
172 // Write a table of titles to the report file. Also keep a list of the found
173 // IDs, as we might need it later for DB updates
174 $this->writeToReport( sprintf( "%10s | ns | dbkey\n", $idField ) );
175 $ids = [];
176 foreach ( $res as $row ) {
177 $this->writeToReport( sprintf( "%10d | %3d | %s\n", $row->id, $row->ns, $row->title ) );
178 $ids[] = $row->id;
179 }
180
181 // If we're doing a dry run, output the new titles we would use for the UPDATE
182 // queries (if relevant), and finish
183 if ( !$this->hasOption( 'fix' ) ) {
184 if ( $table === 'logging' || $table === 'archive' ) {
185 $this->writeToReport( "The following updates would be run with the --fix flag:\n" );
186 foreach ( $res as $row ) {
187 $newTitle = self::makeValidTitle( $row->title );
188 $this->writeToReport(
189 "$idField={$row->id}: update '{$row->title}' to '$newTitle'\n" );
190 }
191 }
192
193 if ( $table !== 'page' && $table !== 'redirect' ) {
194 $this->output( "Run with --fix to clean up these rows\n" );
195 }
196 $this->output( "\n" );
197 return;
198 }
199
200 // Fix the bad data, using different logic for the various tables
201 $dbw = $this->getDB( DB_MASTER );
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->output( <<<TEXT
209 IMPORTANT: This script does not fix invalid entries in the $table table.
210 Consider repairing these rows, and rows in related tables, by hand.
211 You may like to run, or borrow logic from, the cleanupTitles.php script.
212
213 TEXT
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->output(
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 wfWaitForSlaves();
238 $this->output( "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->output( "Deleting invalid $table rows...\n" );
249 $dbw->delete( $table, [ $idField => $ids ], __METHOD__ );
250 wfWaitForSlaves();
251 $this->output( '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->output( "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 wfWaitForSlaves();
267 $this->output( "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->output( "Queueing link update jobs for the pages in $idField...\n" );
277 foreach ( $res as $row ) {
278 $wp = WikiPage::newFromID( $row->id );
279 if ( $wp ) {
280 RefreshLinks::fixLinksFromArticle( $row->id );
281 } else {
282 // This link entry points to a nonexistent page, so just get rid of it
283 $dbw->delete( $table,
284 [ $idField => $row->id, $nsField => $row->ns, $titleField => $row->title ],
285 __METHOD__ );
286 }
287 }
288 wfWaitForSlaves();
289 $this->output( "Link update jobs have been added to the job queue.\n" );
290 break;
291 }
292
293 $this->output( "\n" );
294 return;
295 }
296
297 /**
298 * Fix possible validation issues in the given title (DB key).
299 *
300 * @param string $invalidTitle
301 * @return string
302 */
303 protected static function makeValidTitle( $invalidTitle ) {
304 return strtr( trim( $invalidTitle, '_' ),
305 [ ' ' => '_', "\r" => '', "\n" => '', "\t" => '_' ] );
306 }
307 }
308
309 $maintClass = 'CleanupInvalidDbKeys';
310 require_once RUN_MAINTENANCE_IF_MAIN;