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