MediaWiki REL1_40
importDump.php
Go to the documentation of this file.
1<?php
29
30require_once __DIR__ . '/Maintenance.php';
31
39 public $reportingInterval = 100;
41 public $pageCount = 0;
43 public $revCount = 0;
45 public $dryRun = false;
47 public $uploads = false;
49 protected $uploadCount = 0;
51 public $imageBasePath = false;
53 public $nsFilter = false;
55 public $stderr;
57 protected $importCallback;
61 protected $uploadCallback;
63 protected $startTime;
64
65 public function __construct() {
66 parent::__construct();
67 $gz = in_array( 'compress.zlib', stream_get_wrappers() )
68 ? 'ok'
69 : '(disabled; requires PHP zlib module)';
70 $bz2 = in_array( 'compress.bzip2', stream_get_wrappers() )
71 ? 'ok'
72 : '(disabled; requires PHP bzip2 module)';
73
74 $this->addDescription(
75 <<<TEXT
76This script reads pages from an XML file as produced from Special:Export or
77dumpBackup.php, and saves them into the current wiki.
78
79Compressed XML files may be read directly:
80 .gz $gz
81 .bz2 $bz2
82 .7z (if 7za executable is in PATH)
83
84Note that for very large data sets, importDump.php may be slow; there are
85alternate methods which can be much faster for full site restoration:
86<https://www.mediawiki.org/wiki/Manual:Importing_XML_dumps>
87TEXT
88 );
89 $this->stderr = fopen( "php://stderr", "wt" );
90 $this->addOption( 'report',
91 'Report position and speed after every n pages processed', false, true );
92 $this->addOption( 'namespaces',
93 'Import only the pages from namespaces belonging to the list of ' .
94 'pipe-separated namespace names or namespace indexes', false, true );
95 $this->addOption( 'rootpage', 'Pages will be imported as subpages of the specified page',
96 false, true );
97 $this->addOption( 'dry-run', 'Parse dump without actually importing pages' );
98 $this->addOption( 'debug', 'Output extra verbose debug information' );
99 $this->addOption( 'uploads', 'Process file upload data if included (experimental)' );
100 $this->addOption(
101 'no-updates',
102 'Disable link table updates. Is faster but leaves the wiki in an inconsistent state'
103 );
104 $this->addOption( 'image-base-path', 'Import files from a specified path', false, true );
105 $this->addOption( 'skip-to', 'Start from nth page by skipping first n-1 pages', false, true );
106 $this->addOption( 'username-prefix',
107 'Prefix for interwiki usernames; a trailing ">" will be added. Default: "imported>"',
108 false, true );
109 $this->addOption( 'no-local-users',
110 'Treat all usernames as interwiki. ' .
111 'The default is to assign edits to local users where they exist.',
112 false, false
113 );
114 $this->addArg( 'file', 'Dump file to import [else use stdin]', false );
115 }
116
117 public function execute() {
118 if ( MediaWikiServices::getInstance()->getReadOnlyMode()->isReadOnly() ) {
119 $this->fatalError( "Wiki is in read-only mode; you'll need to disable it for import to work." );
120 }
121
122 $this->reportingInterval = intval( $this->getOption( 'report', 100 ) );
123 if ( !$this->reportingInterval ) {
124 // avoid division by zero
125 $this->reportingInterval = 100;
126 }
127
128 $this->dryRun = $this->hasOption( 'dry-run' );
129 $this->uploads = $this->hasOption( 'uploads' );
130
131 if ( $this->hasOption( 'image-base-path' ) ) {
132 $this->imageBasePath = $this->getOption( 'image-base-path' );
133 }
134 if ( $this->hasOption( 'namespaces' ) ) {
135 $this->setNsfilter( explode( '|', $this->getOption( 'namespaces' ) ) );
136 }
137
138 if ( $this->hasArg( 0 ) ) {
139 $this->importFromFile( $this->getArg( 0 ) );
140 } else {
141 $this->importFromStdin();
142 }
143
144 $this->output( "Done!\n" );
145 $this->output( "You might want to run rebuildrecentchanges.php to regenerate RecentChanges,\n" );
146 $this->output( "and initSiteStats.php to update page and revision counts\n" );
147 }
148
149 private function setNsfilter( array $namespaces ) {
150 if ( count( $namespaces ) == 0 ) {
151 $this->nsFilter = false;
152
153 return;
154 }
155 $this->nsFilter = array_unique( array_map( [ $this, 'getNsIndex' ], $namespaces ) );
156 }
157
158 private function getNsIndex( $namespace ) {
159 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
160 $result = $contLang->getNsIndex( $namespace );
161 if ( $result !== false ) {
162 return $result;
163 }
164 $ns = intval( $namespace );
165 if ( strval( $ns ) === $namespace && $contLang->getNsText( $ns ) !== false ) {
166 return $ns;
167 }
168 $this->fatalError( "Unknown namespace text / index specified: $namespace" );
169 }
170
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 = MediaWikiServices::getInstance()->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 MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->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 $source = new ImportStreamSource( $handle );
315 $importer = MediaWikiServices::getInstance()
316 ->getWikiImporterFactory()
317 ->getWikiImporter( $source );
318
319 // Updating statistics require a lot of time so disable it
320 $importer->disableStatisticsUpdate();
321
322 if ( $this->hasOption( 'debug' ) ) {
323 $importer->setDebug( true );
324 }
325 if ( $this->hasOption( 'no-updates' ) ) {
326 $importer->setNoUpdates( true );
327 }
328 $importer->setUsernamePrefix(
329 $this->getOption( 'username-prefix', 'imported' ),
330 !$this->hasOption( 'no-local-users' )
331 );
332 if ( $this->hasOption( 'rootpage' ) ) {
333 $statusRootPage = $importer->setTargetRootPage( $this->getOption( 'rootpage' ) );
334 if ( !$statusRootPage->isGood() ) {
335 // Die here so that it doesn't print "Done!"
336 $this->fatalError( $statusRootPage->getMessage( false, false, 'en' )->text() );
337 }
338 }
339 if ( $this->hasOption( 'skip-to' ) ) {
340 $nthPage = (int)$this->getOption( 'skip-to' );
341 $importer->setPageOffset( $nthPage );
342 $this->pageCount = $nthPage - 1;
343 }
344 $importer->setPageCallback( [ $this, 'reportPage' ] );
345 $importer->setNoticeCallback( static function ( $msg, $params ) {
346 echo wfMessage( $msg, $params )->text() . "\n";
347 } );
348 $this->importCallback = $importer->setRevisionCallback(
349 [ $this, 'handleRevision' ] );
350 $this->uploadCallback = $importer->setUploadCallback(
351 [ $this, 'handleUpload' ] );
352 $this->logItemCallback = $importer->setLogItemCallback(
353 [ $this, 'handleLogItem' ] );
354 if ( $this->uploads ) {
355 $importer->setImportUploads( true );
356 }
357 if ( $this->imageBasePath ) {
358 $importer->setImageBasePath( $this->imageBasePath );
359 }
360
361 if ( $this->dryRun ) {
362 $importer->setPageOutCallback( null );
363 }
364
365 return $importer->doImport();
366 }
367}
368
369$maintClass = BackupReader::class;
370require_once RUN_MAINTENANCE_IF_MAIN;
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
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?
hasOption( $name)
Checks to see if a particular option was set.
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.
Service locator for MediaWiki core services.
Represents a revision, log entry or upload during the import process.
$maintClass
$source
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition router.php:42