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