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