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