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