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
24 * @ingroup SpecialPage
27 use MediaWiki\MediaWikiServices
;
30 * XML file reader for the page data importer.
32 * implements Special:Import
33 * @ingroup SpecialPage
36 private $reader = null;
37 private $foreignNamespaces = null;
38 private $mLogItemCallback, $mUploadCallback, $mRevisionCallback, $mPageCallback;
39 private $mSiteInfoCallback, $mPageOutCallback;
40 private $mNoticeCallback, $mDebug;
41 private $mImportUploads, $mImageBasePath;
42 private $mNoUpdates = false;
43 private $pageOffset = 0;
46 /** @var ImportTitleFactory */
47 private $importTitleFactory;
49 private $countableCache = [];
51 private $disableStatisticsUpdate = false;
52 /** @var ExternalUserNames */
53 private $externalUserNames;
56 * Creates an ImportXMLReader drawing from the source provided
57 * @param ImportSource $source
58 * @param Config $config
61 function __construct( ImportSource
$source, Config
$config ) {
62 if ( !class_exists( 'XMLReader' ) ) {
63 throw new Exception( 'Import requires PHP to have been compiled with libxml support' );
66 $this->reader
= new XMLReader();
67 $this->config
= $config;
69 if ( !in_array( 'uploadsource', stream_get_wrappers() ) ) {
70 stream_wrapper_register( 'uploadsource', UploadSourceAdapter
::class );
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
);
80 $status = $this->reader
->open( "uploadsource://$id" );
83 $error = libxml_get_last_error();
84 libxml_disable_entity_loader( $oldDisable );
85 throw new MWException( 'Encountered an internal error while initializing WikiImporter object: ' .
88 libxml_disable_entity_loader( $oldDisable );
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();
98 $this->externalUserNames
= new ExternalUserNames( 'imported', false );
102 * @return null|XMLReader
104 public function getReader() {
105 return $this->reader
;
108 public function throwXmlError( $err ) {
109 $this->debug( "FAILURE: $err" );
110 wfDebug( "WikiImporter XML error: $err\n" );
113 public function debug( $data ) {
114 if ( $this->mDebug
) {
115 wfDebug( "IMPORT: $data\n" );
119 public function warn( $data ) {
120 wfDebug( "IMPORT: $data\n" );
123 public function notice( $msg, ...$params ) {
124 if ( is_callable( $this->mNoticeCallback
) ) {
125 call_user_func( $this->mNoticeCallback
, $msg, $params );
126 } else { # No ImportReporter -> CLI
127 // T177997: the command line importers should call setNoticeCallback()
128 // for their own custom callback to echo the notice
129 wfDebug( wfMessage( $msg, $params )->text() . "\n" );
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 * Sets 'pageOffset' value. So it will skip the first n-1 pages
151 * and start from the nth page. It's 1-based indexing.
152 * @param int $nthPage
155 function setPageOffset( $nthPage ) {
156 $this->pageOffset
= $nthPage;
160 * Set a callback that displays notice messages
162 * @param callable $callback
165 public function setNoticeCallback( $callback ) {
166 return wfSetVar( $this->mNoticeCallback
, $callback );
170 * Sets the action to perform as each new page in the stream is reached.
171 * @param callable $callback
174 public function setPageCallback( $callback ) {
175 $previous = $this->mPageCallback
;
176 $this->mPageCallback
= $callback;
181 * Sets the action to perform as each page in the stream is completed.
182 * Callback accepts the page title (as a Title object), a second object
183 * with the original title form (in case it's been overridden into a
184 * local namespace), and a count of revisions.
186 * @param callable $callback
189 public function setPageOutCallback( $callback ) {
190 $previous = $this->mPageOutCallback
;
191 $this->mPageOutCallback
= $callback;
196 * Sets the action to perform as each page revision is reached.
197 * @param callable $callback
200 public function setRevisionCallback( $callback ) {
201 $previous = $this->mRevisionCallback
;
202 $this->mRevisionCallback
= $callback;
207 * Sets the action to perform as each file upload version is reached.
208 * @param callable $callback
211 public function setUploadCallback( $callback ) {
212 $previous = $this->mUploadCallback
;
213 $this->mUploadCallback
= $callback;
218 * Sets the action to perform as each log item reached.
219 * @param callable $callback
222 public function setLogItemCallback( $callback ) {
223 $previous = $this->mLogItemCallback
;
224 $this->mLogItemCallback
= $callback;
229 * Sets the action to perform when site info is encountered
230 * @param callable $callback
233 public function setSiteInfoCallback( $callback ) {
234 $previous = $this->mSiteInfoCallback
;
235 $this->mSiteInfoCallback
= $callback;
240 * Sets the factory object to use to convert ForeignTitle objects into local
242 * @param ImportTitleFactory $factory
244 public function setImportTitleFactory( $factory ) {
245 $this->importTitleFactory
= $factory;
249 * Set a target namespace to override the defaults
250 * @param null|int $namespace
253 public function setTargetNamespace( $namespace ) {
254 if ( is_null( $namespace ) ) {
255 // Don't override namespaces
256 $this->setImportTitleFactory( new NaiveImportTitleFactory() );
260 MediaWikiServices
::getInstance()->getNamespaceInfo()->exists( intval( $namespace ) )
262 $namespace = intval( $namespace );
263 $this->setImportTitleFactory( new NamespaceImportTitleFactory( $namespace ) );
271 * Set a target root page under which all pages are imported
272 * @param null|string $rootpage
275 public function setTargetRootPage( $rootpage ) {
276 $status = Status
::newGood();
277 if ( is_null( $rootpage ) ) {
279 $this->setImportTitleFactory( new NaiveImportTitleFactory() );
280 } elseif ( $rootpage !== '' ) {
281 $rootpage = rtrim( $rootpage, '/' ); // avoid double slashes
282 $title = Title
::newFromText( $rootpage );
284 if ( !$title ||
$title->isExternal() ) {
285 $status->fatal( 'import-rootpage-invalid' );
287 !MediaWikiServices
::getInstance()->getNamespaceInfo()->
288 hasSubpages( $title->getNamespace() )
290 $displayNSText = $title->getNamespace() == NS_MAIN
291 ?
wfMessage( 'blanknamespace' )->text()
292 : MediaWikiServices
::getInstance()->getContentLanguage()->
293 getNsText( $title->getNamespace() );
294 $status->fatal( 'import-rootpage-nosubpage', $displayNSText );
296 // set namespace to 'all', so the namespace check in processTitle() can pass
297 $this->setTargetNamespace( null );
298 $this->setImportTitleFactory( new SubpageImportTitleFactory( $title ) );
307 public function setImageBasePath( $dir ) {
308 $this->mImageBasePath
= $dir;
312 * @param bool $import
314 public function setImportUploads( $import ) {
315 $this->mImportUploads
= $import;
320 * @param string $usernamePrefix Prefix to apply to unknown (and possibly also known) usernames
321 * @param bool $assignKnownUsers Whether to apply the prefix to usernames that exist locally
323 public function setUsernamePrefix( $usernamePrefix, $assignKnownUsers ) {
324 $this->externalUserNames
= new ExternalUserNames( $usernamePrefix, $assignKnownUsers );
328 * Statistics update can cause a lot of time
331 public function disableStatisticsUpdate() {
332 $this->disableStatisticsUpdate
= true;
336 * Default per-page callback. Sets up some things related to site statistics
337 * @param array $titleAndForeignTitle Two-element array, with Title object at
338 * index 0 and ForeignTitle object at index 1
341 public function beforeImportPage( $titleAndForeignTitle ) {
342 $title = $titleAndForeignTitle[0];
343 $page = WikiPage
::factory( $title );
344 $this->countableCache
['title_' . $title->getPrefixedText()] = $page->isCountable();
349 * Default per-revision callback, performs the import.
350 * @param WikiRevision $revision
353 public function importRevision( $revision ) {
354 if ( !$revision->getContentHandler()->canBeUsedOn( $revision->getTitle() ) ) {
355 $this->notice( 'import-error-bad-location',
356 $revision->getTitle()->getPrefixedText(),
358 $revision->getModel(),
359 $revision->getFormat() );
365 return $revision->importOldRevision();
366 } catch ( MWContentSerializationException
$ex ) {
367 $this->notice( 'import-error-unserialize',
368 $revision->getTitle()->getPrefixedText(),
370 $revision->getModel(),
371 $revision->getFormat() );
378 * Default per-revision callback, performs the import.
379 * @param WikiRevision $revision
382 public function importLogItem( $revision ) {
383 return $revision->importLogItem();
388 * @param WikiRevision $revision
391 public function importUpload( $revision ) {
392 return $revision->importUpload();
396 * Mostly for hook use
397 * @param Title $title
398 * @param ForeignTitle $foreignTitle
399 * @param int $revCount
400 * @param int $sRevCount
401 * @param array $pageInfo
404 public function finishImportPage( $title, $foreignTitle, $revCount,
405 $sRevCount, $pageInfo
407 // Update article count statistics (T42009)
408 // The normal counting logic in WikiPage->doEditUpdates() is designed for
409 // one-revision-at-a-time editing, not bulk imports. In this situation it
410 // suffers from issues of replica DB lag. We let WikiPage handle the total page
411 // and revision count, and we implement our own custom logic for the
412 // article (content page) count.
413 if ( !$this->disableStatisticsUpdate
) {
414 $page = WikiPage
::factory( $title );
415 $page->loadPageData( 'fromdbmaster' );
416 $content = $page->getContent();
417 if ( $content === null ) {
418 wfDebug( __METHOD__
. ': Skipping article count adjustment for ' . $title .
419 ' because WikiPage::getContent() returned null' );
421 $editInfo = $page->prepareContentForEdit( $content );
422 $countKey = 'title_' . $title->getPrefixedText();
423 $countable = $page->isCountable( $editInfo );
424 if ( array_key_exists( $countKey, $this->countableCache
) &&
425 $countable != $this->countableCache
[$countKey] ) {
426 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [
427 'articles' => ( (int)$countable - (int)$this->countableCache
[$countKey] )
433 return Hooks
::run( 'AfterImportPage', func_get_args() );
437 * Alternate per-revision callback, for debugging.
438 * @param WikiRevision &$revision
440 public function debugRevisionHandler( &$revision ) {
441 $this->debug( "Got revision:" );
442 if ( is_object( $revision->title
) ) {
443 $this->debug( "-- Title: " . $revision->title
->getPrefixedText() );
445 $this->debug( "-- Title: <invalid>" );
447 $this->debug( "-- User: " . $revision->user_text
);
448 $this->debug( "-- Timestamp: " . $revision->timestamp
);
449 $this->debug( "-- Comment: " . $revision->comment
);
450 $this->debug( "-- Text: " . $revision->text
);
454 * Notify the callback function of site info
455 * @param array $siteInfo
458 private function siteInfoCallback( $siteInfo ) {
459 if ( isset( $this->mSiteInfoCallback
) ) {
460 return call_user_func_array( $this->mSiteInfoCallback
,
461 [ $siteInfo, $this ] );
468 * Notify the callback function when a new "<page>" is reached.
469 * @param array $title
471 function pageCallback( $title ) {
472 if ( isset( $this->mPageCallback
) ) {
473 call_user_func( $this->mPageCallback
, $title );
478 * Notify the callback function when a "</page>" is closed.
479 * @param Title $title
480 * @param ForeignTitle $foreignTitle
481 * @param int $revCount
482 * @param int $sucCount Number of revisions for which callback returned true
483 * @param array $pageInfo Associative array of page information
485 private function pageOutCallback( $title, $foreignTitle, $revCount,
486 $sucCount, $pageInfo ) {
487 if ( isset( $this->mPageOutCallback
) ) {
488 call_user_func_array( $this->mPageOutCallback
, func_get_args() );
493 * Notify the callback function of a revision
494 * @param WikiRevision $revision
497 private function revisionCallback( $revision ) {
498 if ( isset( $this->mRevisionCallback
) ) {
499 return call_user_func_array( $this->mRevisionCallback
,
500 [ $revision, $this ] );
507 * Notify the callback function of a new log item
508 * @param WikiRevision $revision
511 private function logItemCallback( $revision ) {
512 if ( isset( $this->mLogItemCallback
) ) {
513 return call_user_func_array( $this->mLogItemCallback
,
514 [ $revision, $this ] );
521 * Retrieves the contents of the named attribute of the current element.
522 * @param string $attr The name of the attribute
523 * @return string The value of the attribute or an empty string if it is not set in the current
526 public function nodeAttribute( $attr ) {
527 return $this->reader
->getAttribute( $attr );
531 * Shouldn't something like this be built-in to XMLReader?
532 * Fetches text contents of the current element, assuming
533 * no sub-elements or such scary things.
537 public function nodeContents() {
538 if ( $this->reader
->isEmptyElement
) {
542 while ( $this->reader
->read() ) {
543 switch ( $this->reader
->nodeType
) {
544 case XMLReader
::TEXT
:
545 case XMLReader
::CDATA
:
546 case XMLReader
::SIGNIFICANT_WHITESPACE
:
547 $buffer .= $this->reader
->value
;
549 case XMLReader
::END_ELEMENT
:
554 $this->reader
->close();
559 * Primary entry point
561 * @throws MWException
564 public function doImport() {
565 // Calls to reader->read need to be wrapped in calls to
566 // libxml_disable_entity_loader() to avoid local file
567 // inclusion attacks (T48932).
568 $oldDisable = libxml_disable_entity_loader( true );
569 $this->reader
->read();
571 if ( $this->reader
->localName
!= 'mediawiki' ) {
572 libxml_disable_entity_loader( $oldDisable );
573 throw new MWException( "Expected <mediawiki> tag, got " .
574 $this->reader
->localName
);
576 $this->debug( "<mediawiki> tag is correct." );
578 $this->debug( "Starting primary dump processing loop." );
580 $keepReading = $this->reader
->read();
585 while ( $keepReading ) {
586 $tag = $this->reader
->localName
;
587 if ( $this->pageOffset
) {
588 if ( $tag === 'page' ) {
591 if ( $pageCount < $this->pageOffset
) {
592 $keepReading = $this->reader
->next();
596 $type = $this->reader
->nodeType
;
598 if ( !Hooks
::run( 'ImportHandleToplevelXMLTag', [ $this ] ) ) {
600 } elseif ( $tag == 'mediawiki' && $type == XMLReader
::END_ELEMENT
) {
602 } elseif ( $tag == 'siteinfo' ) {
603 $this->handleSiteInfo();
604 } elseif ( $tag == 'page' ) {
606 } elseif ( $tag == 'logitem' ) {
607 $this->handleLogItem();
608 } elseif ( $tag != '#text' ) {
609 $this->warn( "Unhandled top-level XML tag $tag" );
615 $keepReading = $this->reader
->next();
617 $this->debug( "Skip" );
619 $keepReading = $this->reader
->read();
622 } catch ( Exception
$ex ) {
627 libxml_disable_entity_loader( $oldDisable );
628 $this->reader
->close();
637 private function handleSiteInfo() {
638 $this->debug( "Enter site info handler." );
641 // Fields that can just be stuffed in the siteInfo object
642 $normalFields = [ 'sitename', 'base', 'generator', 'case' ];
644 while ( $this->reader
->read() ) {
645 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
646 $this->reader
->localName
== 'siteinfo' ) {
650 $tag = $this->reader
->localName
;
652 if ( $tag == 'namespace' ) {
653 $this->foreignNamespaces
[$this->nodeAttribute( 'key' )] =
654 $this->nodeContents();
655 } elseif ( in_array( $tag, $normalFields ) ) {
656 $siteInfo[$tag] = $this->nodeContents();
660 $siteInfo['_namespaces'] = $this->foreignNamespaces
;
661 $this->siteInfoCallback( $siteInfo );
664 private function handleLogItem() {
665 $this->debug( "Enter log item handler." );
668 // Fields that can just be stuffed in the pageInfo object
669 $normalFields = [ 'id', 'comment', 'type', 'action', 'timestamp',
670 'logtitle', 'params' ];
672 while ( $this->reader
->read() ) {
673 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
674 $this->reader
->localName
== 'logitem' ) {
678 $tag = $this->reader
->localName
;
680 if ( !Hooks
::run( 'ImportHandleLogItemXMLTag', [
684 } elseif ( in_array( $tag, $normalFields ) ) {
685 $logInfo[$tag] = $this->nodeContents();
686 } elseif ( $tag == 'contributor' ) {
687 $logInfo['contributor'] = $this->handleContributor();
688 } elseif ( $tag != '#text' ) {
689 $this->warn( "Unhandled log-item XML tag $tag" );
693 $this->processLogItem( $logInfo );
697 * @param array $logInfo
700 private function processLogItem( $logInfo ) {
701 $revision = new WikiRevision( $this->config
);
703 if ( isset( $logInfo['id'] ) ) {
704 $revision->setID( $logInfo['id'] );
706 $revision->setType( $logInfo['type'] );
707 $revision->setAction( $logInfo['action'] );
708 if ( isset( $logInfo['timestamp'] ) ) {
709 $revision->setTimestamp( $logInfo['timestamp'] );
711 if ( isset( $logInfo['params'] ) ) {
712 $revision->setParams( $logInfo['params'] );
714 if ( isset( $logInfo['logtitle'] ) ) {
715 // @todo Using Title for non-local titles is a recipe for disaster.
716 // We should use ForeignTitle here instead.
717 $revision->setTitle( Title
::newFromText( $logInfo['logtitle'] ) );
720 $revision->setNoUpdates( $this->mNoUpdates
);
722 if ( isset( $logInfo['comment'] ) ) {
723 $revision->setComment( $logInfo['comment'] );
726 if ( isset( $logInfo['contributor']['ip'] ) ) {
727 $revision->setUserIP( $logInfo['contributor']['ip'] );
730 if ( !isset( $logInfo['contributor']['username'] ) ) {
731 $revision->setUsername( $this->externalUserNames
->addPrefix( 'Unknown user' ) );
733 $revision->setUsername(
734 $this->externalUserNames
->applyPrefix( $logInfo['contributor']['username'] )
738 return $this->logItemCallback( $revision );
742 * @suppress PhanTypeInvalidDimOffset Phan not reading the reference inside the hook
744 private function handlePage() {
746 $this->debug( "Enter page handler." );
747 $pageInfo = [ 'revisionCount' => 0, 'successfulRevisionCount' => 0 ];
749 // Fields that can just be stuffed in the pageInfo object
750 $normalFields = [ 'title', 'ns', 'id', 'redirect', 'restrictions' ];
755 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
756 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
757 $this->reader
->localName
== 'page' ) {
763 $tag = $this->reader
->localName
;
766 // The title is invalid, bail out of this page
768 } elseif ( !Hooks
::run( 'ImportHandlePageXMLTag', [ $this,
771 } elseif ( in_array( $tag, $normalFields ) ) {
775 // <title>Page</title>
776 // <redirect title="NewTitle"/>
778 // Because the redirect tag is built differently, we need special handling for that case.
779 if ( $tag == 'redirect' ) {
780 $pageInfo[$tag] = $this->nodeAttribute( 'title' );
782 $pageInfo[$tag] = $this->nodeContents();
784 } elseif ( $tag == 'revision' ||
$tag == 'upload' ) {
785 if ( !isset( $title ) ) {
786 $title = $this->processTitle( $pageInfo['title'],
787 $pageInfo['ns'] ??
null );
789 // $title is either an array of two titles or false.
790 if ( is_array( $title ) ) {
791 $this->pageCallback( $title );
792 list( $pageInfo['_title'], $foreignTitle ) = $title;
800 if ( $tag == 'revision' ) {
801 $this->handleRevision( $pageInfo );
803 $this->handleUpload( $pageInfo );
806 } elseif ( $tag != '#text' ) {
807 $this->warn( "Unhandled page XML tag $tag" );
812 // @note $pageInfo is only set if a valid $title is processed above with
813 // no error. If we have a valid $title, then pageCallback is called
814 // above, $pageInfo['title'] is set and we do pageOutCallback here.
815 // If $pageInfo['_title'] is not set, then $foreignTitle is also not
816 // set since they both come from $title above.
817 if ( array_key_exists( '_title', $pageInfo ) ) {
818 $this->pageOutCallback( $pageInfo['_title'], $foreignTitle,
819 $pageInfo['revisionCount'],
820 $pageInfo['successfulRevisionCount'],
826 * @param array $pageInfo
828 private function handleRevision( &$pageInfo ) {
829 $this->debug( "Enter revision handler" );
832 $normalFields = [ 'id', 'timestamp', 'comment', 'minor', 'model', 'format', 'text', 'sha1' ];
836 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
837 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
838 $this->reader
->localName
== 'revision' ) {
842 $tag = $this->reader
->localName
;
844 if ( !Hooks
::run( 'ImportHandleRevisionXMLTag', [
845 $this, $pageInfo, $revisionInfo
848 } elseif ( in_array( $tag, $normalFields ) ) {
849 $revisionInfo[$tag] = $this->nodeContents();
850 } elseif ( $tag == 'contributor' ) {
851 $revisionInfo['contributor'] = $this->handleContributor();
852 } elseif ( $tag != '#text' ) {
853 $this->warn( "Unhandled revision XML tag $tag" );
858 $pageInfo['revisionCount']++
;
859 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
860 $pageInfo['successfulRevisionCount']++
;
865 * @param array $pageInfo
866 * @param array $revisionInfo
867 * @throws MWException
870 private function processRevision( $pageInfo, $revisionInfo ) {
871 global $wgMaxArticleSize;
873 // Make sure revisions won't violate $wgMaxArticleSize, which could lead to
874 // database errors and instability. Testing for revisions with only listed
875 // content models, as other content models might use serialization formats
876 // which aren't checked against $wgMaxArticleSize.
877 if ( ( !isset( $revisionInfo['model'] ) ||
878 in_array( $revisionInfo['model'], [
886 strlen( $revisionInfo['text'] ) > $wgMaxArticleSize * 1024
888 throw new MWException( 'The text of ' .
889 ( isset( $revisionInfo['id'] ) ?
890 "the revision with ID $revisionInfo[id]" :
892 ) . " exceeds the maximum allowable size ($wgMaxArticleSize KB)" );
895 // FIXME: process schema version 11!
896 $revision = new WikiRevision( $this->config
);
898 if ( isset( $revisionInfo['id'] ) ) {
899 $revision->setID( $revisionInfo['id'] );
901 if ( isset( $revisionInfo['model'] ) ) {
902 $revision->setModel( $revisionInfo['model'] );
904 if ( isset( $revisionInfo['format'] ) ) {
905 $revision->setFormat( $revisionInfo['format'] );
907 $revision->setTitle( $pageInfo['_title'] );
909 if ( isset( $revisionInfo['text'] ) ) {
910 $handler = $revision->getContentHandler();
911 $text = $handler->importTransform(
912 $revisionInfo['text'],
913 $revision->getFormat() );
915 $revision->setText( $text );
917 $revision->setTimestamp( $revisionInfo['timestamp'] ??
wfTimestampNow() );
919 if ( isset( $revisionInfo['comment'] ) ) {
920 $revision->setComment( $revisionInfo['comment'] );
923 if ( isset( $revisionInfo['minor'] ) ) {
924 $revision->setMinor( true );
926 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
927 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
928 } elseif ( isset( $revisionInfo['contributor']['username'] ) ) {
929 $revision->setUsername(
930 $this->externalUserNames
->applyPrefix( $revisionInfo['contributor']['username'] )
933 $revision->setUsername( $this->externalUserNames
->addPrefix( 'Unknown user' ) );
935 if ( isset( $revisionInfo['sha1'] ) ) {
936 $revision->setSha1Base36( $revisionInfo['sha1'] );
938 $revision->setNoUpdates( $this->mNoUpdates
);
940 return $this->revisionCallback( $revision );
944 * @param array $pageInfo
947 private function handleUpload( &$pageInfo ) {
948 $this->debug( "Enter upload handler" );
951 $normalFields = [ 'timestamp', 'comment', 'filename', 'text',
952 'src', 'size', 'sha1base36', 'archivename', 'rel' ];
956 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
957 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
958 $this->reader
->localName
== 'upload' ) {
962 $tag = $this->reader
->localName
;
964 if ( !Hooks
::run( 'ImportHandleUploadXMLTag', [
968 } elseif ( in_array( $tag, $normalFields ) ) {
969 $uploadInfo[$tag] = $this->nodeContents();
970 } elseif ( $tag == 'contributor' ) {
971 $uploadInfo['contributor'] = $this->handleContributor();
972 } elseif ( $tag == 'contents' ) {
973 $contents = $this->nodeContents();
974 $encoding = $this->reader
->getAttribute( 'encoding' );
975 if ( $encoding === 'base64' ) {
976 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
977 $uploadInfo['isTempSrc'] = true;
979 } elseif ( $tag != '#text' ) {
980 $this->warn( "Unhandled upload XML tag $tag" );
985 if ( $this->mImageBasePath
&& isset( $uploadInfo['rel'] ) ) {
986 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
987 if ( file_exists( $path ) ) {
988 $uploadInfo['fileSrc'] = $path;
989 $uploadInfo['isTempSrc'] = false;
993 if ( $this->mImportUploads
) {
994 return $this->processUpload( $pageInfo, $uploadInfo );
999 * @param string $contents
1002 private function dumpTemp( $contents ) {
1003 $filename = tempnam( wfTempDir(), 'importupload' );
1004 file_put_contents( $filename, $contents );
1009 * @param array $pageInfo
1010 * @param array $uploadInfo
1013 private function processUpload( $pageInfo, $uploadInfo ) {
1014 $revision = new WikiRevision( $this->config
);
1015 $text = $uploadInfo['text'] ??
'';
1017 $revision->setTitle( $pageInfo['_title'] );
1018 $revision->setID( $pageInfo['id'] );
1019 $revision->setTimestamp( $uploadInfo['timestamp'] );
1020 $revision->setText( $text );
1021 $revision->setFilename( $uploadInfo['filename'] );
1022 if ( isset( $uploadInfo['archivename'] ) ) {
1023 $revision->setArchiveName( $uploadInfo['archivename'] );
1025 $revision->setSrc( $uploadInfo['src'] );
1026 if ( isset( $uploadInfo['fileSrc'] ) ) {
1027 $revision->setFileSrc( $uploadInfo['fileSrc'],
1028 !empty( $uploadInfo['isTempSrc'] ) );
1030 if ( isset( $uploadInfo['sha1base36'] ) ) {
1031 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
1033 $revision->setSize( intval( $uploadInfo['size'] ) );
1034 $revision->setComment( $uploadInfo['comment'] );
1036 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
1037 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
1039 if ( isset( $uploadInfo['contributor']['username'] ) ) {
1040 $revision->setUsername(
1041 $this->externalUserNames
->applyPrefix( $uploadInfo['contributor']['username'] )
1044 $revision->setNoUpdates( $this->mNoUpdates
);
1046 return call_user_func( $this->mUploadCallback
, $revision );
1052 private function handleContributor() {
1053 $fields = [ 'id', 'ip', 'username' ];
1056 if ( $this->reader
->isEmptyElement
) {
1059 while ( $this->reader
->read() ) {
1060 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
1061 $this->reader
->localName
== 'contributor' ) {
1065 $tag = $this->reader
->localName
;
1067 if ( in_array( $tag, $fields ) ) {
1068 $info[$tag] = $this->nodeContents();
1076 * @param string $text
1077 * @param string|null $ns
1078 * @return array|bool
1080 private function processTitle( $text, $ns = null ) {
1081 if ( is_null( $this->foreignNamespaces
) ) {
1082 $foreignTitleFactory = new NaiveForeignTitleFactory();
1084 $foreignTitleFactory = new NamespaceAwareForeignTitleFactory(
1085 $this->foreignNamespaces
);
1088 $foreignTitle = $foreignTitleFactory->createForeignTitle( $text,
1091 $title = $this->importTitleFactory
->createTitleFromForeignTitle(
1094 $commandLineMode = $this->config
->get( 'CommandLineMode' );
1095 if ( is_null( $title ) ) {
1096 # Invalid page title? Ignore the page
1097 $this->notice( 'import-error-invalid', $foreignTitle->getFullText() );
1099 } elseif ( $title->isExternal() ) {
1100 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
1102 } elseif ( !$title->canExist() ) {
1103 $this->notice( 'import-error-special', $title->getPrefixedText() );
1105 } elseif ( !$commandLineMode ) {
1106 $permissionManager = MediaWikiServices
::getInstance()->getPermissionManager();
1107 $user = RequestContext
::getMain()->getUser();
1109 if ( !$permissionManager->userCan( 'edit', $user, $title ) ) {
1110 # Do not import if the importing wiki user cannot edit this page
1111 $this->notice( 'import-error-edit', $title->getPrefixedText() );
1116 if ( !$title->exists() && !$permissionManager->userCan( 'create', $user, $title ) ) {
1117 # Do not import if the importing wiki user cannot create this page
1118 $this->notice( 'import-error-create', $title->getPrefixedText() );
1124 return [ $title, $foreignTitle ];