Merge "Special:Upload should not crash on failing previews"
[mediawiki.git] / includes / import / WikiImporter.php
blob1769924ab06b4a2872ee175e2ac53c3812895cbc
1 <?php
2 /**
3 * MediaWiki page data importer.
5 * Copyright © 2003,2005 Brion Vibber <brion@pobox.com>
6 * https://www.mediawiki.org/
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.
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.
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
23 * @file
24 * @ingroup SpecialPage
26 use MediaWiki\MediaWikiServices;
28 /**
29 * XML file reader for the page data importer.
31 * implements Special:Import
32 * @ingroup SpecialPage
34 class WikiImporter {
35 private $reader = null;
36 private $foreignNamespaces = null;
37 private $mLogItemCallback, $mUploadCallback, $mRevisionCallback, $mPageCallback;
38 private $mSiteInfoCallback, $mPageOutCallback;
39 private $mNoticeCallback, $mDebug;
40 private $mImportUploads, $mImageBasePath;
41 private $mNoUpdates = false;
42 /** @var Config */
43 private $config;
44 /** @var ImportTitleFactory */
45 private $importTitleFactory;
46 /** @var array */
47 private $countableCache = [];
48 /** @var bool */
49 private $disableStatisticsUpdate = false;
51 /**
52 * Creates an ImportXMLReader drawing from the source provided
53 * @param ImportSource $source
54 * @param Config $config
55 * @throws Exception
57 function __construct( ImportSource $source, Config $config = null ) {
58 if ( !class_exists( 'XMLReader' ) ) {
59 throw new Exception( 'Import requires PHP to have been compiled with libxml support' );
62 $this->reader = new XMLReader();
63 if ( !$config ) {
64 wfDeprecated( __METHOD__ . ' without a Config instance', '1.25' );
65 $config = MediaWikiServices::getInstance()->getMainConfig();
67 $this->config = $config;
69 if ( !in_array( 'uploadsource', stream_get_wrappers() ) ) {
70 stream_wrapper_register( 'uploadsource', 'UploadSourceAdapter' );
72 $id = UploadSourceAdapter::registerSource( $source );
74 // Enable the entity loader, as it is needed for loading external URLs via
75 // XMLReader::open (T86036)
76 $oldDisable = libxml_disable_entity_loader( false );
77 if ( defined( 'LIBXML_PARSEHUGE' ) ) {
78 $status = $this->reader->open( "uploadsource://$id", null, LIBXML_PARSEHUGE );
79 } else {
80 $status = $this->reader->open( "uploadsource://$id" );
82 if ( !$status ) {
83 $error = libxml_get_last_error();
84 libxml_disable_entity_loader( $oldDisable );
85 throw new MWException( 'Encountered an internal error while initializing WikiImporter object: ' .
86 $error->message );
88 libxml_disable_entity_loader( $oldDisable );
90 // Default callbacks
91 $this->setPageCallback( [ $this, 'beforeImportPage' ] );
92 $this->setRevisionCallback( [ $this, "importRevision" ] );
93 $this->setUploadCallback( [ $this, 'importUpload' ] );
94 $this->setLogItemCallback( [ $this, 'importLogItem' ] );
95 $this->setPageOutCallback( [ $this, 'finishImportPage' ] );
97 $this->importTitleFactory = new NaiveImportTitleFactory();
101 * @return null|XMLReader
103 public function getReader() {
104 return $this->reader;
107 public function throwXmlError( $err ) {
108 $this->debug( "FAILURE: $err" );
109 wfDebug( "WikiImporter XML error: $err\n" );
112 public function debug( $data ) {
113 if ( $this->mDebug ) {
114 wfDebug( "IMPORT: $data\n" );
118 public function warn( $data ) {
119 wfDebug( "IMPORT: $data\n" );
122 public function notice( $msg /*, $param, ...*/ ) {
123 $params = func_get_args();
124 array_shift( $params );
126 if ( is_callable( $this->mNoticeCallback ) ) {
127 call_user_func( $this->mNoticeCallback, $msg, $params );
128 } else { # No ImportReporter -> CLI
129 echo wfMessage( $msg, $params )->text() . "\n";
134 * Set debug mode...
135 * @param bool $debug
137 function setDebug( $debug ) {
138 $this->mDebug = $debug;
142 * Set 'no updates' mode. In this mode, the link tables will not be updated by the importer
143 * @param bool $noupdates
145 function setNoUpdates( $noupdates ) {
146 $this->mNoUpdates = $noupdates;
150 * Set a callback that displays notice messages
152 * @param callable $callback
153 * @return callable
155 public function setNoticeCallback( $callback ) {
156 return wfSetVar( $this->mNoticeCallback, $callback );
160 * Sets the action to perform as each new page in the stream is reached.
161 * @param callable $callback
162 * @return callable
164 public function setPageCallback( $callback ) {
165 $previous = $this->mPageCallback;
166 $this->mPageCallback = $callback;
167 return $previous;
171 * Sets the action to perform as each page in the stream is completed.
172 * Callback accepts the page title (as a Title object), a second object
173 * with the original title form (in case it's been overridden into a
174 * local namespace), and a count of revisions.
176 * @param callable $callback
177 * @return callable
179 public function setPageOutCallback( $callback ) {
180 $previous = $this->mPageOutCallback;
181 $this->mPageOutCallback = $callback;
182 return $previous;
186 * Sets the action to perform as each page revision is reached.
187 * @param callable $callback
188 * @return callable
190 public function setRevisionCallback( $callback ) {
191 $previous = $this->mRevisionCallback;
192 $this->mRevisionCallback = $callback;
193 return $previous;
197 * Sets the action to perform as each file upload version is reached.
198 * @param callable $callback
199 * @return callable
201 public function setUploadCallback( $callback ) {
202 $previous = $this->mUploadCallback;
203 $this->mUploadCallback = $callback;
204 return $previous;
208 * Sets the action to perform as each log item reached.
209 * @param callable $callback
210 * @return callable
212 public function setLogItemCallback( $callback ) {
213 $previous = $this->mLogItemCallback;
214 $this->mLogItemCallback = $callback;
215 return $previous;
219 * Sets the action to perform when site info is encountered
220 * @param callable $callback
221 * @return callable
223 public function setSiteInfoCallback( $callback ) {
224 $previous = $this->mSiteInfoCallback;
225 $this->mSiteInfoCallback = $callback;
226 return $previous;
230 * Sets the factory object to use to convert ForeignTitle objects into local
231 * Title objects
232 * @param ImportTitleFactory $factory
234 public function setImportTitleFactory( $factory ) {
235 $this->importTitleFactory = $factory;
239 * Set a target namespace to override the defaults
240 * @param null|int $namespace
241 * @return bool
243 public function setTargetNamespace( $namespace ) {
244 if ( is_null( $namespace ) ) {
245 // Don't override namespaces
246 $this->setImportTitleFactory( new NaiveImportTitleFactory() );
247 return true;
248 } elseif (
249 $namespace >= 0 &&
250 MWNamespace::exists( intval( $namespace ) )
252 $namespace = intval( $namespace );
253 $this->setImportTitleFactory( new NamespaceImportTitleFactory( $namespace ) );
254 return true;
255 } else {
256 return false;
261 * Set a target root page under which all pages are imported
262 * @param null|string $rootpage
263 * @return Status
265 public function setTargetRootPage( $rootpage ) {
266 $status = Status::newGood();
267 if ( is_null( $rootpage ) ) {
268 // No rootpage
269 $this->setImportTitleFactory( new NaiveImportTitleFactory() );
270 } elseif ( $rootpage !== '' ) {
271 $rootpage = rtrim( $rootpage, '/' ); // avoid double slashes
272 $title = Title::newFromText( $rootpage );
274 if ( !$title || $title->isExternal() ) {
275 $status->fatal( 'import-rootpage-invalid' );
276 } else {
277 if ( !MWNamespace::hasSubpages( $title->getNamespace() ) ) {
278 global $wgContLang;
280 $displayNSText = $title->getNamespace() == NS_MAIN
281 ? wfMessage( 'blanknamespace' )->text()
282 : $wgContLang->getNsText( $title->getNamespace() );
283 $status->fatal( 'import-rootpage-nosubpage', $displayNSText );
284 } else {
285 // set namespace to 'all', so the namespace check in processTitle() can pass
286 $this->setTargetNamespace( null );
287 $this->setImportTitleFactory( new SubpageImportTitleFactory( $title ) );
291 return $status;
295 * @param string $dir
297 public function setImageBasePath( $dir ) {
298 $this->mImageBasePath = $dir;
302 * @param bool $import
304 public function setImportUploads( $import ) {
305 $this->mImportUploads = $import;
309 * Statistics update can cause a lot of time
310 * @since 1.29
312 public function disableStatisticsUpdate() {
313 $this->disableStatisticsUpdate = true;
317 * Default per-page callback. Sets up some things related to site statistics
318 * @param array $titleAndForeignTitle Two-element array, with Title object at
319 * index 0 and ForeignTitle object at index 1
320 * @return bool
322 public function beforeImportPage( $titleAndForeignTitle ) {
323 $title = $titleAndForeignTitle[0];
324 $page = WikiPage::factory( $title );
325 $this->countableCache['title_' . $title->getPrefixedText()] = $page->isCountable();
326 return true;
330 * Default per-revision callback, performs the import.
331 * @param WikiRevision $revision
332 * @return bool
334 public function importRevision( $revision ) {
335 if ( !$revision->getContentHandler()->canBeUsedOn( $revision->getTitle() ) ) {
336 $this->notice( 'import-error-bad-location',
337 $revision->getTitle()->getPrefixedText(),
338 $revision->getID(),
339 $revision->getModel(),
340 $revision->getFormat() );
342 return false;
345 try {
346 return $revision->importOldRevision();
347 } catch ( MWContentSerializationException $ex ) {
348 $this->notice( 'import-error-unserialize',
349 $revision->getTitle()->getPrefixedText(),
350 $revision->getID(),
351 $revision->getModel(),
352 $revision->getFormat() );
355 return false;
359 * Default per-revision callback, performs the import.
360 * @param WikiRevision $revision
361 * @return bool
363 public function importLogItem( $revision ) {
364 return $revision->importLogItem();
368 * Dummy for now...
369 * @param WikiRevision $revision
370 * @return bool
372 public function importUpload( $revision ) {
373 return $revision->importUpload();
377 * Mostly for hook use
378 * @param Title $title
379 * @param ForeignTitle $foreignTitle
380 * @param int $revCount
381 * @param int $sRevCount
382 * @param array $pageInfo
383 * @return bool
385 public function finishImportPage( $title, $foreignTitle, $revCount,
386 $sRevCount, $pageInfo ) {
388 // Update article count statistics (T42009)
389 // The normal counting logic in WikiPage->doEditUpdates() is designed for
390 // one-revision-at-a-time editing, not bulk imports. In this situation it
391 // suffers from issues of replica DB lag. We let WikiPage handle the total page
392 // and revision count, and we implement our own custom logic for the
393 // article (content page) count.
394 if ( !$this->disableStatisticsUpdate ) {
395 $page = WikiPage::factory( $title );
396 $page->loadPageData( 'fromdbmaster' );
397 $content = $page->getContent();
398 if ( $content === null ) {
399 wfDebug( __METHOD__ . ': Skipping article count adjustment for ' . $title .
400 ' because WikiPage::getContent() returned null' );
401 } else {
402 $editInfo = $page->prepareContentForEdit( $content );
403 $countKey = 'title_' . $title->getPrefixedText();
404 $countable = $page->isCountable( $editInfo );
405 if ( array_key_exists( $countKey, $this->countableCache ) &&
406 $countable != $this->countableCache[$countKey] ) {
407 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [
408 'articles' => ( (int)$countable - (int)$this->countableCache[$countKey] )
409 ] ) );
414 $args = func_get_args();
415 return Hooks::run( 'AfterImportPage', $args );
419 * Alternate per-revision callback, for debugging.
420 * @param WikiRevision $revision
422 public function debugRevisionHandler( &$revision ) {
423 $this->debug( "Got revision:" );
424 if ( is_object( $revision->title ) ) {
425 $this->debug( "-- Title: " . $revision->title->getPrefixedText() );
426 } else {
427 $this->debug( "-- Title: <invalid>" );
429 $this->debug( "-- User: " . $revision->user_text );
430 $this->debug( "-- Timestamp: " . $revision->timestamp );
431 $this->debug( "-- Comment: " . $revision->comment );
432 $this->debug( "-- Text: " . $revision->text );
436 * Notify the callback function of site info
437 * @param array $siteInfo
438 * @return bool|mixed
440 private function siteInfoCallback( $siteInfo ) {
441 if ( isset( $this->mSiteInfoCallback ) ) {
442 return call_user_func_array( $this->mSiteInfoCallback,
443 [ $siteInfo, $this ] );
444 } else {
445 return false;
450 * Notify the callback function when a new "<page>" is reached.
451 * @param Title $title
453 function pageCallback( $title ) {
454 if ( isset( $this->mPageCallback ) ) {
455 call_user_func( $this->mPageCallback, $title );
460 * Notify the callback function when a "</page>" is closed.
461 * @param Title $title
462 * @param ForeignTitle $foreignTitle
463 * @param int $revCount
464 * @param int $sucCount Number of revisions for which callback returned true
465 * @param array $pageInfo Associative array of page information
467 private function pageOutCallback( $title, $foreignTitle, $revCount,
468 $sucCount, $pageInfo ) {
469 if ( isset( $this->mPageOutCallback ) ) {
470 $args = func_get_args();
471 call_user_func_array( $this->mPageOutCallback, $args );
476 * Notify the callback function of a revision
477 * @param WikiRevision $revision
478 * @return bool|mixed
480 private function revisionCallback( $revision ) {
481 if ( isset( $this->mRevisionCallback ) ) {
482 return call_user_func_array( $this->mRevisionCallback,
483 [ $revision, $this ] );
484 } else {
485 return false;
490 * Notify the callback function of a new log item
491 * @param WikiRevision $revision
492 * @return bool|mixed
494 private function logItemCallback( $revision ) {
495 if ( isset( $this->mLogItemCallback ) ) {
496 return call_user_func_array( $this->mLogItemCallback,
497 [ $revision, $this ] );
498 } else {
499 return false;
504 * Retrieves the contents of the named attribute of the current element.
505 * @param string $attr The name of the attribute
506 * @return string The value of the attribute or an empty string if it is not set in the current
507 * element.
509 public function nodeAttribute( $attr ) {
510 return $this->reader->getAttribute( $attr );
514 * Shouldn't something like this be built-in to XMLReader?
515 * Fetches text contents of the current element, assuming
516 * no sub-elements or such scary things.
517 * @return string
518 * @access private
520 public function nodeContents() {
521 if ( $this->reader->isEmptyElement ) {
522 return "";
524 $buffer = "";
525 while ( $this->reader->read() ) {
526 switch ( $this->reader->nodeType ) {
527 case XMLReader::TEXT:
528 case XMLReader::CDATA:
529 case XMLReader::SIGNIFICANT_WHITESPACE:
530 $buffer .= $this->reader->value;
531 break;
532 case XMLReader::END_ELEMENT:
533 return $buffer;
537 $this->reader->close();
538 return '';
542 * Primary entry point
543 * @throws MWException
544 * @return bool
546 public function doImport() {
547 // Calls to reader->read need to be wrapped in calls to
548 // libxml_disable_entity_loader() to avoid local file
549 // inclusion attacks (bug 46932).
550 $oldDisable = libxml_disable_entity_loader( true );
551 $this->reader->read();
553 if ( $this->reader->localName != 'mediawiki' ) {
554 libxml_disable_entity_loader( $oldDisable );
555 throw new MWException( "Expected <mediawiki> tag, got " .
556 $this->reader->localName );
558 $this->debug( "<mediawiki> tag is correct." );
560 $this->debug( "Starting primary dump processing loop." );
562 $keepReading = $this->reader->read();
563 $skip = false;
564 $rethrow = null;
565 try {
566 while ( $keepReading ) {
567 $tag = $this->reader->localName;
568 $type = $this->reader->nodeType;
570 if ( !Hooks::run( 'ImportHandleToplevelXMLTag', [ $this ] ) ) {
571 // Do nothing
572 } elseif ( $tag == 'mediawiki' && $type == XMLReader::END_ELEMENT ) {
573 break;
574 } elseif ( $tag == 'siteinfo' ) {
575 $this->handleSiteInfo();
576 } elseif ( $tag == 'page' ) {
577 $this->handlePage();
578 } elseif ( $tag == 'logitem' ) {
579 $this->handleLogItem();
580 } elseif ( $tag != '#text' ) {
581 $this->warn( "Unhandled top-level XML tag $tag" );
583 $skip = true;
586 if ( $skip ) {
587 $keepReading = $this->reader->next();
588 $skip = false;
589 $this->debug( "Skip" );
590 } else {
591 $keepReading = $this->reader->read();
594 } catch ( Exception $ex ) {
595 $rethrow = $ex;
598 // finally
599 libxml_disable_entity_loader( $oldDisable );
600 $this->reader->close();
602 if ( $rethrow ) {
603 throw $rethrow;
606 return true;
609 private function handleSiteInfo() {
610 $this->debug( "Enter site info handler." );
611 $siteInfo = [];
613 // Fields that can just be stuffed in the siteInfo object
614 $normalFields = [ 'sitename', 'base', 'generator', 'case' ];
616 while ( $this->reader->read() ) {
617 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
618 $this->reader->localName == 'siteinfo' ) {
619 break;
622 $tag = $this->reader->localName;
624 if ( $tag == 'namespace' ) {
625 $this->foreignNamespaces[$this->nodeAttribute( 'key' )] =
626 $this->nodeContents();
627 } elseif ( in_array( $tag, $normalFields ) ) {
628 $siteInfo[$tag] = $this->nodeContents();
632 $siteInfo['_namespaces'] = $this->foreignNamespaces;
633 $this->siteInfoCallback( $siteInfo );
636 private function handleLogItem() {
637 $this->debug( "Enter log item handler." );
638 $logInfo = [];
640 // Fields that can just be stuffed in the pageInfo object
641 $normalFields = [ 'id', 'comment', 'type', 'action', 'timestamp',
642 'logtitle', 'params' ];
644 while ( $this->reader->read() ) {
645 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
646 $this->reader->localName == 'logitem' ) {
647 break;
650 $tag = $this->reader->localName;
652 if ( !Hooks::run( 'ImportHandleLogItemXMLTag', [
653 $this, $logInfo
654 ] ) ) {
655 // Do nothing
656 } elseif ( in_array( $tag, $normalFields ) ) {
657 $logInfo[$tag] = $this->nodeContents();
658 } elseif ( $tag == 'contributor' ) {
659 $logInfo['contributor'] = $this->handleContributor();
660 } elseif ( $tag != '#text' ) {
661 $this->warn( "Unhandled log-item XML tag $tag" );
665 $this->processLogItem( $logInfo );
669 * @param array $logInfo
670 * @return bool|mixed
672 private function processLogItem( $logInfo ) {
674 $revision = new WikiRevision( $this->config );
676 if ( isset( $logInfo['id'] ) ) {
677 $revision->setID( $logInfo['id'] );
679 $revision->setType( $logInfo['type'] );
680 $revision->setAction( $logInfo['action'] );
681 if ( isset( $logInfo['timestamp'] ) ) {
682 $revision->setTimestamp( $logInfo['timestamp'] );
684 if ( isset( $logInfo['params'] ) ) {
685 $revision->setParams( $logInfo['params'] );
687 if ( isset( $logInfo['logtitle'] ) ) {
688 // @todo Using Title for non-local titles is a recipe for disaster.
689 // We should use ForeignTitle here instead.
690 $revision->setTitle( Title::newFromText( $logInfo['logtitle'] ) );
693 $revision->setNoUpdates( $this->mNoUpdates );
695 if ( isset( $logInfo['comment'] ) ) {
696 $revision->setComment( $logInfo['comment'] );
699 if ( isset( $logInfo['contributor']['ip'] ) ) {
700 $revision->setUserIP( $logInfo['contributor']['ip'] );
703 if ( !isset( $logInfo['contributor']['username'] ) ) {
704 $revision->setUsername( 'Unknown user' );
705 } else {
706 $revision->setUsername( $logInfo['contributor']['username'] );
709 return $this->logItemCallback( $revision );
712 private function handlePage() {
713 // Handle page data.
714 $this->debug( "Enter page handler." );
715 $pageInfo = [ 'revisionCount' => 0, 'successfulRevisionCount' => 0 ];
717 // Fields that can just be stuffed in the pageInfo object
718 $normalFields = [ 'title', 'ns', 'id', 'redirect', 'restrictions' ];
720 $skip = false;
721 $badTitle = false;
723 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
724 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
725 $this->reader->localName == 'page' ) {
726 break;
729 $skip = false;
731 $tag = $this->reader->localName;
733 if ( $badTitle ) {
734 // The title is invalid, bail out of this page
735 $skip = true;
736 } elseif ( !Hooks::run( 'ImportHandlePageXMLTag', [ $this,
737 &$pageInfo ] ) ) {
738 // Do nothing
739 } elseif ( in_array( $tag, $normalFields ) ) {
740 // An XML snippet:
741 // <page>
742 // <id>123</id>
743 // <title>Page</title>
744 // <redirect title="NewTitle"/>
745 // ...
746 // Because the redirect tag is built differently, we need special handling for that case.
747 if ( $tag == 'redirect' ) {
748 $pageInfo[$tag] = $this->nodeAttribute( 'title' );
749 } else {
750 $pageInfo[$tag] = $this->nodeContents();
752 } elseif ( $tag == 'revision' || $tag == 'upload' ) {
753 if ( !isset( $title ) ) {
754 $title = $this->processTitle( $pageInfo['title'],
755 isset( $pageInfo['ns'] ) ? $pageInfo['ns'] : null );
757 // $title is either an array of two titles or false.
758 if ( is_array( $title ) ) {
759 $this->pageCallback( $title );
760 list( $pageInfo['_title'], $foreignTitle ) = $title;
761 } else {
762 $badTitle = true;
763 $skip = true;
767 if ( $title ) {
768 if ( $tag == 'revision' ) {
769 $this->handleRevision( $pageInfo );
770 } else {
771 $this->handleUpload( $pageInfo );
774 } elseif ( $tag != '#text' ) {
775 $this->warn( "Unhandled page XML tag $tag" );
776 $skip = true;
780 // @note $pageInfo is only set if a valid $title is processed above with
781 // no error. If we have a valid $title, then pageCallback is called
782 // above, $pageInfo['title'] is set and we do pageOutCallback here.
783 // If $pageInfo['_title'] is not set, then $foreignTitle is also not
784 // set since they both come from $title above.
785 if ( array_key_exists( '_title', $pageInfo ) ) {
786 $this->pageOutCallback( $pageInfo['_title'], $foreignTitle,
787 $pageInfo['revisionCount'],
788 $pageInfo['successfulRevisionCount'],
789 $pageInfo );
794 * @param array $pageInfo
796 private function handleRevision( &$pageInfo ) {
797 $this->debug( "Enter revision handler" );
798 $revisionInfo = [];
800 $normalFields = [ 'id', 'timestamp', 'comment', 'minor', 'model', 'format', 'text' ];
802 $skip = false;
804 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
805 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
806 $this->reader->localName == 'revision' ) {
807 break;
810 $tag = $this->reader->localName;
812 if ( !Hooks::run( 'ImportHandleRevisionXMLTag', [
813 $this, $pageInfo, $revisionInfo
814 ] ) ) {
815 // Do nothing
816 } elseif ( in_array( $tag, $normalFields ) ) {
817 $revisionInfo[$tag] = $this->nodeContents();
818 } elseif ( $tag == 'contributor' ) {
819 $revisionInfo['contributor'] = $this->handleContributor();
820 } elseif ( $tag != '#text' ) {
821 $this->warn( "Unhandled revision XML tag $tag" );
822 $skip = true;
826 $pageInfo['revisionCount']++;
827 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
828 $pageInfo['successfulRevisionCount']++;
833 * @param array $pageInfo
834 * @param array $revisionInfo
835 * @return bool|mixed
837 private function processRevision( $pageInfo, $revisionInfo ) {
838 global $wgMaxArticleSize;
840 // Make sure revisions won't violate $wgMaxArticleSize, which could lead to
841 // database errors and instability. Testing for revisions with only listed
842 // content models, as other content models might use serialization formats
843 // which aren't checked against $wgMaxArticleSize.
844 if ( ( !isset( $revisionInfo['model'] ) ||
845 in_array( $revisionInfo['model'], [
846 'wikitext',
847 'css',
848 'json',
849 'javascript',
850 'text',
852 ] ) ) &&
853 strlen( $revisionInfo['text'] ) > $wgMaxArticleSize * 1024
855 throw new MWException( 'The text of ' .
856 ( isset( $revisionInfo['id'] ) ?
857 "the revision with ID $revisionInfo[id]" :
858 'a revision'
859 ) . " exceeds the maximum allowable size ($wgMaxArticleSize KB)" );
862 $revision = new WikiRevision( $this->config );
864 if ( isset( $revisionInfo['id'] ) ) {
865 $revision->setID( $revisionInfo['id'] );
867 if ( isset( $revisionInfo['model'] ) ) {
868 $revision->setModel( $revisionInfo['model'] );
870 if ( isset( $revisionInfo['format'] ) ) {
871 $revision->setFormat( $revisionInfo['format'] );
873 $revision->setTitle( $pageInfo['_title'] );
875 if ( isset( $revisionInfo['text'] ) ) {
876 $handler = $revision->getContentHandler();
877 $text = $handler->importTransform(
878 $revisionInfo['text'],
879 $revision->getFormat() );
881 $revision->setText( $text );
883 if ( isset( $revisionInfo['timestamp'] ) ) {
884 $revision->setTimestamp( $revisionInfo['timestamp'] );
885 } else {
886 $revision->setTimestamp( wfTimestampNow() );
889 if ( isset( $revisionInfo['comment'] ) ) {
890 $revision->setComment( $revisionInfo['comment'] );
893 if ( isset( $revisionInfo['minor'] ) ) {
894 $revision->setMinor( true );
896 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
897 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
898 } elseif ( isset( $revisionInfo['contributor']['username'] ) ) {
899 $revision->setUsername( $revisionInfo['contributor']['username'] );
900 } else {
901 $revision->setUsername( 'Unknown user' );
903 $revision->setNoUpdates( $this->mNoUpdates );
905 return $this->revisionCallback( $revision );
909 * @param array $pageInfo
910 * @return mixed
912 private function handleUpload( &$pageInfo ) {
913 $this->debug( "Enter upload handler" );
914 $uploadInfo = [];
916 $normalFields = [ 'timestamp', 'comment', 'filename', 'text',
917 'src', 'size', 'sha1base36', 'archivename', 'rel' ];
919 $skip = false;
921 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
922 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
923 $this->reader->localName == 'upload' ) {
924 break;
927 $tag = $this->reader->localName;
929 if ( !Hooks::run( 'ImportHandleUploadXMLTag', [
930 $this, $pageInfo
931 ] ) ) {
932 // Do nothing
933 } elseif ( in_array( $tag, $normalFields ) ) {
934 $uploadInfo[$tag] = $this->nodeContents();
935 } elseif ( $tag == 'contributor' ) {
936 $uploadInfo['contributor'] = $this->handleContributor();
937 } elseif ( $tag == 'contents' ) {
938 $contents = $this->nodeContents();
939 $encoding = $this->reader->getAttribute( 'encoding' );
940 if ( $encoding === 'base64' ) {
941 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
942 $uploadInfo['isTempSrc'] = true;
944 } elseif ( $tag != '#text' ) {
945 $this->warn( "Unhandled upload XML tag $tag" );
946 $skip = true;
950 if ( $this->mImageBasePath && isset( $uploadInfo['rel'] ) ) {
951 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
952 if ( file_exists( $path ) ) {
953 $uploadInfo['fileSrc'] = $path;
954 $uploadInfo['isTempSrc'] = false;
958 if ( $this->mImportUploads ) {
959 return $this->processUpload( $pageInfo, $uploadInfo );
964 * @param string $contents
965 * @return string
967 private function dumpTemp( $contents ) {
968 $filename = tempnam( wfTempDir(), 'importupload' );
969 file_put_contents( $filename, $contents );
970 return $filename;
974 * @param array $pageInfo
975 * @param array $uploadInfo
976 * @return mixed
978 private function processUpload( $pageInfo, $uploadInfo ) {
979 $revision = new WikiRevision( $this->config );
980 $text = isset( $uploadInfo['text'] ) ? $uploadInfo['text'] : '';
982 $revision->setTitle( $pageInfo['_title'] );
983 $revision->setID( $pageInfo['id'] );
984 $revision->setTimestamp( $uploadInfo['timestamp'] );
985 $revision->setText( $text );
986 $revision->setFilename( $uploadInfo['filename'] );
987 if ( isset( $uploadInfo['archivename'] ) ) {
988 $revision->setArchiveName( $uploadInfo['archivename'] );
990 $revision->setSrc( $uploadInfo['src'] );
991 if ( isset( $uploadInfo['fileSrc'] ) ) {
992 $revision->setFileSrc( $uploadInfo['fileSrc'],
993 !empty( $uploadInfo['isTempSrc'] ) );
995 if ( isset( $uploadInfo['sha1base36'] ) ) {
996 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
998 $revision->setSize( intval( $uploadInfo['size'] ) );
999 $revision->setComment( $uploadInfo['comment'] );
1001 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
1002 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
1004 if ( isset( $uploadInfo['contributor']['username'] ) ) {
1005 $revision->setUsername( $uploadInfo['contributor']['username'] );
1007 $revision->setNoUpdates( $this->mNoUpdates );
1009 return call_user_func( $this->mUploadCallback, $revision );
1013 * @return array
1015 private function handleContributor() {
1016 $fields = [ 'id', 'ip', 'username' ];
1017 $info = [];
1019 if ( $this->reader->isEmptyElement ) {
1020 return $info;
1022 while ( $this->reader->read() ) {
1023 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
1024 $this->reader->localName == 'contributor' ) {
1025 break;
1028 $tag = $this->reader->localName;
1030 if ( in_array( $tag, $fields ) ) {
1031 $info[$tag] = $this->nodeContents();
1035 return $info;
1039 * @param string $text
1040 * @param string|null $ns
1041 * @return array|bool
1043 private function processTitle( $text, $ns = null ) {
1044 if ( is_null( $this->foreignNamespaces ) ) {
1045 $foreignTitleFactory = new NaiveForeignTitleFactory();
1046 } else {
1047 $foreignTitleFactory = new NamespaceAwareForeignTitleFactory(
1048 $this->foreignNamespaces );
1051 $foreignTitle = $foreignTitleFactory->createForeignTitle( $text,
1052 intval( $ns ) );
1054 $title = $this->importTitleFactory->createTitleFromForeignTitle(
1055 $foreignTitle );
1057 $commandLineMode = $this->config->get( 'CommandLineMode' );
1058 if ( is_null( $title ) ) {
1059 # Invalid page title? Ignore the page
1060 $this->notice( 'import-error-invalid', $foreignTitle->getFullText() );
1061 return false;
1062 } elseif ( $title->isExternal() ) {
1063 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
1064 return false;
1065 } elseif ( !$title->canExist() ) {
1066 $this->notice( 'import-error-special', $title->getPrefixedText() );
1067 return false;
1068 } elseif ( !$title->userCan( 'edit' ) && !$commandLineMode ) {
1069 # Do not import if the importing wiki user cannot edit this page
1070 $this->notice( 'import-error-edit', $title->getPrefixedText() );
1071 return false;
1072 } elseif ( !$title->exists() && !$title->userCan( 'create' ) && !$commandLineMode ) {
1073 # Do not import if the importing wiki user cannot create this page
1074 $this->notice( 'import-error-create', $title->getPrefixedText() );
1075 return false;
1078 return [ $title, $foreignTitle ];