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 );
741 private function handlePage() {
743 $this->debug( "Enter page handler." );
744 $pageInfo = [ 'revisionCount' => 0, 'successfulRevisionCount' => 0 ];
746 // Fields that can just be stuffed in the pageInfo object
747 $normalFields = [ 'title', 'ns', 'id', 'redirect', 'restrictions' ];
752 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
753 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
754 $this->reader
->localName
== 'page' ) {
760 $tag = $this->reader
->localName
;
763 // The title is invalid, bail out of this page
765 } elseif ( !Hooks
::run( 'ImportHandlePageXMLTag', [ $this,
768 } elseif ( in_array( $tag, $normalFields ) ) {
772 // <title>Page</title>
773 // <redirect title="NewTitle"/>
775 // Because the redirect tag is built differently, we need special handling for that case.
776 if ( $tag == 'redirect' ) {
777 $pageInfo[$tag] = $this->nodeAttribute( 'title' );
779 $pageInfo[$tag] = $this->nodeContents();
781 } elseif ( $tag == 'revision' ||
$tag == 'upload' ) {
782 if ( !isset( $title ) ) {
783 $title = $this->processTitle( $pageInfo['title'],
784 $pageInfo['ns'] ??
null );
786 // $title is either an array of two titles or false.
787 if ( is_array( $title ) ) {
788 $this->pageCallback( $title );
789 list( $pageInfo['_title'], $foreignTitle ) = $title;
797 if ( $tag == 'revision' ) {
798 $this->handleRevision( $pageInfo );
800 $this->handleUpload( $pageInfo );
803 } elseif ( $tag != '#text' ) {
804 $this->warn( "Unhandled page XML tag $tag" );
809 // @note $pageInfo is only set if a valid $title is processed above with
810 // no error. If we have a valid $title, then pageCallback is called
811 // above, $pageInfo['title'] is set and we do pageOutCallback here.
812 // If $pageInfo['_title'] is not set, then $foreignTitle is also not
813 // set since they both come from $title above.
814 if ( array_key_exists( '_title', $pageInfo ) ) {
815 $this->pageOutCallback( $pageInfo['_title'], $foreignTitle,
816 $pageInfo['revisionCount'],
817 $pageInfo['successfulRevisionCount'],
823 * @param array $pageInfo
825 private function handleRevision( &$pageInfo ) {
826 $this->debug( "Enter revision handler" );
829 $normalFields = [ 'id', 'timestamp', 'comment', 'minor', 'model', 'format', 'text', 'sha1' ];
833 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
834 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
835 $this->reader
->localName
== 'revision' ) {
839 $tag = $this->reader
->localName
;
841 if ( !Hooks
::run( 'ImportHandleRevisionXMLTag', [
842 $this, $pageInfo, $revisionInfo
845 } elseif ( in_array( $tag, $normalFields ) ) {
846 $revisionInfo[$tag] = $this->nodeContents();
847 } elseif ( $tag == 'contributor' ) {
848 $revisionInfo['contributor'] = $this->handleContributor();
849 } elseif ( $tag != '#text' ) {
850 $this->warn( "Unhandled revision XML tag $tag" );
855 $pageInfo['revisionCount']++
;
856 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
857 $pageInfo['successfulRevisionCount']++
;
862 * @param array $pageInfo
863 * @param array $revisionInfo
864 * @throws MWException
867 private function processRevision( $pageInfo, $revisionInfo ) {
868 global $wgMaxArticleSize;
870 // Make sure revisions won't violate $wgMaxArticleSize, which could lead to
871 // database errors and instability. Testing for revisions with only listed
872 // content models, as other content models might use serialization formats
873 // which aren't checked against $wgMaxArticleSize.
874 if ( ( !isset( $revisionInfo['model'] ) ||
875 in_array( $revisionInfo['model'], [
883 strlen( $revisionInfo['text'] ) > $wgMaxArticleSize * 1024
885 throw new MWException( 'The text of ' .
886 ( isset( $revisionInfo['id'] ) ?
887 "the revision with ID $revisionInfo[id]" :
889 ) . " exceeds the maximum allowable size ($wgMaxArticleSize KB)" );
892 // FIXME: process schema version 11!
893 $revision = new WikiRevision( $this->config
);
895 if ( isset( $revisionInfo['id'] ) ) {
896 $revision->setID( $revisionInfo['id'] );
898 if ( isset( $revisionInfo['model'] ) ) {
899 $revision->setModel( $revisionInfo['model'] );
901 if ( isset( $revisionInfo['format'] ) ) {
902 $revision->setFormat( $revisionInfo['format'] );
904 $revision->setTitle( $pageInfo['_title'] );
906 if ( isset( $revisionInfo['text'] ) ) {
907 $handler = $revision->getContentHandler();
908 $text = $handler->importTransform(
909 $revisionInfo['text'],
910 $revision->getFormat() );
912 $revision->setText( $text );
914 $revision->setTimestamp( $revisionInfo['timestamp'] ??
wfTimestampNow() );
916 if ( isset( $revisionInfo['comment'] ) ) {
917 $revision->setComment( $revisionInfo['comment'] );
920 if ( isset( $revisionInfo['minor'] ) ) {
921 $revision->setMinor( true );
923 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
924 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
925 } elseif ( isset( $revisionInfo['contributor']['username'] ) ) {
926 $revision->setUsername(
927 $this->externalUserNames
->applyPrefix( $revisionInfo['contributor']['username'] )
930 $revision->setUsername( $this->externalUserNames
->addPrefix( 'Unknown user' ) );
932 if ( isset( $revisionInfo['sha1'] ) ) {
933 $revision->setSha1Base36( $revisionInfo['sha1'] );
935 $revision->setNoUpdates( $this->mNoUpdates
);
937 return $this->revisionCallback( $revision );
941 * @param array $pageInfo
944 private function handleUpload( &$pageInfo ) {
945 $this->debug( "Enter upload handler" );
948 $normalFields = [ 'timestamp', 'comment', 'filename', 'text',
949 'src', 'size', 'sha1base36', 'archivename', 'rel' ];
953 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
954 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
955 $this->reader
->localName
== 'upload' ) {
959 $tag = $this->reader
->localName
;
961 if ( !Hooks
::run( 'ImportHandleUploadXMLTag', [
965 } elseif ( in_array( $tag, $normalFields ) ) {
966 $uploadInfo[$tag] = $this->nodeContents();
967 } elseif ( $tag == 'contributor' ) {
968 $uploadInfo['contributor'] = $this->handleContributor();
969 } elseif ( $tag == 'contents' ) {
970 $contents = $this->nodeContents();
971 $encoding = $this->reader
->getAttribute( 'encoding' );
972 if ( $encoding === 'base64' ) {
973 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
974 $uploadInfo['isTempSrc'] = true;
976 } elseif ( $tag != '#text' ) {
977 $this->warn( "Unhandled upload XML tag $tag" );
982 if ( $this->mImageBasePath
&& isset( $uploadInfo['rel'] ) ) {
983 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
984 if ( file_exists( $path ) ) {
985 $uploadInfo['fileSrc'] = $path;
986 $uploadInfo['isTempSrc'] = false;
990 if ( $this->mImportUploads
) {
991 return $this->processUpload( $pageInfo, $uploadInfo );
996 * @param string $contents
999 private function dumpTemp( $contents ) {
1000 $filename = tempnam( wfTempDir(), 'importupload' );
1001 file_put_contents( $filename, $contents );
1006 * @param array $pageInfo
1007 * @param array $uploadInfo
1010 private function processUpload( $pageInfo, $uploadInfo ) {
1011 $revision = new WikiRevision( $this->config
);
1012 $text = $uploadInfo['text'] ??
'';
1014 $revision->setTitle( $pageInfo['_title'] );
1015 $revision->setID( $pageInfo['id'] );
1016 $revision->setTimestamp( $uploadInfo['timestamp'] );
1017 $revision->setText( $text );
1018 $revision->setFilename( $uploadInfo['filename'] );
1019 if ( isset( $uploadInfo['archivename'] ) ) {
1020 $revision->setArchiveName( $uploadInfo['archivename'] );
1022 $revision->setSrc( $uploadInfo['src'] );
1023 if ( isset( $uploadInfo['fileSrc'] ) ) {
1024 $revision->setFileSrc( $uploadInfo['fileSrc'],
1025 !empty( $uploadInfo['isTempSrc'] ) );
1027 if ( isset( $uploadInfo['sha1base36'] ) ) {
1028 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
1030 $revision->setSize( intval( $uploadInfo['size'] ) );
1031 $revision->setComment( $uploadInfo['comment'] );
1033 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
1034 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
1036 if ( isset( $uploadInfo['contributor']['username'] ) ) {
1037 $revision->setUsername(
1038 $this->externalUserNames
->applyPrefix( $uploadInfo['contributor']['username'] )
1041 $revision->setNoUpdates( $this->mNoUpdates
);
1043 return call_user_func( $this->mUploadCallback
, $revision );
1049 private function handleContributor() {
1050 $fields = [ 'id', 'ip', 'username' ];
1053 if ( $this->reader
->isEmptyElement
) {
1056 while ( $this->reader
->read() ) {
1057 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
1058 $this->reader
->localName
== 'contributor' ) {
1062 $tag = $this->reader
->localName
;
1064 if ( in_array( $tag, $fields ) ) {
1065 $info[$tag] = $this->nodeContents();
1073 * @param string $text
1074 * @param string|null $ns
1075 * @return array|bool
1077 private function processTitle( $text, $ns = null ) {
1078 if ( is_null( $this->foreignNamespaces
) ) {
1079 $foreignTitleFactory = new NaiveForeignTitleFactory();
1081 $foreignTitleFactory = new NamespaceAwareForeignTitleFactory(
1082 $this->foreignNamespaces
);
1085 $foreignTitle = $foreignTitleFactory->createForeignTitle( $text,
1088 $title = $this->importTitleFactory
->createTitleFromForeignTitle(
1091 $commandLineMode = $this->config
->get( 'CommandLineMode' );
1092 if ( is_null( $title ) ) {
1093 # Invalid page title? Ignore the page
1094 $this->notice( 'import-error-invalid', $foreignTitle->getFullText() );
1096 } elseif ( $title->isExternal() ) {
1097 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
1099 } elseif ( !$title->canExist() ) {
1100 $this->notice( 'import-error-special', $title->getPrefixedText() );
1102 } elseif ( !$commandLineMode ) {
1103 $permissionManager = MediaWikiServices
::getInstance()->getPermissionManager();
1104 $user = RequestContext
::getMain()->getUser();
1106 if ( !$permissionManager->userCan( 'edit', $user, $title ) ) {
1107 # Do not import if the importing wiki user cannot edit this page
1108 $this->notice( 'import-error-edit', $title->getPrefixedText() );
1113 if ( !$title->exists() && !$permissionManager->userCan( 'create', $user, $title ) ) {
1114 # Do not import if the importing wiki user cannot create this page
1115 $this->notice( 'import-error-create', $title->getPrefixedText() );
1121 return [ $title, $foreignTitle ];