importDump.php 10 KB

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