Merge "Allow users to prevent new users from sending them email."
[lhc/web/wiklou.git] / maintenance / storage / checkStorage.php
1 <?php
2 /**
3 * Fsck for MediaWiki
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 ExternalStorage
22 */
23
24 use MediaWiki\MediaWikiServices;
25
26 if ( !defined( 'MEDIAWIKI' ) ) {
27 $optionsWithoutArgs = [ 'fix' ];
28 require_once __DIR__ . '/../commandLine.inc';
29
30 $cs = new CheckStorage;
31 $fix = isset( $options['fix'] );
32 if ( isset( $args[0] ) ) {
33 $xml = $args[0];
34 } else {
35 $xml = false;
36 }
37 $cs->check( $fix, $xml );
38 }
39
40 // ----------------------------------------------------------------------------------
41
42 /**
43 * Maintenance script to do various checks on external storage.
44 *
45 * @fixme this should extend the base Maintenance class
46 * @ingroup Maintenance ExternalStorage
47 */
48 class CheckStorage {
49 const CONCAT_HEADER = 'O:27:"concatenatedgziphistoryblob"';
50 public $oldIdMap, $errors;
51 public $dbStore = null;
52
53 public $errorDescriptions = [
54 'restore text' => 'Damaged text, need to be restored from a backup',
55 'restore revision' => 'Damaged revision row, need to be restored from a backup',
56 'unfixable' => 'Unexpected errors with no automated fixing method',
57 'fixed' => 'Errors already fixed',
58 'fixable' => 'Errors which would already be fixed if --fix was specified',
59 ];
60
61 function check( $fix = false, $xml = '' ) {
62 $dbr = wfGetDB( DB_REPLICA );
63 if ( $fix ) {
64 print "Checking, will fix errors if possible...\n";
65 } else {
66 print "Checking...\n";
67 }
68 $maxRevId = $dbr->selectField( 'revision', 'MAX(rev_id)', false, __METHOD__ );
69 $chunkSize = 1000;
70 $flagStats = [];
71 $objectStats = [];
72 $knownFlags = [ 'external', 'gzip', 'object', 'utf-8' ];
73 $this->errors = [
74 'restore text' => [],
75 'restore revision' => [],
76 'unfixable' => [],
77 'fixed' => [],
78 'fixable' => [],
79 ];
80
81 for ( $chunkStart = 1; $chunkStart < $maxRevId; $chunkStart += $chunkSize ) {
82 $chunkEnd = $chunkStart + $chunkSize - 1;
83 // print "$chunkStart of $maxRevId\n";
84
85 // Fetch revision rows
86 $this->oldIdMap = [];
87 $dbr->ping();
88 $res = $dbr->select( 'revision', [ 'rev_id', 'rev_text_id' ],
89 [ "rev_id BETWEEN $chunkStart AND $chunkEnd" ], __METHOD__ );
90 foreach ( $res as $row ) {
91 $this->oldIdMap[$row->rev_id] = $row->rev_text_id;
92 }
93 $dbr->freeResult( $res );
94
95 if ( !count( $this->oldIdMap ) ) {
96 continue;
97 }
98
99 // Fetch old_flags
100 $missingTextRows = array_flip( $this->oldIdMap );
101 $externalRevs = [];
102 $objectRevs = [];
103 $res = $dbr->select(
104 'text',
105 [ 'old_id', 'old_flags' ],
106 [ 'old_id' => $this->oldIdMap ],
107 __METHOD__
108 );
109 foreach ( $res as $row ) {
110 /**
111 * @var $flags int
112 */
113 $flags = $row->old_flags;
114 $id = $row->old_id;
115
116 // Create flagStats row if it doesn't exist
117 $flagStats = $flagStats + [ $flags => 0 ];
118 // Increment counter
119 $flagStats[$flags]++;
120
121 // Not missing
122 unset( $missingTextRows[$row->old_id] );
123
124 // Check for external or object
125 if ( $flags == '' ) {
126 $flagArray = [];
127 } else {
128 $flagArray = explode( ',', $flags );
129 }
130 if ( in_array( 'external', $flagArray ) ) {
131 $externalRevs[] = $id;
132 } elseif ( in_array( 'object', $flagArray ) ) {
133 $objectRevs[] = $id;
134 }
135
136 // Check for unrecognised flags
137 if ( $flags == '0' ) {
138 // This is a known bug from 2004
139 // It's safe to just erase the old_flags field
140 if ( $fix ) {
141 $this->addError( 'fixed', "Warning: old_flags set to 0", $id );
142 $dbw = wfGetDB( DB_MASTER );
143 $dbw->ping();
144 $dbw->update( 'text', [ 'old_flags' => '' ],
145 [ 'old_id' => $id ], __METHOD__ );
146 echo "Fixed\n";
147 } else {
148 $this->addError( 'fixable', "Warning: old_flags set to 0", $id );
149 }
150 } elseif ( count( array_diff( $flagArray, $knownFlags ) ) ) {
151 $this->addError( 'unfixable', "Error: invalid flags field \"$flags\"", $id );
152 }
153 }
154 $dbr->freeResult( $res );
155
156 // Output errors for any missing text rows
157 foreach ( $missingTextRows as $oldId => $revId ) {
158 $this->addError( 'restore revision', "Error: missing text row", $oldId );
159 }
160
161 // Verify external revisions
162 $externalConcatBlobs = [];
163 $externalNormalBlobs = [];
164 if ( count( $externalRevs ) ) {
165 $res = $dbr->select(
166 'text',
167 [ 'old_id', 'old_flags', 'old_text' ],
168 [ 'old_id' => $externalRevs ],
169 __METHOD__
170 );
171 foreach ( $res as $row ) {
172 $urlParts = explode( '://', $row->old_text, 2 );
173 if ( count( $urlParts ) !== 2 || $urlParts[1] == '' ) {
174 $this->addError( 'restore text', "Error: invalid URL \"{$row->old_text}\"", $row->old_id );
175 continue;
176 }
177 list( $proto, ) = $urlParts;
178 if ( $proto != 'DB' ) {
179 $this->addError(
180 'restore text',
181 "Error: invalid external protocol \"$proto\"",
182 $row->old_id );
183 continue;
184 }
185 $path = explode( '/', $row->old_text );
186 $cluster = $path[2];
187 $id = $path[3];
188 if ( isset( $path[4] ) ) {
189 $externalConcatBlobs[$cluster][$id][] = $row->old_id;
190 } else {
191 $externalNormalBlobs[$cluster][$id][] = $row->old_id;
192 }
193 }
194 $dbr->freeResult( $res );
195 }
196
197 // Check external concat blobs for the right header
198 $this->checkExternalConcatBlobs( $externalConcatBlobs );
199
200 // Check external normal blobs for existence
201 if ( count( $externalNormalBlobs ) ) {
202 if ( is_null( $this->dbStore ) ) {
203 $this->dbStore = new ExternalStoreDB;
204 }
205 foreach ( $externalConcatBlobs as $cluster => $xBlobIds ) {
206 $blobIds = array_keys( $xBlobIds );
207 $extDb =& $this->dbStore->getSlave( $cluster );
208 $blobsTable = $this->dbStore->getTable( $extDb );
209 $res = $extDb->select( $blobsTable,
210 [ 'blob_id' ],
211 [ 'blob_id IN( ' . implode( ',', $blobIds ) . ')' ], __METHOD__ );
212 foreach ( $res as $row ) {
213 unset( $xBlobIds[$row->blob_id] );
214 }
215 $extDb->freeResult( $res );
216 // Print errors for missing blobs rows
217 foreach ( $xBlobIds as $blobId => $oldId ) {
218 $this->addError(
219 'restore text',
220 "Error: missing target $blobId for one-part ES URL",
221 $oldId );
222 }
223 }
224 }
225
226 // Check local objects
227 $dbr->ping();
228 $concatBlobs = [];
229 $curIds = [];
230 if ( count( $objectRevs ) ) {
231 $headerLength = 300;
232 $res = $dbr->select(
233 'text',
234 [ 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ],
235 [ 'old_id' => $objectRevs ],
236 __METHOD__
237 );
238 foreach ( $res as $row ) {
239 $oldId = $row->old_id;
240 $matches = [];
241 if ( !preg_match( '/^O:(\d+):"(\w+)"/', $row->header, $matches ) ) {
242 $this->addError( 'restore text', "Error: invalid object header", $oldId );
243 continue;
244 }
245
246 $className = strtolower( $matches[2] );
247 if ( strlen( $className ) != $matches[1] ) {
248 $this->addError(
249 'restore text',
250 "Error: invalid object header, wrong class name length",
251 $oldId
252 );
253 continue;
254 }
255
256 $objectStats = $objectStats + [ $className => 0 ];
257 $objectStats[$className]++;
258
259 switch ( $className ) {
260 case 'concatenatedgziphistoryblob':
261 // Good
262 break;
263 case 'historyblobstub':
264 case 'historyblobcurstub':
265 if ( strlen( $row->header ) == $headerLength ) {
266 $this->addError( 'unfixable', "Error: overlong stub header", $oldId );
267 continue;
268 }
269 $stubObj = unserialize( $row->header );
270 if ( !is_object( $stubObj ) ) {
271 $this->addError( 'restore text', "Error: unable to unserialize stub object", $oldId );
272 continue;
273 }
274 if ( $className == 'historyblobstub' ) {
275 $concatBlobs[$stubObj->mOldId][] = $oldId;
276 } else {
277 $curIds[$stubObj->mCurId][] = $oldId;
278 }
279 break;
280 default:
281 $this->addError( 'unfixable', "Error: unrecognised object class \"$className\"", $oldId );
282 }
283 }
284 $dbr->freeResult( $res );
285 }
286
287 // Check local concat blob validity
288 $externalConcatBlobs = [];
289 if ( count( $concatBlobs ) ) {
290 $headerLength = 300;
291 $res = $dbr->select(
292 'text',
293 [ 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ],
294 [ 'old_id' => array_keys( $concatBlobs ) ],
295 __METHOD__
296 );
297 foreach ( $res as $row ) {
298 $flags = explode( ',', $row->old_flags );
299 if ( in_array( 'external', $flags ) ) {
300 // Concat blob is in external storage?
301 if ( in_array( 'object', $flags ) ) {
302 $urlParts = explode( '/', $row->header );
303 if ( $urlParts[0] != 'DB:' ) {
304 $this->addError(
305 'unfixable',
306 "Error: unrecognised external storage type \"{$urlParts[0]}",
307 $row->old_id
308 );
309 } else {
310 $cluster = $urlParts[2];
311 $id = $urlParts[3];
312 if ( !isset( $externalConcatBlobs[$cluster][$id] ) ) {
313 $externalConcatBlobs[$cluster][$id] = [];
314 }
315 $externalConcatBlobs[$cluster][$id] = array_merge(
316 $externalConcatBlobs[$cluster][$id], $concatBlobs[$row->old_id]
317 );
318 }
319 } else {
320 $this->addError(
321 'unfixable',
322 "Error: invalid flags \"{$row->old_flags}\" on concat bulk row {$row->old_id}",
323 $concatBlobs[$row->old_id] );
324 }
325 } elseif ( strcasecmp(
326 substr( $row->header, 0, strlen( self::CONCAT_HEADER ) ),
327 self::CONCAT_HEADER
328 ) ) {
329 $this->addError(
330 'restore text',
331 "Error: Incorrect object header for concat bulk row {$row->old_id}",
332 $concatBlobs[$row->old_id]
333 );
334 } # else good
335
336 unset( $concatBlobs[$row->old_id] );
337 }
338 $dbr->freeResult( $res );
339 }
340
341 // Check targets of unresolved stubs
342 $this->checkExternalConcatBlobs( $externalConcatBlobs );
343 // next chunk
344 }
345
346 print "\n\nErrors:\n";
347 foreach ( $this->errors as $name => $errors ) {
348 if ( count( $errors ) ) {
349 $description = $this->errorDescriptions[$name];
350 echo "$description: " . implode( ',', array_keys( $errors ) ) . "\n";
351 }
352 }
353
354 if ( count( $this->errors['restore text'] ) && $fix ) {
355 if ( (string)$xml !== '' ) {
356 $this->restoreText( array_keys( $this->errors['restore text'] ), $xml );
357 } else {
358 echo "Can't fix text, no XML backup specified\n";
359 }
360 }
361
362 print "\nFlag statistics:\n";
363 $total = array_sum( $flagStats );
364 foreach ( $flagStats as $flag => $count ) {
365 printf( "%-30s %10d %5.2f%%\n", $flag, $count, $count / $total * 100 );
366 }
367 print "\nLocal object statistics:\n";
368 $total = array_sum( $objectStats );
369 foreach ( $objectStats as $className => $count ) {
370 printf( "%-30s %10d %5.2f%%\n", $className, $count, $count / $total * 100 );
371 }
372 }
373
374 function addError( $type, $msg, $ids ) {
375 if ( is_array( $ids ) && count( $ids ) == 1 ) {
376 $ids = reset( $ids );
377 }
378 if ( is_array( $ids ) ) {
379 $revIds = [];
380 foreach ( $ids as $id ) {
381 $revIds = array_merge( $revIds, array_keys( $this->oldIdMap, $id ) );
382 }
383 print "$msg in text rows " . implode( ', ', $ids ) .
384 ", revisions " . implode( ', ', $revIds ) . "\n";
385 } else {
386 $id = $ids;
387 $revIds = array_keys( $this->oldIdMap, $id );
388 if ( count( $revIds ) == 1 ) {
389 print "$msg in old_id $id, rev_id {$revIds[0]}\n";
390 } else {
391 print "$msg in old_id $id, revisions " . implode( ', ', $revIds ) . "\n";
392 }
393 }
394 $this->errors[$type] = $this->errors[$type] + array_flip( $revIds );
395 }
396
397 function checkExternalConcatBlobs( $externalConcatBlobs ) {
398 if ( !count( $externalConcatBlobs ) ) {
399 return;
400 }
401
402 if ( is_null( $this->dbStore ) ) {
403 $this->dbStore = new ExternalStoreDB;
404 }
405
406 foreach ( $externalConcatBlobs as $cluster => $oldIds ) {
407 $blobIds = array_keys( $oldIds );
408 $extDb =& $this->dbStore->getSlave( $cluster );
409 $blobsTable = $this->dbStore->getTable( $extDb );
410 $headerLength = strlen( self::CONCAT_HEADER );
411 $res = $extDb->select( $blobsTable,
412 [ 'blob_id', "LEFT(blob_text, $headerLength) AS header" ],
413 [ 'blob_id IN( ' . implode( ',', $blobIds ) . ')' ], __METHOD__ );
414 foreach ( $res as $row ) {
415 if ( strcasecmp( $row->header, self::CONCAT_HEADER ) ) {
416 $this->addError(
417 'restore text',
418 "Error: invalid header on target $cluster/{$row->blob_id} of two-part ES URL",
419 $oldIds[$row->blob_id]
420 );
421 }
422 unset( $oldIds[$row->blob_id] );
423 }
424 $extDb->freeResult( $res );
425
426 // Print errors for missing blobs rows
427 foreach ( $oldIds as $blobId => $oldIds2 ) {
428 $this->addError(
429 'restore text',
430 "Error: missing target $cluster/$blobId for two-part ES URL",
431 $oldIds2
432 );
433 }
434 }
435 }
436
437 function restoreText( $revIds, $xml ) {
438 global $wgDBname;
439 $tmpDir = wfTempDir();
440
441 if ( !count( $revIds ) ) {
442 return;
443 }
444
445 print "Restoring text from XML backup...\n";
446
447 $revFileName = "$tmpDir/broken-revlist-$wgDBname";
448 $filteredXmlFileName = "$tmpDir/filtered-$wgDBname.xml";
449
450 // Write revision list
451 if ( !file_put_contents( $revFileName, implode( "\n", $revIds ) ) ) {
452 echo "Error writing revision list, can't restore text\n";
453
454 return;
455 }
456
457 // Run mwdumper
458 echo "Filtering XML dump...\n";
459 $exitStatus = 0;
460 passthru( 'mwdumper ' .
461 wfEscapeShellArg(
462 "--output=file:$filteredXmlFileName",
463 "--filter=revlist:$revFileName",
464 $xml
465 ), $exitStatus
466 );
467
468 if ( $exitStatus ) {
469 echo "mwdumper died with exit status $exitStatus\n";
470
471 return;
472 }
473
474 $file = fopen( $filteredXmlFileName, 'r' );
475 if ( !$file ) {
476 echo "Unable to open filtered XML file\n";
477
478 return;
479 }
480
481 $dbr = wfGetDB( DB_REPLICA );
482 $dbw = wfGetDB( DB_MASTER );
483 $dbr->ping();
484 $dbw->ping();
485
486 $source = new ImportStreamSource( $file );
487 $importer = new WikiImporter(
488 $source,
489 MediaWikiServices::getInstance()->getMainConfig()
490 );
491 $importer->setRevisionCallback( [ $this, 'importRevision' ] );
492 $importer->doImport();
493 }
494
495 function importRevision( &$revision, &$importer ) {
496 $id = $revision->getID();
497 $content = $revision->getContent( Revision::RAW );
498 $id = $id ? $id : '';
499
500 if ( $content === null ) {
501 echo "Revision $id is broken, we have no content available\n";
502
503 return;
504 }
505
506 $text = $content->serialize();
507 if ( $text === '' ) {
508 // This is what happens if the revision was broken at the time the
509 // dump was made. Unfortunately, it also happens if the revision was
510 // legitimately blank, so there's no way to tell the difference. To
511 // be safe, we'll skip it and leave it broken
512
513 echo "Revision $id is blank in the dump, may have been broken before export\n";
514
515 return;
516 }
517
518 if ( !$id ) {
519 // No ID, can't import
520 echo "No id tag in revision, can't import\n";
521
522 return;
523 }
524
525 // Find text row again
526 $dbr = wfGetDB( DB_REPLICA );
527 $oldId = $dbr->selectField( 'revision', 'rev_text_id', [ 'rev_id' => $id ], __METHOD__ );
528 if ( !$oldId ) {
529 echo "Missing revision row for rev_id $id\n";
530
531 return;
532 }
533
534 // Compress the text
535 $flags = Revision::compressRevisionText( $text );
536
537 // Update the text row
538 $dbw = wfGetDB( DB_MASTER );
539 $dbw->update( 'text',
540 [ 'old_flags' => $flags, 'old_text' => $text ],
541 [ 'old_id' => $oldId ],
542 __METHOD__, [ 'LIMIT' => 1 ]
543 );
544
545 // Remove it from the unfixed list and add it to the fixed list
546 unset( $this->errors['restore text'][$id] );
547 $this->errors['fixed'][$id] = true;
548 }
549 }