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