MediaWiki master
importDump.php
Go to the documentation of this file.
1<?php
30
31require_once __DIR__ . '/Maintenance.php';
32
40 public $reportingInterval = 100;
42 public $pageCount = 0;
44 public $revCount = 0;
46 public $dryRun = false;
48 public $uploads = false;
50 protected $uploadCount = 0;
52 public $imageBasePath = false;
54 public $nsFilter = false;
56 public $stderr;
58 protected $importCallback;
62 protected $uploadCallback;
64 protected $startTime;
65
66 public function __construct() {
67 parent::__construct();
68 $gz = in_array( 'compress.zlib', stream_get_wrappers() )
69 ? 'ok'
70 : '(disabled; requires PHP zlib module)';
71 $bz2 = in_array( 'compress.bzip2', stream_get_wrappers() )
72 ? 'ok'
73 : '(disabled; requires PHP bzip2 module)';
74
75 $this->addDescription(
76 <<<TEXT
77This script reads pages from an XML file as produced from Special:Export or
78dumpBackup.php, and saves them into the current wiki.
79
80Compressed XML files may be read directly:
81 .gz $gz
82 .bz2 $bz2
83 .7z (if 7za executable is in PATH)
84
85Note that for very large data sets, importDump.php may be slow; there are
86alternate methods which can be much faster for full site restoration:
87<https://www.mediawiki.org/wiki/Manual:Importing_XML_dumps>
88TEXT
89 );
90 $this->stderr = fopen( "php://stderr", "wt" );
91 $this->addOption( 'report',
92 'Report position and speed after every n pages processed', false, true );
93 $this->addOption( 'namespaces',
94 'Import only the pages from namespaces belonging to the list of ' .
95 'pipe-separated namespace names or namespace indexes', false, true );
96 $this->addOption( 'rootpage', 'Pages will be imported as subpages of the specified page',
97 false, true );
98 $this->addOption( 'dry-run', 'Parse dump without actually importing pages' );
99 $this->addOption( 'debug', 'Output extra verbose debug information' );
100 $this->addOption( 'uploads', 'Process file upload data if included (experimental)' );
101 $this->addOption(
102 'no-updates',
103 'Disable link table updates. Is faster but leaves the wiki in an inconsistent state'
104 );
105 $this->addOption( 'image-base-path', 'Import files from a specified path', false, true );
106 $this->addOption( 'skip-to', 'Start from nth page by skipping first n-1 pages', false, true );
107 $this->addOption( 'username-prefix',
108 'Prefix for interwiki usernames; a trailing ">" will be added. Default: "imported>"',
109 false, true );
110 $this->addOption( 'no-local-users',
111 'Treat all usernames as interwiki. ' .
112 'The default is to assign edits to local users where they exist.',
113 false, false
114 );
115 $this->addArg( 'file', 'Dump file to import [else use stdin]', false );
116 }
117
118 public function execute() {
119 if ( $this->getServiceContainer()->getReadOnlyMode()->isReadOnly() ) {
120 $this->fatalError( "Wiki is in read-only mode; you'll need to disable it for import to work." );
121 }
122
123 $this->reportingInterval = intval( $this->getOption( 'report', 100 ) );
124 if ( !$this->reportingInterval ) {
125 // avoid division by zero
126 $this->reportingInterval = 100;
127 }
128
129 $this->dryRun = $this->hasOption( 'dry-run' );
130 $this->uploads = $this->hasOption( 'uploads' );
131
132 if ( $this->hasOption( 'image-base-path' ) ) {
133 $this->imageBasePath = $this->getOption( 'image-base-path' );
134 }
135 if ( $this->hasOption( 'namespaces' ) ) {
136 $this->setNsfilter( explode( '|', $this->getOption( 'namespaces' ) ) );
137 }
138
139 if ( $this->hasArg( 0 ) ) {
140 $this->importFromFile( $this->getArg( 0 ) );
141 } else {
142 $this->importFromStdin();
143 }
144
145 $this->output( "Done!\n" );
146 $this->output( "You might want to run rebuildrecentchanges.php to regenerate RecentChanges,\n" );
147 $this->output( "and initSiteStats.php to update page and revision counts\n" );
148 }
149
150 private function setNsfilter( array $namespaces ) {
151 if ( count( $namespaces ) == 0 ) {
152 $this->nsFilter = false;
153
154 return;
155 }
156 $this->nsFilter = array_unique( array_map( [ $this, 'getNsIndex' ], $namespaces ) );
157 }
158
159 private function getNsIndex( $namespace ) {
160 $contLang = $this->getServiceContainer()->getContentLanguage();
161 $result = $contLang->getNsIndex( $namespace );
162 if ( $result !== false ) {
163 return $result;
164 }
165 $ns = intval( $namespace );
166 if ( strval( $ns ) === $namespace && $contLang->getNsText( $ns ) !== false ) {
167 return $ns;
168 }
169 $this->fatalError( "Unknown namespace text / index specified: $namespace" );
170 }
171
176 private function skippedNamespace( $title ) {
177 if ( $title === null ) {
178 // Probably a log entry
179 return false;
180 }
181
182 $ns = $title->getNamespace();
183
184 return is_array( $this->nsFilter ) && !in_array( $ns, $this->nsFilter );
185 }
186
187 public function reportPage( $page ) {
188 $this->pageCount++;
189 }
190
194 public function handleRevision( WikiRevision $rev ) {
195 $title = $rev->getTitle();
196 if ( !$title ) {
197 $this->progress( "Got bogus revision with null title!" );
198
199 return;
200 }
201
202 if ( $this->skippedNamespace( $title ) ) {
203 return;
204 }
205
206 $this->revCount++;
207 $this->report();
208
209 if ( !$this->dryRun ) {
210 call_user_func( $this->importCallback, $rev );
211 }
212 }
213
218 public function handleUpload( WikiRevision $revision ) {
219 if ( $this->uploads ) {
220 if ( $this->skippedNamespace( $revision->getTitle() ) ) {
221 return false;
222 }
223 $this->uploadCount++;
224 // $this->report();
225 $this->progress( "upload: " . $revision->getFilename() );
226
227 if ( !$this->dryRun ) {
228 // bluuuh hack
229 // call_user_func( $this->uploadCallback, $revision );
230 $importer = $this->getServiceContainer()->getWikiRevisionUploadImporter();
231 $statusValue = $importer->import( $revision );
232
233 return $statusValue->isGood();
234 }
235 }
236
237 return false;
238 }
239
243 public function handleLogItem( WikiRevision $rev ) {
244 if ( $this->skippedNamespace( $rev->getTitle() ) ) {
245 return;
246 }
247 $this->revCount++;
248 $this->report();
249
250 if ( !$this->dryRun ) {
251 call_user_func( $this->logItemCallback, $rev );
252 }
253 }
254
255 private function report( $final = false ) {
256 if ( $final xor ( $this->pageCount % $this->reportingInterval == 0 ) ) {
257 $this->showReport();
258 }
259 }
260
261 private function showReport() {
262 if ( !$this->mQuiet ) {
263 $delta = microtime( true ) - $this->startTime;
264 if ( $delta ) {
265 $rate = sprintf( "%.2f", $this->pageCount / $delta );
266 $revrate = sprintf( "%.2f", $this->revCount / $delta );
267 } else {
268 $rate = '-';
269 $revrate = '-';
270 }
271 # Logs dumps don't have page tallies
272 if ( $this->pageCount ) {
273 $this->progress( "$this->pageCount ($rate pages/sec $revrate revs/sec)" );
274 } else {
275 $this->progress( "$this->revCount ($revrate revs/sec)" );
276 }
277 }
278 $this->waitForReplication();
279 }
280
281 private function progress( $string ) {
282 fwrite( $this->stderr, $string . "\n" );
283 }
284
285 private function importFromFile( $filename ) {
286 if ( preg_match( '/\.gz$/', $filename ) ) {
287 $filename = 'compress.zlib://' . $filename;
288 } elseif ( preg_match( '/\.bz2$/', $filename ) ) {
289 $filename = 'compress.bzip2://' . $filename;
290 } elseif ( preg_match( '/\.7z$/', $filename ) ) {
291 $filename = 'mediawiki.compress.7z://' . $filename;
292 }
293
294 $file = fopen( $filename, 'rt' );
295 if ( $file === false ) {
296 $this->fatalError( error_get_last()['message'] ?? 'Could not open file' );
297 }
298
299 return $this->importFromHandle( $file );
300 }
301
302 private function importFromStdin() {
303 $file = fopen( 'php://stdin', 'rt' );
304 if ( self::posix_isatty( $file ) ) {
305 $this->maybeHelp( true );
306 }
307
308 return $this->importFromHandle( $file );
309 }
310
311 private function importFromHandle( $handle ) {
312 $this->startTime = microtime( true );
313
314 $user = User::newSystemUser( User::MAINTENANCE_SCRIPT_USER, [ 'steal' => true ] );
315
316 $source = new ImportStreamSource( $handle );
317 $importer = $this->getServiceContainer()
318 ->getWikiImporterFactory()
319 ->getWikiImporter( $source, new UltimateAuthority( $user ) );
320
321 // Updating statistics require a lot of time so disable it
322 $importer->disableStatisticsUpdate();
323
324 if ( $this->hasOption( 'debug' ) ) {
325 $importer->setDebug( true );
326 }
327 if ( $this->hasOption( 'no-updates' ) ) {
328 $importer->setNoUpdates( true );
329 }
330 $importer->setUsernamePrefix(
331 $this->getOption( 'username-prefix', 'imported' ),
332 !$this->hasOption( 'no-local-users' )
333 );
334 if ( $this->hasOption( 'rootpage' ) ) {
335 $statusRootPage = $importer->setTargetRootPage( $this->getOption( 'rootpage' ) );
336 if ( !$statusRootPage->isGood() ) {
337 // Die here so that it doesn't print "Done!"
338 $this->fatalError( $statusRootPage );
339 }
340 }
341 if ( $this->hasOption( 'skip-to' ) ) {
342 $nthPage = (int)$this->getOption( 'skip-to' );
343 $importer->setPageOffset( $nthPage );
344 $this->pageCount = $nthPage - 1;
345 }
346 $importer->setPageCallback( [ $this, 'reportPage' ] );
347 $importer->setNoticeCallback( static function ( $msg, $params ) {
348 echo wfMessage( $msg, $params )->text() . "\n";
349 } );
350 $this->importCallback = $importer->setRevisionCallback(
351 [ $this, 'handleRevision' ] );
352 $this->uploadCallback = $importer->setUploadCallback(
353 [ $this, 'handleUpload' ] );
354 $this->logItemCallback = $importer->setLogItemCallback(
355 [ $this, 'handleLogItem' ] );
356 if ( $this->uploads ) {
357 $importer->setImportUploads( true );
358 }
359 if ( $this->imageBasePath ) {
360 $importer->setImageBasePath( $this->imageBasePath );
361 }
362
363 if ( $this->dryRun ) {
364 $importer->setPageOutCallback( null );
365 }
366
367 return $importer->doImport();
368 }
369}
370
371$maintClass = BackupReader::class;
372require_once RUN_MAINTENANCE_IF_MAIN;
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
array $params
The job parameters.
Maintenance script that imports XML dump files into the current wiki.
resource false $stderr
handleRevision(WikiRevision $rev)
string false $imageBasePath
float $startTime
callable null $logItemCallback
callable null $uploadCallback
array false $nsFilter
execute()
Do the actual work.
handleLogItem(WikiRevision $rev)
__construct()
Default constructor.
reportPage( $page)
callable null $importCallback
int $reportingInterval
handleUpload(WikiRevision $revision)
Imports a XML dump from a file (either from file upload, files on disk, or HTTP)
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
addArg( $arg, $description, $required=true, $multi=false)
Add some args that are needed.
output( $out, $channel=null)
Throw some output to the user.
hasArg( $argId=0)
Does a given argument exist?
waitForReplication()
Wait for replica DBs to catch up.
hasOption( $name)
Checks to see if a particular option was set.
getServiceContainer()
Returns the main service container.
getArg( $argId=0, $default=null)
Get an argument.
addDescription( $text)
Set the description text.
maybeHelp( $force=false)
Maybe show the help.
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
getOption( $name, $default=null)
Get an option, or return the default.
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
Represents an authority that has all permissions.
internal since 1.36
Definition User.php:93
Represents a revision, log entry or upload during the import process.
$maintClass
Represents the target of a wiki link.
$source