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->addArg( 'file', 'Dump file to import [else use stdin]', false );
86 }
87
88 public function execute() {
89 if ( wfReadOnly() ) {
90 $this->error( "Wiki is in read-only mode; you'll need to disable it for import to work.", true );
91 }
92
93 $this->reportingInterval = intval( $this->getOption( 'report', 100 ) );
94 if ( !$this->reportingInterval ) {
95 $this->reportingInterval = 100; // avoid division by zero
96 }
97
98 $this->dryRun = $this->hasOption( 'dry-run' );
99 $this->uploads = $this->hasOption( 'uploads' ); // experimental!
100 if ( $this->hasOption( 'image-base-path' ) ) {
101 $this->imageBasePath = $this->getOption( 'image-base-path' );
102 }
103 if ( $this->hasOption( 'namespaces' ) ) {
104 $this->setNsfilter( explode( '|', $this->getOption( 'namespaces' ) ) );
105 }
106
107 if ( $this->hasArg() ) {
108 $this->importFromFile( $this->getArg() );
109 } else {
110 $this->importFromStdin();
111 }
112
113 $this->output( "Done!\n" );
114 $this->output( "You might want to run rebuildrecentchanges.php to regenerate RecentChanges,\n" );
115 $this->output( "and initSiteStats.php to update page and revision counts\n" );
116 }
117
118 function setNsfilter( array $namespaces ) {
119 if ( count( $namespaces ) == 0 ) {
120 $this->nsFilter = false;
121
122 return;
123 }
124 $this->nsFilter = array_unique( array_map( [ $this, 'getNsIndex' ], $namespaces ) );
125 }
126
127 private function getNsIndex( $namespace ) {
128 global $wgContLang;
129 $result = $wgContLang->getNsIndex( $namespace );
130 if ( $result !== false ) {
131 return $result;
132 }
133 $ns = intval( $namespace );
134 if ( strval( $ns ) === $namespace && $wgContLang->getNsText( $ns ) !== false ) {
135 return $ns;
136 }
137 $this->error( "Unknown namespace text / index specified: $namespace", true );
138 }
139
140 /**
141 * @param Title|Revision $obj
142 * @throws MWException
143 * @return bool
144 */
145 private function skippedNamespace( $obj ) {
146 $title = null;
147 if ( $obj instanceof Title ) {
148 $title = $obj;
149 } elseif ( $obj instanceof Revision ) {
150 $title = $obj->getTitle();
151 } elseif ( $obj instanceof WikiRevision ) {
152 $title = $obj->title;
153 } else {
154 throw new MWException( "Cannot get namespace of object in " . __METHOD__ );
155 }
156
157 if ( is_null( $title ) ) {
158 // Probably a log entry
159 return false;
160 }
161
162 $ns = $title->getNamespace();
163
164 return is_array( $this->nsFilter ) && !in_array( $ns, $this->nsFilter );
165 }
166
167 function reportPage( $page ) {
168 $this->pageCount++;
169 }
170
171 /**
172 * @param Revision $rev
173 */
174 function handleRevision( $rev ) {
175 $title = $rev->getTitle();
176 if ( !$title ) {
177 $this->progress( "Got bogus revision with null title!" );
178
179 return;
180 }
181
182 if ( $this->skippedNamespace( $title ) ) {
183 return;
184 }
185
186 $this->revCount++;
187 $this->report();
188
189 if ( !$this->dryRun ) {
190 call_user_func( $this->importCallback, $rev );
191 }
192 }
193
194 /**
195 * @param Revision $revision
196 * @return bool
197 */
198 function handleUpload( $revision ) {
199 if ( $this->uploads ) {
200 if ( $this->skippedNamespace( $revision ) ) {
201 return false;
202 }
203 $this->uploadCount++;
204 // $this->report();
205 $this->progress( "upload: " . $revision->getFilename() );
206
207 if ( !$this->dryRun ) {
208 // bluuuh hack
209 // call_user_func( $this->uploadCallback, $revision );
210 $dbw = $this->getDB( DB_MASTER );
211
212 return $dbw->deadlockLoop( [ $revision, 'importUpload' ] );
213 }
214 }
215
216 return false;
217 }
218
219 function handleLogItem( $rev ) {
220 if ( $this->skippedNamespace( $rev ) ) {
221 return;
222 }
223 $this->revCount++;
224 $this->report();
225
226 if ( !$this->dryRun ) {
227 call_user_func( $this->logItemCallback, $rev );
228 }
229 }
230
231 function report( $final = false ) {
232 if ( $final xor ( $this->pageCount % $this->reportingInterval == 0 ) ) {
233 $this->showReport();
234 }
235 }
236
237 function showReport() {
238 if ( !$this->mQuiet ) {
239 $delta = microtime( true ) - $this->startTime;
240 if ( $delta ) {
241 $rate = sprintf( "%.2f", $this->pageCount / $delta );
242 $revrate = sprintf( "%.2f", $this->revCount / $delta );
243 } else {
244 $rate = '-';
245 $revrate = '-';
246 }
247 # Logs dumps don't have page tallies
248 if ( $this->pageCount ) {
249 $this->progress( "$this->pageCount ($rate pages/sec $revrate revs/sec)" );
250 } else {
251 $this->progress( "$this->revCount ($revrate revs/sec)" );
252 }
253 }
254 wfWaitForSlaves();
255 }
256
257 function progress( $string ) {
258 fwrite( $this->stderr, $string . "\n" );
259 }
260
261 function importFromFile( $filename ) {
262 if ( preg_match( '/\.gz$/', $filename ) ) {
263 $filename = 'compress.zlib://' . $filename;
264 } elseif ( preg_match( '/\.bz2$/', $filename ) ) {
265 $filename = 'compress.bzip2://' . $filename;
266 } elseif ( preg_match( '/\.7z$/', $filename ) ) {
267 $filename = 'mediawiki.compress.7z://' . $filename;
268 }
269
270 $file = fopen( $filename, 'rt' );
271
272 return $this->importFromHandle( $file );
273 }
274
275 function importFromStdin() {
276 $file = fopen( 'php://stdin', 'rt' );
277 if ( self::posix_isatty( $file ) ) {
278 $this->maybeHelp( true );
279 }
280
281 return $this->importFromHandle( $file );
282 }
283
284 function importFromHandle( $handle ) {
285 $this->startTime = microtime( true );
286
287 $source = new ImportStreamSource( $handle );
288 $importer = new WikiImporter( $source, $this->getConfig() );
289
290 // Updating statistics require a lot of time so disable it
291 $importer->disableStatisticsUpdate();
292
293 if ( $this->hasOption( 'debug' ) ) {
294 $importer->setDebug( true );
295 }
296 if ( $this->hasOption( 'no-updates' ) ) {
297 $importer->setNoUpdates( true );
298 }
299 if ( $this->hasOption( 'rootpage' ) ) {
300 $statusRootPage = $importer->setTargetRootPage( $this->getOption( 'rootpage' ) );
301 if ( !$statusRootPage->isGood() ) {
302 // Die here so that it doesn't print "Done!"
303 $this->error( $statusRootPage->getMessage()->text(), 1 );
304 return false;
305 }
306 }
307 if ( $this->hasOption( 'skip-to' ) ) {
308 $nthPage = (int)$this->getOption( 'skip-to' );
309 $importer->setPageOffset( $nthPage );
310 $this->pageCount = $nthPage - 1;
311 }
312 $importer->setPageCallback( [ $this, 'reportPage' ] );
313 $this->importCallback = $importer->setRevisionCallback(
314 [ $this, 'handleRevision' ] );
315 $this->uploadCallback = $importer->setUploadCallback(
316 [ $this, 'handleUpload' ] );
317 $this->logItemCallback = $importer->setLogItemCallback(
318 [ $this, 'handleLogItem' ] );
319 if ( $this->uploads ) {
320 $importer->setImportUploads( true );
321 }
322 if ( $this->imageBasePath ) {
323 $importer->setImageBasePath( $this->imageBasePath );
324 }
325
326 if ( $this->dryRun ) {
327 $importer->setPageOutCallback( null );
328 }
329
330 return $importer->doImport();
331 }
332 }
333
334 $maintClass = 'BackupReader';
335 require_once RUN_MAINTENANCE_IF_MAIN;