Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 171
0.00% covered (danger)
0.00%
0 / 15
CRAP
0.00% covered (danger)
0.00%
0 / 1
BackupReader
0.00% covered (danger)
0.00%
0 / 168
0.00% covered (danger)
0.00%
0 / 15
2862
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 40
0.00% covered (danger)
0.00%
0 / 1
12
 execute
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
42
 setNsfilter
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 getNsIndex
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
20
 skippedNamespace
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
 reportPage
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 handleRevision
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
20
 handleUpload
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
20
 handleLogItem
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
 report
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 showReport
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
20
 progress
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 importFromFile
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
30
 importFromStdin
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 importFromHandle
0.00% covered (danger)
0.00%
0 / 40
0.00% covered (danger)
0.00%
0 / 1
90
1<?php
2/**
3 * Import XML dump files into the current wiki.
4 *
5 * Copyright © 2005 Brooke Vibber <bvibber@wikimedia.org>
6 * https://www.mediawiki.org/
7 *
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.
12 *
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.
17 *
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
22 *
23 * @file
24 * @ingroup Maintenance
25 */
26
27use MediaWiki\Linker\LinkTarget;
28use MediaWiki\Permissions\UltimateAuthority;
29
30require_once __DIR__ . '/Maintenance.php';
31
32/**
33 * Maintenance script that imports XML dump files into the current wiki.
34 *
35 * @ingroup Maintenance
36 */
37class BackupReader extends Maintenance {
38    /** @var int */
39    public $reportingInterval = 100;
40    /** @var int */
41    public $pageCount = 0;
42    /** @var int */
43    public $revCount = 0;
44    /** @var bool */
45    public $dryRun = false;
46    /** @var bool */
47    public $uploads = false;
48    /** @var int */
49    protected $uploadCount = 0;
50    /** @var string|false */
51    public $imageBasePath = false;
52    /** @var array|false */
53    public $nsFilter = false;
54    /** @var resource|false */
55    public $stderr;
56    /** @var callable|null */
57    protected $importCallback;
58    /** @var callable|null */
59    protected $logItemCallback;
60    /** @var callable|null */
61    protected $uploadCallback;
62    /** @var float */
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 ( $this->getServiceContainer()->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 = $this->getServiceContainer()->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
171    /**
172     * @param LinkTarget|null $title
173     * @return bool
174     */
175    private function skippedNamespace( $title ) {
176        if ( $title === null ) {
177            // Probably a log entry
178            return false;
179        }
180
181        $ns = $title->getNamespace();
182
183        return is_array( $this->nsFilter ) && !in_array( $ns, $this->nsFilter );
184    }
185
186    public function reportPage( $page ) {
187        $this->pageCount++;
188    }
189
190    /**
191     * @param WikiRevision $rev
192     */
193    public function handleRevision( WikiRevision $rev ) {
194        $title = $rev->getTitle();
195        if ( !$title ) {
196            $this->progress( "Got bogus revision with null title!" );
197
198            return;
199        }
200
201        if ( $this->skippedNamespace( $title ) ) {
202            return;
203        }
204
205        $this->revCount++;
206        $this->report();
207
208        if ( !$this->dryRun ) {
209            call_user_func( $this->importCallback, $rev );
210        }
211    }
212
213    /**
214     * @param WikiRevision $revision
215     * @return bool
216     */
217    public function handleUpload( WikiRevision $revision ) {
218        if ( $this->uploads ) {
219            if ( $this->skippedNamespace( $revision->getTitle() ) ) {
220                return false;
221            }
222            $this->uploadCount++;
223            // $this->report();
224            $this->progress( "upload: " . $revision->getFilename() );
225
226            if ( !$this->dryRun ) {
227                // bluuuh hack
228                // call_user_func( $this->uploadCallback, $revision );
229                $importer = $this->getServiceContainer()->getWikiRevisionUploadImporter();
230                $statusValue = $importer->import( $revision );
231
232                return $statusValue->isGood();
233            }
234        }
235
236        return false;
237    }
238
239    /**
240     * @param WikiRevision $rev
241     */
242    public function handleLogItem( WikiRevision $rev ) {
243        if ( $this->skippedNamespace( $rev->getTitle() ) ) {
244            return;
245        }
246        $this->revCount++;
247        $this->report();
248
249        if ( !$this->dryRun ) {
250            call_user_func( $this->logItemCallback, $rev );
251        }
252    }
253
254    private function report( $final = false ) {
255        if ( $final xor ( $this->pageCount % $this->reportingInterval == 0 ) ) {
256            $this->showReport();
257        }
258    }
259
260    private function showReport() {
261        if ( !$this->mQuiet ) {
262            $delta = microtime( true ) - $this->startTime;
263            if ( $delta ) {
264                $rate = sprintf( "%.2f", $this->pageCount / $delta );
265                $revrate = sprintf( "%.2f", $this->revCount / $delta );
266            } else {
267                $rate = '-';
268                $revrate = '-';
269            }
270            # Logs dumps don't have page tallies
271            if ( $this->pageCount ) {
272                $this->progress( "$this->pageCount ($rate pages/sec $revrate revs/sec)" );
273            } else {
274                $this->progress( "$this->revCount ($revrate revs/sec)" );
275            }
276        }
277        $this->waitForReplication();
278    }
279
280    private function progress( $string ) {
281        fwrite( $this->stderr, $string . "\n" );
282    }
283
284    private function importFromFile( $filename ) {
285        if ( preg_match( '/\.gz$/', $filename ) ) {
286            $filename = 'compress.zlib://' . $filename;
287        } elseif ( preg_match( '/\.bz2$/', $filename ) ) {
288            $filename = 'compress.bzip2://' . $filename;
289        } elseif ( preg_match( '/\.7z$/', $filename ) ) {
290            $filename = 'mediawiki.compress.7z://' . $filename;
291        }
292
293        $file = fopen( $filename, 'rt' );
294        if ( $file === false ) {
295            $this->fatalError( error_get_last()['message'] ?? 'Could not open file' );
296        }
297
298        return $this->importFromHandle( $file );
299    }
300
301    private function importFromStdin() {
302        $file = fopen( 'php://stdin', 'rt' );
303        if ( self::posix_isatty( $file ) ) {
304            $this->maybeHelp( true );
305        }
306
307        return $this->importFromHandle( $file );
308    }
309
310    private function importFromHandle( $handle ) {
311        $this->startTime = microtime( true );
312
313        $user = User::newSystemUser( User::MAINTENANCE_SCRIPT_USER, [ 'steal' => true ] );
314
315        $source = new ImportStreamSource( $handle );
316        $importer = $this->getServiceContainer()
317            ->getWikiImporterFactory()
318            ->getWikiImporter( $source, new UltimateAuthority( $user ) );
319
320        // Updating statistics require a lot of time so disable it
321        $importer->disableStatisticsUpdate();
322
323        if ( $this->hasOption( 'debug' ) ) {
324            $importer->setDebug( true );
325        }
326        if ( $this->hasOption( 'no-updates' ) ) {
327            $importer->setNoUpdates( true );
328        }
329        $importer->setUsernamePrefix(
330            $this->getOption( 'username-prefix', 'imported' ),
331            !$this->hasOption( 'no-local-users' )
332        );
333        if ( $this->hasOption( 'rootpage' ) ) {
334            $statusRootPage = $importer->setTargetRootPage( $this->getOption( 'rootpage' ) );
335            if ( !$statusRootPage->isGood() ) {
336                // Die here so that it doesn't print "Done!"
337                $this->fatalError( $statusRootPage->getMessage( false, false, 'en' )->text() );
338            }
339        }
340        if ( $this->hasOption( 'skip-to' ) ) {
341            $nthPage = (int)$this->getOption( 'skip-to' );
342            $importer->setPageOffset( $nthPage );
343            $this->pageCount = $nthPage - 1;
344        }
345        $importer->setPageCallback( [ $this, 'reportPage' ] );
346        $importer->setNoticeCallback( static function ( $msg, $params ) {
347            echo wfMessage( $msg, $params )->text() . "\n";
348        } );
349        $this->importCallback = $importer->setRevisionCallback(
350            [ $this, 'handleRevision' ] );
351        $this->uploadCallback = $importer->setUploadCallback(
352            [ $this, 'handleUpload' ] );
353        $this->logItemCallback = $importer->setLogItemCallback(
354            [ $this, 'handleLogItem' ] );
355        if ( $this->uploads ) {
356            $importer->setImportUploads( true );
357        }
358        if ( $this->imageBasePath ) {
359            $importer->setImageBasePath( $this->imageBasePath );
360        }
361
362        if ( $this->dryRun ) {
363            $importer->setPageOutCallback( null );
364        }
365
366        return $importer->doImport();
367    }
368}
369
370$maintClass = BackupReader::class;
371require_once RUN_MAINTENANCE_IF_MAIN;