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\Linker\LinkTarget
;
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
{
38 public $reportingInterval = 100;
40 public $pageCount = 0;
44 public $dryRun = false;
46 public $uploads = false;
48 protected $uploadCount = 0;
49 /** @var string|false */
50 public $imageBasePath = false;
51 /** @var array|false */
52 public $nsFilter = false;
53 /** @var resource|false */
55 /** @var callable|null */
56 protected $importCallback;
57 /** @var callable|null */
58 protected $logItemCallback;
59 /** @var callable|null */
60 protected $uploadCallback;
64 public function __construct() {
65 parent
::__construct();
66 $gz = in_array( 'compress.zlib', stream_get_wrappers() )
68 : '(disabled; requires PHP zlib module)';
69 $bz2 = in_array( 'compress.bzip2', stream_get_wrappers() )
71 : '(disabled; requires PHP bzip2 module)';
73 $this->addDescription(
75 This script reads pages from an XML file as produced from Special:Export or
76 dumpBackup.php, and saves them into the current wiki.
78 Compressed XML files may be read directly:
81 .7z (if 7za executable is in PATH)
83 Note that for very large data sets, importDump.php may be slow; there are
84 alternate methods which can be much faster for full site restoration:
85 <https://www.mediawiki.org/wiki/Manual:Importing_XML_dumps>
88 $this->stderr
= fopen( "php://stderr", "wt" );
89 $this->addOption( 'report',
90 'Report position and speed after every n pages processed', false, true );
91 $this->addOption( 'namespaces',
92 'Import only the pages from namespaces belonging to the list of ' .
93 'pipe-separated namespace names or namespace indexes', false, true );
94 $this->addOption( 'rootpage', 'Pages will be imported as subpages of the specified page',
96 $this->addOption( 'dry-run', 'Parse dump without actually importing pages' );
97 $this->addOption( 'debug', 'Output extra verbose debug information' );
98 $this->addOption( 'uploads', 'Process file upload data if included (experimental)' );
101 'Disable link table updates. Is faster but leaves the wiki in an inconsistent state'
103 $this->addOption( 'image-base-path', 'Import files from a specified path', false, true );
104 $this->addOption( 'skip-to', 'Start from nth page by skipping first n-1 pages', false, true );
105 $this->addOption( 'username-prefix',
106 'Prefix for interwiki usernames; a trailing ">" will be added. Default: "imported>"',
108 $this->addOption( 'no-local-users',
109 'Treat all usernames as interwiki. ' .
110 'The default is to assign edits to local users where they exist.',
113 $this->addArg( 'file', 'Dump file to import [else use stdin]', false );
116 public function execute() {
117 if ( $this->getServiceContainer()->getReadOnlyMode()->isReadOnly() ) {
118 $this->fatalError( "Wiki is in read-only mode; you'll need to disable it for import to work." );
121 $this->reportingInterval
= intval( $this->getOption( 'report', 100 ) );
122 if ( !$this->reportingInterval
) {
123 // avoid division by zero
124 $this->reportingInterval
= 100;
127 $this->dryRun
= $this->hasOption( 'dry-run' );
128 $this->uploads
= $this->hasOption( 'uploads' );
130 if ( $this->hasOption( 'image-base-path' ) ) {
131 $this->imageBasePath
= $this->getOption( 'image-base-path' );
133 if ( $this->hasOption( 'namespaces' ) ) {
134 $this->setNsfilter( explode( '|', $this->getOption( 'namespaces' ) ) );
137 if ( $this->hasArg( 0 ) ) {
138 $this->importFromFile( $this->getArg( 0 ) );
140 $this->importFromStdin();
143 $this->output( "Done!\n" );
144 $this->output( "You might want to run rebuildrecentchanges.php to regenerate RecentChanges,\n" );
145 $this->output( "and initSiteStats.php to update page and revision counts\n" );
148 private function setNsfilter( array $namespaces ) {
149 if ( count( $namespaces ) == 0 ) {
150 $this->nsFilter
= false;
154 $this->nsFilter
= array_unique( array_map( [ $this, 'getNsIndex' ], $namespaces ) );
157 private function getNsIndex( $namespace ) {
158 $contLang = $this->getServiceContainer()->getContentLanguage();
159 $result = $contLang->getNsIndex( $namespace );
160 if ( $result !== false ) {
163 $ns = intval( $namespace );
164 if ( strval( $ns ) === $namespace && $contLang->getNsText( $ns ) !== false ) {
167 $this->fatalError( "Unknown namespace text / index specified: $namespace" );
171 * @param LinkTarget|null $title
174 private function skippedNamespace( $title ) {
175 if ( $title === null ) {
176 // Probably a log entry
180 $ns = $title->getNamespace();
182 return is_array( $this->nsFilter
) && !in_array( $ns, $this->nsFilter
);
185 public function reportPage( $page ) {
190 * @param WikiRevision $rev
192 public function handleRevision( WikiRevision
$rev ) {
193 $title = $rev->getTitle();
195 $this->progress( "Got bogus revision with null title!" );
200 if ( $this->skippedNamespace( $title ) ) {
207 if ( !$this->dryRun
) {
208 call_user_func( $this->importCallback
, $rev );
213 * @param WikiRevision $revision
216 public function handleUpload( WikiRevision
$revision ) {
217 if ( $this->uploads
) {
218 if ( $this->skippedNamespace( $revision->getTitle() ) ) {
221 $this->uploadCount++
;
223 $this->progress( "upload: " . $revision->getFilename() );
225 if ( !$this->dryRun
) {
227 // call_user_func( $this->uploadCallback, $revision );
228 $importer = $this->getServiceContainer()->getWikiRevisionUploadImporter();
229 $statusValue = $importer->import( $revision );
231 return $statusValue->isGood();
239 * @param WikiRevision $rev
241 public function handleLogItem( WikiRevision
$rev ) {
242 if ( $this->skippedNamespace( $rev->getTitle() ) ) {
248 if ( !$this->dryRun
) {
249 call_user_func( $this->logItemCallback
, $rev );
253 private function report( $final = false ) {
254 if ( $final xor ( $this->pageCount %
$this->reportingInterval
== 0 ) ) {
259 private function showReport() {
260 if ( !$this->mQuiet
) {
261 $delta = microtime( true ) - $this->startTime
;
263 $rate = sprintf( "%.2f", $this->pageCount
/ $delta );
264 $revrate = sprintf( "%.2f", $this->revCount
/ $delta );
269 # Logs dumps don't have page tallies
270 if ( $this->pageCount
) {
271 $this->progress( "$this->pageCount ($rate pages/sec $revrate revs/sec)" );
273 $this->progress( "$this->revCount ($revrate revs/sec)" );
276 $this->getServiceContainer()->getDBLoadBalancerFactory()->waitForReplication();
279 private function progress( $string ) {
280 fwrite( $this->stderr
, $string . "\n" );
283 private function importFromFile( $filename ) {
284 if ( preg_match( '/\.gz$/', $filename ) ) {
285 $filename = 'compress.zlib://' . $filename;
286 } elseif ( preg_match( '/\.bz2$/', $filename ) ) {
287 $filename = 'compress.bzip2://' . $filename;
288 } elseif ( preg_match( '/\.7z$/', $filename ) ) {
289 $filename = 'mediawiki.compress.7z://' . $filename;
292 $file = fopen( $filename, 'rt' );
293 if ( $file === false ) {
294 $this->fatalError( error_get_last()['message'] ??
'Could not open file' );
297 return $this->importFromHandle( $file );
300 private function importFromStdin() {
301 $file = fopen( 'php://stdin', 'rt' );
302 if ( self
::posix_isatty( $file ) ) {
303 $this->maybeHelp( true );
306 return $this->importFromHandle( $file );
309 private function importFromHandle( $handle ) {
310 $this->startTime
= microtime( true );
312 $source = new ImportStreamSource( $handle );
313 $importer = $this->getServiceContainer()
314 ->getWikiImporterFactory()
315 ->getWikiImporter( $source );
317 // Updating statistics require a lot of time so disable it
318 $importer->disableStatisticsUpdate();
320 if ( $this->hasOption( 'debug' ) ) {
321 $importer->setDebug( true );
323 if ( $this->hasOption( 'no-updates' ) ) {
324 $importer->setNoUpdates( true );
326 $importer->setUsernamePrefix(
327 $this->getOption( 'username-prefix', 'imported' ),
328 !$this->hasOption( 'no-local-users' )
330 if ( $this->hasOption( 'rootpage' ) ) {
331 $statusRootPage = $importer->setTargetRootPage( $this->getOption( 'rootpage' ) );
332 if ( !$statusRootPage->isGood() ) {
333 // Die here so that it doesn't print "Done!"
334 $this->fatalError( $statusRootPage->getMessage( false, false, 'en' )->text() );
337 if ( $this->hasOption( 'skip-to' ) ) {
338 $nthPage = (int)$this->getOption( 'skip-to' );
339 $importer->setPageOffset( $nthPage );
340 $this->pageCount
= $nthPage - 1;
342 $importer->setPageCallback( [ $this, 'reportPage' ] );
343 $importer->setNoticeCallback( static function ( $msg, $params ) {
344 echo wfMessage( $msg, $params )->text() . "\n";
346 $this->importCallback
= $importer->setRevisionCallback(
347 [ $this, 'handleRevision' ] );
348 $this->uploadCallback
= $importer->setUploadCallback(
349 [ $this, 'handleUpload' ] );
350 $this->logItemCallback
= $importer->setLogItemCallback(
351 [ $this, 'handleLogItem' ] );
352 if ( $this->uploads
) {
353 $importer->setImportUploads( true );
355 if ( $this->imageBasePath
) {
356 $importer->setImageBasePath( $this->imageBasePath
);
359 if ( $this->dryRun
) {
360 $importer->setPageOutCallback( null );
363 return $importer->doImport();
367 $maintClass = BackupReader
::class;
368 require_once RUN_MAINTENANCE_IF_MAIN
;