3 * Import XML dump files into the current wiki.
5 * Copyright © 2005 Brion Vibber <brion@pobox.com>
6 * https://www.mediawiki.org/
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
24 * @ingroup Maintenance
27 use MediaWiki\MediaWikiServices
;
29 require_once __DIR__
. '/Maintenance.php';
32 * Maintenance script that imports XML dump files into the current wiki.
34 * @ingroup Maintenance
36 class BackupReader
extends Maintenance
{
37 public $reportingInterval = 100;
38 public $pageCount = 0;
40 public $dryRun = false;
41 public $uploads = false;
42 protected $uploadCount = 0;
43 public $imageBasePath = false;
44 /** @var array|false */
45 public $nsFilter = false;
46 /** @var bool|resource */
48 /** @var callable|null */
49 protected $importCallback;
50 /** @var callable|null */
51 protected $logItemCallback;
52 /** @var callable|null */
53 protected $uploadCallback;
57 function __construct() {
58 parent
::__construct();
59 $gz = in_array( 'compress.zlib', stream_get_wrappers() )
61 : '(disabled; requires PHP zlib module)';
62 $bz2 = in_array( 'compress.bzip2', stream_get_wrappers() )
64 : '(disabled; requires PHP bzip2 module)';
66 $this->addDescription(
68 This script reads pages from an XML file as produced from Special:Export or
69 dumpBackup.php, and saves them into the current wiki.
71 Compressed XML files may be read directly:
74 .7z (if 7za executable is in PATH)
76 Note that for very large data sets, importDump.php may be slow; there are
77 alternate methods which can be much faster for full site restoration:
78 <https://www.mediawiki.org/wiki/Manual:Importing_XML_dumps>
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',
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)' );
94 'Disable link table updates. Is faster but leaves the wiki in an inconsistent state'
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', 'Prefix for interwiki usernames', 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.',
104 $this->addArg( 'file', 'Dump file to import [else use stdin]', false );
107 public function execute() {
108 if ( wfReadOnly() ) {
109 $this->fatalError( "Wiki is in read-only mode; you'll need to disable it for import to work." );
112 $this->reportingInterval
= intval( $this->getOption( 'report', 100 ) );
113 if ( !$this->reportingInterval
) {
114 $this->reportingInterval
= 100; // avoid division by zero
117 $this->dryRun
= $this->hasOption( 'dry-run' );
118 $this->uploads
= $this->hasOption( 'uploads' ); // experimental!
119 if ( $this->hasOption( 'image-base-path' ) ) {
120 $this->imageBasePath
= $this->getOption( 'image-base-path' );
122 if ( $this->hasOption( 'namespaces' ) ) {
123 $this->setNsfilter( explode( '|', $this->getOption( 'namespaces' ) ) );
126 if ( $this->hasArg( 0 ) ) {
127 $this->importFromFile( $this->getArg( 0 ) );
129 $this->importFromStdin();
132 $this->output( "Done!\n" );
133 $this->output( "You might want to run rebuildrecentchanges.php to regenerate RecentChanges,\n" );
134 $this->output( "and initSiteStats.php to update page and revision counts\n" );
137 function setNsfilter( array $namespaces ) {
138 if ( count( $namespaces ) == 0 ) {
139 $this->nsFilter
= false;
143 $this->nsFilter
= array_unique( array_map( [ $this, 'getNsIndex' ], $namespaces ) );
146 private function getNsIndex( $namespace ) {
147 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
148 $result = $contLang->getNsIndex( $namespace );
149 if ( $result !== false ) {
152 $ns = intval( $namespace );
153 if ( strval( $ns ) === $namespace && $contLang->getNsText( $ns ) !== false ) {
156 $this->fatalError( "Unknown namespace text / index specified: $namespace" );
160 * @param Title|Revision $obj
161 * @throws MWException
164 private function skippedNamespace( $obj ) {
166 if ( $obj instanceof Title
) {
168 } elseif ( $obj instanceof Revision
) {
169 $title = $obj->getTitle();
170 } elseif ( $obj instanceof WikiRevision
) {
171 $title = $obj->title
;
173 throw new MWException( "Cannot get namespace of object in " . __METHOD__
);
176 if ( is_null( $title ) ) {
177 // Probably a log entry
181 $ns = $title->getNamespace();
183 return is_array( $this->nsFilter
) && !in_array( $ns, $this->nsFilter
);
186 function reportPage( $page ) {
191 * @param Revision $rev
193 function handleRevision( $rev ) {
194 $title = $rev->getTitle();
196 $this->progress( "Got bogus revision with null title!" );
201 if ( $this->skippedNamespace( $title ) ) {
208 if ( !$this->dryRun
) {
209 call_user_func( $this->importCallback
, $rev );
214 * @param Revision $revision
217 function handleUpload( $revision ) {
218 if ( $this->uploads
) {
219 if ( $this->skippedNamespace( $revision ) ) {
222 $this->uploadCount++
;
224 // @phan-suppress-next-line PhanUndeclaredMethod
225 $this->progress( "upload: " . $revision->getFilename() );
227 if ( !$this->dryRun
) {
229 // call_user_func( $this->uploadCallback, $revision );
230 $dbw = $this->getDB( DB_MASTER
);
232 return $dbw->deadlockLoop( [ $revision, 'importUpload' ] );
239 function handleLogItem( $rev ) {
240 if ( $this->skippedNamespace( $rev ) ) {
246 if ( !$this->dryRun
) {
247 call_user_func( $this->logItemCallback
, $rev );
251 function report( $final = false ) {
252 if ( $final xor ( $this->pageCount %
$this->reportingInterval
== 0 ) ) {
257 function showReport() {
258 if ( !$this->mQuiet
) {
259 $delta = microtime( true ) - $this->startTime
;
261 $rate = sprintf( "%.2f", $this->pageCount
/ $delta );
262 $revrate = sprintf( "%.2f", $this->revCount
/ $delta );
267 # Logs dumps don't have page tallies
268 if ( $this->pageCount
) {
269 $this->progress( "$this->pageCount ($rate pages/sec $revrate revs/sec)" );
271 $this->progress( "$this->revCount ($revrate revs/sec)" );
277 function progress( $string ) {
278 fwrite( $this->stderr
, $string . "\n" );
281 function importFromFile( $filename ) {
282 if ( preg_match( '/\.gz$/', $filename ) ) {
283 $filename = 'compress.zlib://' . $filename;
284 } elseif ( preg_match( '/\.bz2$/', $filename ) ) {
285 $filename = 'compress.bzip2://' . $filename;
286 } elseif ( preg_match( '/\.7z$/', $filename ) ) {
287 $filename = 'mediawiki.compress.7z://' . $filename;
290 $file = fopen( $filename, 'rt' );
292 return $this->importFromHandle( $file );
295 function importFromStdin() {
296 $file = fopen( 'php://stdin', 'rt' );
297 if ( self
::posix_isatty( $file ) ) {
298 $this->maybeHelp( true );
301 return $this->importFromHandle( $file );
304 function importFromHandle( $handle ) {
305 $this->startTime
= microtime( true );
307 $source = new ImportStreamSource( $handle );
308 $importer = new WikiImporter( $source, $this->getConfig() );
310 // Updating statistics require a lot of time so disable it
311 $importer->disableStatisticsUpdate();
313 if ( $this->hasOption( 'debug' ) ) {
314 $importer->setDebug( true );
316 if ( $this->hasOption( 'no-updates' ) ) {
317 $importer->setNoUpdates( true );
319 if ( $this->hasOption( 'username-prefix' ) ) {
320 $importer->setUsernamePrefix(
321 $this->getOption( 'username-prefix' ),
322 !$this->hasOption( 'no-local-users' )
325 if ( $this->hasOption( 'rootpage' ) ) {
326 $statusRootPage = $importer->setTargetRootPage( $this->getOption( 'rootpage' ) );
327 if ( !$statusRootPage->isGood() ) {
328 // Die here so that it doesn't print "Done!"
329 $this->fatalError( $statusRootPage->getMessage()->text() );
333 if ( $this->hasOption( 'skip-to' ) ) {
334 $nthPage = (int)$this->getOption( 'skip-to' );
335 $importer->setPageOffset( $nthPage );
336 $this->pageCount
= $nthPage - 1;
338 $importer->setPageCallback( [ $this, 'reportPage' ] );
339 $importer->setNoticeCallback( function ( $msg, $params ) {
340 echo wfMessage( $msg, $params )->text() . "\n";
342 $this->importCallback
= $importer->setRevisionCallback(
343 [ $this, 'handleRevision' ] );
344 $this->uploadCallback
= $importer->setUploadCallback(
345 [ $this, 'handleUpload' ] );
346 $this->logItemCallback
= $importer->setLogItemCallback(
347 [ $this, 'handleLogItem' ] );
348 if ( $this->uploads
) {
349 $importer->setImportUploads( true );
351 if ( $this->imageBasePath
) {
352 $importer->setImageBasePath( $this->imageBasePath
);
355 if ( $this->dryRun
) {
356 $importer->setPageOutCallback( null );
359 return $importer->doImport();
363 $maintClass = BackupReader
::class;
364 require_once RUN_MAINTENANCE_IF_MAIN
;