-
Notifications
You must be signed in to change notification settings - Fork 6
/
importDump.php
375 lines (332 loc) · 11.8 KB
/
importDump.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
<?php
/**
* Maintenance script to import revisions from a XML dump with page, revision,
* and user IDs preserved.
*
* This script is adapted from the core importDump.php maintenance script,
* but used a customized WikiImporter. The goal is to make the core importer
* more flexible to use, and eventually drop our customized importer.
*
* For the source of XML dumps, dumps generated by the recent versions of
* wikiteam3 are recommended, which should be very close to the standard
* XML dump schema. Dumps by old wikiteam2 are not supported for now, since
* their format is very broken and lacks lots of fields.
*
* @file
* @ingroup Maintenance
*/
use MediaWiki\MediaWikiServices;
use MediaWiki\Page\PageIdentityValue;
use MediaWiki\Settings\SettingsBuilder;
require_once 'includes/TextGrabber.php';
require_once 'includes/WikiImportHandler.php';
class ImportDump extends TextGrabber {
/** @var int */
public $reportingInterval = 100;
/** @var int */
public $pageCount = 0;
/** @var int */
public $revCount = 0;
/** @var bool */
public $dryRun = false;
/** @var array|false */
public $nsFilter = false;
/** @var resource|false */
public $stderr;
/** @var float */
protected $startTime;
protected $skipToRevId = null;
public function __construct() {
parent::__construct();
$gz = in_array( 'compress.zlib', stream_get_wrappers() )
? 'ok'
: '(disabled; requires PHP zlib module)';
$bz2 = in_array( 'compress.bzip2', stream_get_wrappers() )
? 'ok'
: '(disabled; requires PHP bzip2 module)';
$this->addDescription(
<<<TEXT
This script reads pages from an XML file as produced from Special:Export or
dumpBackup.php, and saves them into the current wiki.
Compressed XML files may be read directly:
.gz $gz
.bz2 $bz2
.7z (if 7za executable is in PATH)
Note that for very large data sets, importDump.php may be slow; there are
alternate methods which can be much faster for full site restoration:
<https://www.mediawiki.org/wiki/Manual:Importing_XML_dumps>
TEXT
);
$this->stderr = fopen( "php://stderr", "wt" );
$this->addOption( 'report',
'Report position and speed after every n pages processed', false, true );
$this->addOption( 'namespaces',
'Import only the pages from namespaces belonging to the list of ' .
'pipe-separated namespace names or namespace indexes', false, true );
$this->addOption( 'dry-run', 'Parse dump without actually importing pages' );
$this->addOption( 'debug', 'Output extra verbose debug information' );
$this->addOption( 'skip-to', 'Start from nth page by skipping first n-1 pages', false, true );
$this->addOption( 'skip-to-revid', 'Start from the given revision ID by skipping previous ones', false, true );
$this->addArg( 'file', 'Dump file to import [else use stdin]', false );
}
public function finalSetup( SettingsBuilder $settingsBuilder = null ) {
parent::finalSetup( $settingsBuilder );
SevenZipStream::register();
}
public function execute() {
if ( MediaWikiServices::getInstance()->getReadOnlyMode()->isReadOnly() ) {
$this->fatalError( "Wiki is in read-only mode; you'll need to disable it for import to work." );
}
parent::execute();
$this->reportingInterval = intval( $this->getOption( 'report', 100 ) );
if ( !$this->reportingInterval ) {
// avoid division by zero
$this->reportingInterval = 100;
}
$this->dryRun = $this->hasOption( 'dry-run' );
if ( $this->hasOption( 'namespaces' ) ) {
$this->setNsfilter( explode( '|', $this->getOption( 'namespaces' ) ) );
}
if ( $this->hasOption( 'skip-to-revid' ) ) {
$this->skipToRevId = $this->getOption( 'skip-to-revid' );
}
if ( $this->hasArg( 0 ) ) {
$this->importFromFile( $this->getArg( 0 ) );
} else {
$this->importFromStdin();
}
$this->output( "Done!\n" );
$this->output( "You might want to run rebuildrecentchanges.php to regenerate RecentChanges,\n" );
$this->output( "and initSiteStats.php to update page and revision counts\n" );
}
private function importFromFile( $filename ) {
if ( preg_match( '/\.gz$/', $filename ) ) {
$filename = 'compress.zlib://' . $filename;
} elseif ( preg_match( '/\.bz2$/', $filename ) ) {
$filename = 'compress.bzip2://' . $filename;
} elseif ( preg_match( '/\.7z$/', $filename ) ) {
$filename = 'mediawiki.compress.7z://' . $filename;
}
$file = fopen( $filename, 'rt' );
if ( $file === false ) {
$this->fatalError( error_get_last()['message'] ?? 'Could not open file' );
}
return $this->importFromHandle( $file );
}
private function importFromStdin() {
$file = fopen( 'php://stdin', 'rt' );
if ( self::posix_isatty( $file ) ) {
$this->maybeHelp( true );
}
return $this->importFromHandle( $file );
}
private function importFromHandle( $handle ) {
$this->startTime = microtime( true );
$source = new ImportStreamSource( $handle );
$importer = new WikiImportHandler( $source );
if ( $this->hasOption( 'debug' ) ) {
$importer->setDebug( true );
}
if ( $this->hasOption( 'skip-to' ) ) {
$nthPage = (int)$this->getOption( 'skip-to' );
$importer->setPageOffset( $nthPage );
$this->pageCount = $nthPage - 1;
}
$importer->setPageCallback( [ $this, 'handlePage' ] );
$importer->setNoticeCallback( static function ( $msg, $params ) {
echo wfMessage( $msg, $params )->text() . "\n";
} );
$importer->setRevisionCallback( [ $this, 'handleRevision' ] );
$importer->setPageOutCallback( [ $this, 'handlePageOut' ] );
return $importer->doImport();
}
private function setNsfilter( array $namespaces ) {
if ( count( $namespaces ) == 0 ) {
$this->nsFilter = false;
return;
}
$this->nsFilter = array_unique( array_map( [ $this, 'getNsIndex' ], $namespaces ) );
}
private function getNsIndex( $namespace ) {
$contLang = MediaWikiServices::getInstance()->getContentLanguage();
$result = $contLang->getNsIndex( $namespace );
if ( $result !== false ) {
return $result;
}
$ns = intval( $namespace );
if ( strval( $ns ) === $namespace && $contLang->getNsText( $ns ) !== false ) {
return $ns;
}
$this->fatalError( "Unknown namespace text / index specified: $namespace" );
}
/**
* @param int $ns
* @return bool
*/
private function skippedNamespace( $ns ) {
return is_array( $this->nsFilter ) && !in_array( $ns, $this->nsFilter );
}
public function handlePage( $pageInfo ) {
if ( $this->skippedNamespace( (int)$pageInfo['ns'] ) ) {
return false;
}
$this->pageCount++;
}
private function report( $final = false ) {
if ( $final xor ( $this->pageCount % $this->reportingInterval == 0 ) ) {
$this->showReport();
}
}
private function showReport() {
if ( !$this->mQuiet ) {
$delta = microtime( true ) - $this->startTime;
if ( $delta ) {
$rate = sprintf( "%.2f", $this->pageCount / $delta );
$revrate = sprintf( "%.2f", $this->revCount / $delta );
} else {
$rate = '-';
$revrate = '-';
}
# Logs dumps don't have page tallies
if ( $this->pageCount ) {
$this->progress( "$this->pageCount ($rate pages/sec $revrate revs/sec)" );
} else {
$this->progress( "$this->revCount ($revrate revs/sec)" );
}
}
MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->waitForReplication();
}
private function progress( $string ) {
fwrite( $this->stderr, $string . "\n" );
}
public function handleRevision( array $pageInfo, array $revisionInfo ) {
$this->revCount++;
$this->report();
if ( $this->skipToRevId ) {
if ( $revisionInfo['id'] == $this->skipToRevId ) {
$this->skipToRevId = null;
}
} elseif ( !$this->dryRun ) {
return $this->insertRevision( $pageInfo, $revisionInfo );
}
}
private function insertRevision( array $pageInfo, array $revisionInfo ) {
$user = $revisionInfo['contributor'];
$userName = $user['username'] ?? $user['ip'] ?? '';
$revision = [
'revid' => $revisionInfo['id'],
'parentid' => $revisionInfo['parentid'] ?? 0,
'minor' => $revisionInfo['minor'] ?? null,
'user' => $userName,
'userid' => $user['id'] ?? 0,
'timestamp' => $revisionInfo['timestamp'],
'sha1' => $revisionInfo['sha1'],
'contentmodel' => $revisionInfo['model'],
'contentformat' => $revisionInfo['format'] ?? null,
'*' => $revisionInfo['text'],
'comment' => $revisionInfo['comment'] ?? '',
'texthidden' => ( $revisionInfo['deleted']['text'] ?? false ) ?: null,
'userhidden' => ( $revisionInfo['deleted']['contributor'] ?? false ) ?: null,
'commenthidden' => ( $revisionInfo['deleted']['comment'] ?? false ) ?: null,
];
$pageIdent = PageIdentityValue::localIdentity(
$pageInfo['id'], $pageInfo['ns'],
$this->sanitiseTitle( $pageInfo['ns'], $pageInfo['title'] )
);
return $this->processRevision( $revision, $pageInfo['id'], $pageIdent );
}
public function handlePageOut( array $pageInfo, array $revisionInfo ) {
$pageID = $pageInfo['id'];
$page_e = [
'namespace' => $pageInfo['ns'],
'title' => $this->sanitiseTitle( $pageInfo['ns'], $pageInfo['title'] ),
'is_redirect' => ( isset( $pageInfo['redirect'] ) ? 1 : 0 ),
'len' => strlen( $revisionInfo['text'] ),
'latest' => $revisionInfo['id'],
'content_model' => null
];
# We kind of need this to resume...
// $this->output( "Title: {$page_e['title']} in namespace {$page_e['namespace']}\n" );
// $title = Title::makeTitle( $page_e['namespace'], $page_e['title'] );
if ( isset( $revisionInfo['model'] ) ) {
# This would be the most accurate way of getting the content model for a page.
# However it calls hooks and can be incredibly slow or cause errors
# $defaultModel = ContentHandler::getDefaultModelFor( $title );
$defaultModel = MediaWikiServices::getInstance()->getNamespaceInfo()
->getNamespaceContentModel( $pageInfo['ns'] ) || CONTENT_MODEL_WIKITEXT;
# Set only if not the default content model
if ( $defaultModel != $revisionInfo['model'] ) {
$page_e['content_model'] = $revisionInfo['model'];
}
}
# Check if page is present
$pageIsPresent = false;
$pageRow = $this->dbw->selectRow(
'page',
[ 'page_latest', 'page_namespace', 'page_title' ],
[ 'page_id' => $pageID ],
__METHOD__
);
if ( $pageRow ) {
$pageLatest = $pageRow->page_latest;
$pageIsPresent = true;
}
# If page is not present, check if title is present, because we can't insert
# a duplicate title. That would mean the page was moved leaving a redirect but
# we haven't processed the move yet
if ( !$pageIsPresent ||
$pageRow->page_namespace != $page_e['namespace'] ||
$pageRow->page_title != $page_e['title']
) {
$conflictingPageID = $this->getPageID( $page_e['namespace'], $page_e['title'] );
if ( $conflictingPageID ) {
# Whoops...
$this->resolveConflictingTitle( $page_e['namespace'], $page_e['title'], $pageID, $conflictingPageID );
# The conflicting page can be deleted because we are working on a XML dump.
# The page would be created unintentionally again, but we will eventually
# reach the synced state.
$pageLatest = $this->dbw->selectField(
'page',
'page_latest',
[ 'page_id' => $pageID ],
__METHOD__
);
$pageIsPresent = $pageLatest !== false;
}
}
$insert_fields = [
'page_namespace' => $page_e['namespace'],
'page_title' => $page_e['title'],
'page_is_redirect' => $page_e['is_redirect'],
'page_is_new' => 0,
'page_touched' => wfTimestampNow(),
'page_latest' => $page_e['latest'],
'page_len' => $page_e['len'],
'page_content_model' => $page_e['content_model']
];
if ( !$pageIsPresent ) {
# insert if not present
$this->output( "Inserting page entry $pageID\n" );
$insert_fields += [
'page_id' => $pageID,
'page_random' => wfRandom(),
];
$this->dbw->insert(
'page',
$insert_fields,
__METHOD__
);
} else {
# update existing
$this->output( "Updating page entry $pageID\n" );
$this->dbw->update(
'page',
$insert_fields,
[ 'page_id' => $pageID ],
__METHOD__
);
}
}
}
$maintClass = ImportDump::class;
require_once RUN_MAINTENANCE_IF_MAIN;