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 MWNamespace
::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' );
286 } elseif ( !MWNamespace
::hasSubpages( $title->getNamespace() ) ) {
287 $displayNSText = $title->getNamespace() == NS_MAIN
288 ?
wfMessage( 'blanknamespace' )->text()
289 : MediaWikiServices
::getInstance()->getContentLanguage()->
290 getNsText( $title->getNamespace() );
291 $status->fatal( 'import-rootpage-nosubpage', $displayNSText );
293 // set namespace to 'all', so the namespace check in processTitle() can pass
294 $this->setTargetNamespace( null );
295 $this->setImportTitleFactory( new SubpageImportTitleFactory( $title ) );
304 public function setImageBasePath( $dir ) {
305 $this->mImageBasePath
= $dir;
309 * @param bool $import
311 public function setImportUploads( $import ) {
312 $this->mImportUploads
= $import;
317 * @param string $usernamePrefix Prefix to apply to unknown (and possibly also known) usernames
318 * @param bool $assignKnownUsers Whether to apply the prefix to usernames that exist locally
320 public function setUsernamePrefix( $usernamePrefix, $assignKnownUsers ) {
321 $this->externalUserNames
= new ExternalUserNames( $usernamePrefix, $assignKnownUsers );
325 * Statistics update can cause a lot of time
328 public function disableStatisticsUpdate() {
329 $this->disableStatisticsUpdate
= true;
333 * Default per-page callback. Sets up some things related to site statistics
334 * @param array $titleAndForeignTitle Two-element array, with Title object at
335 * index 0 and ForeignTitle object at index 1
338 public function beforeImportPage( $titleAndForeignTitle ) {
339 $title = $titleAndForeignTitle[0];
340 $page = WikiPage
::factory( $title );
341 $this->countableCache
['title_' . $title->getPrefixedText()] = $page->isCountable();
346 * Default per-revision callback, performs the import.
347 * @param WikiRevision $revision
350 public function importRevision( $revision ) {
351 if ( !$revision->getContentHandler()->canBeUsedOn( $revision->getTitle() ) ) {
352 $this->notice( 'import-error-bad-location',
353 $revision->getTitle()->getPrefixedText(),
355 $revision->getModel(),
356 $revision->getFormat() );
362 return $revision->importOldRevision();
363 } catch ( MWContentSerializationException
$ex ) {
364 $this->notice( 'import-error-unserialize',
365 $revision->getTitle()->getPrefixedText(),
367 $revision->getModel(),
368 $revision->getFormat() );
375 * Default per-revision callback, performs the import.
376 * @param WikiRevision $revision
379 public function importLogItem( $revision ) {
380 return $revision->importLogItem();
385 * @param WikiRevision $revision
388 public function importUpload( $revision ) {
389 return $revision->importUpload();
393 * Mostly for hook use
394 * @param Title $title
395 * @param ForeignTitle $foreignTitle
396 * @param int $revCount
397 * @param int $sRevCount
398 * @param array $pageInfo
401 public function finishImportPage( $title, $foreignTitle, $revCount,
402 $sRevCount, $pageInfo
404 // Update article count statistics (T42009)
405 // The normal counting logic in WikiPage->doEditUpdates() is designed for
406 // one-revision-at-a-time editing, not bulk imports. In this situation it
407 // suffers from issues of replica DB lag. We let WikiPage handle the total page
408 // and revision count, and we implement our own custom logic for the
409 // article (content page) count.
410 if ( !$this->disableStatisticsUpdate
) {
411 $page = WikiPage
::factory( $title );
412 $page->loadPageData( 'fromdbmaster' );
413 $content = $page->getContent();
414 if ( $content === null ) {
415 wfDebug( __METHOD__
. ': Skipping article count adjustment for ' . $title .
416 ' because WikiPage::getContent() returned null' );
418 $editInfo = $page->prepareContentForEdit( $content );
419 $countKey = 'title_' . $title->getPrefixedText();
420 $countable = $page->isCountable( $editInfo );
421 if ( array_key_exists( $countKey, $this->countableCache
) &&
422 $countable != $this->countableCache
[$countKey] ) {
423 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [
424 'articles' => ( (int)$countable - (int)$this->countableCache
[$countKey] )
430 return Hooks
::run( 'AfterImportPage', func_get_args() );
434 * Alternate per-revision callback, for debugging.
435 * @param WikiRevision &$revision
437 public function debugRevisionHandler( &$revision ) {
438 $this->debug( "Got revision:" );
439 if ( is_object( $revision->title
) ) {
440 $this->debug( "-- Title: " . $revision->title
->getPrefixedText() );
442 $this->debug( "-- Title: <invalid>" );
444 $this->debug( "-- User: " . $revision->user_text
);
445 $this->debug( "-- Timestamp: " . $revision->timestamp
);
446 $this->debug( "-- Comment: " . $revision->comment
);
447 $this->debug( "-- Text: " . $revision->text
);
451 * Notify the callback function of site info
452 * @param array $siteInfo
455 private function siteInfoCallback( $siteInfo ) {
456 if ( isset( $this->mSiteInfoCallback
) ) {
457 return call_user_func_array( $this->mSiteInfoCallback
,
458 [ $siteInfo, $this ] );
465 * Notify the callback function when a new "<page>" is reached.
466 * @param Title $title
468 function pageCallback( $title ) {
469 if ( isset( $this->mPageCallback
) ) {
470 call_user_func( $this->mPageCallback
, $title );
475 * Notify the callback function when a "</page>" is closed.
476 * @param Title $title
477 * @param ForeignTitle $foreignTitle
478 * @param int $revCount
479 * @param int $sucCount Number of revisions for which callback returned true
480 * @param array $pageInfo Associative array of page information
482 private function pageOutCallback( $title, $foreignTitle, $revCount,
483 $sucCount, $pageInfo ) {
484 if ( isset( $this->mPageOutCallback
) ) {
485 call_user_func_array( $this->mPageOutCallback
, func_get_args() );
490 * Notify the callback function of a revision
491 * @param WikiRevision $revision
494 private function revisionCallback( $revision ) {
495 if ( isset( $this->mRevisionCallback
) ) {
496 return call_user_func_array( $this->mRevisionCallback
,
497 [ $revision, $this ] );
504 * Notify the callback function of a new log item
505 * @param WikiRevision $revision
508 private function logItemCallback( $revision ) {
509 if ( isset( $this->mLogItemCallback
) ) {
510 return call_user_func_array( $this->mLogItemCallback
,
511 [ $revision, $this ] );
518 * Retrieves the contents of the named attribute of the current element.
519 * @param string $attr The name of the attribute
520 * @return string The value of the attribute or an empty string if it is not set in the current
523 public function nodeAttribute( $attr ) {
524 return $this->reader
->getAttribute( $attr );
528 * Shouldn't something like this be built-in to XMLReader?
529 * Fetches text contents of the current element, assuming
530 * no sub-elements or such scary things.
534 public function nodeContents() {
535 if ( $this->reader
->isEmptyElement
) {
539 while ( $this->reader
->read() ) {
540 switch ( $this->reader
->nodeType
) {
541 case XMLReader
::TEXT
:
542 case XMLReader
::CDATA
:
543 case XMLReader
::SIGNIFICANT_WHITESPACE
:
544 $buffer .= $this->reader
->value
;
546 case XMLReader
::END_ELEMENT
:
551 $this->reader
->close();
556 * Primary entry point
558 * @throws MWException
561 public function doImport() {
562 // Calls to reader->read need to be wrapped in calls to
563 // libxml_disable_entity_loader() to avoid local file
564 // inclusion attacks (T48932).
565 $oldDisable = libxml_disable_entity_loader( true );
566 $this->reader
->read();
568 if ( $this->reader
->localName
!= 'mediawiki' ) {
569 libxml_disable_entity_loader( $oldDisable );
570 throw new MWException( "Expected <mediawiki> tag, got " .
571 $this->reader
->localName
);
573 $this->debug( "<mediawiki> tag is correct." );
575 $this->debug( "Starting primary dump processing loop." );
577 $keepReading = $this->reader
->read();
582 while ( $keepReading ) {
583 $tag = $this->reader
->localName
;
584 if ( $this->pageOffset
) {
585 if ( $tag === 'page' ) {
588 if ( $pageCount < $this->pageOffset
) {
589 $keepReading = $this->reader
->next();
593 $type = $this->reader
->nodeType
;
595 if ( !Hooks
::run( 'ImportHandleToplevelXMLTag', [ $this ] ) ) {
597 } elseif ( $tag == 'mediawiki' && $type == XMLReader
::END_ELEMENT
) {
599 } elseif ( $tag == 'siteinfo' ) {
600 $this->handleSiteInfo();
601 } elseif ( $tag == 'page' ) {
603 } elseif ( $tag == 'logitem' ) {
604 $this->handleLogItem();
605 } elseif ( $tag != '#text' ) {
606 $this->warn( "Unhandled top-level XML tag $tag" );
612 $keepReading = $this->reader
->next();
614 $this->debug( "Skip" );
616 $keepReading = $this->reader
->read();
619 } catch ( Exception
$ex ) {
624 libxml_disable_entity_loader( $oldDisable );
625 $this->reader
->close();
634 private function handleSiteInfo() {
635 $this->debug( "Enter site info handler." );
638 // Fields that can just be stuffed in the siteInfo object
639 $normalFields = [ 'sitename', 'base', 'generator', 'case' ];
641 while ( $this->reader
->read() ) {
642 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
643 $this->reader
->localName
== 'siteinfo' ) {
647 $tag = $this->reader
->localName
;
649 if ( $tag == 'namespace' ) {
650 $this->foreignNamespaces
[$this->nodeAttribute( 'key' )] =
651 $this->nodeContents();
652 } elseif ( in_array( $tag, $normalFields ) ) {
653 $siteInfo[$tag] = $this->nodeContents();
657 $siteInfo['_namespaces'] = $this->foreignNamespaces
;
658 $this->siteInfoCallback( $siteInfo );
661 private function handleLogItem() {
662 $this->debug( "Enter log item handler." );
665 // Fields that can just be stuffed in the pageInfo object
666 $normalFields = [ 'id', 'comment', 'type', 'action', 'timestamp',
667 'logtitle', 'params' ];
669 while ( $this->reader
->read() ) {
670 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
671 $this->reader
->localName
== 'logitem' ) {
675 $tag = $this->reader
->localName
;
677 if ( !Hooks
::run( 'ImportHandleLogItemXMLTag', [
681 } elseif ( in_array( $tag, $normalFields ) ) {
682 $logInfo[$tag] = $this->nodeContents();
683 } elseif ( $tag == 'contributor' ) {
684 $logInfo['contributor'] = $this->handleContributor();
685 } elseif ( $tag != '#text' ) {
686 $this->warn( "Unhandled log-item XML tag $tag" );
690 $this->processLogItem( $logInfo );
694 * @param array $logInfo
697 private function processLogItem( $logInfo ) {
698 $revision = new WikiRevision( $this->config
);
700 if ( isset( $logInfo['id'] ) ) {
701 $revision->setID( $logInfo['id'] );
703 $revision->setType( $logInfo['type'] );
704 $revision->setAction( $logInfo['action'] );
705 if ( isset( $logInfo['timestamp'] ) ) {
706 $revision->setTimestamp( $logInfo['timestamp'] );
708 if ( isset( $logInfo['params'] ) ) {
709 $revision->setParams( $logInfo['params'] );
711 if ( isset( $logInfo['logtitle'] ) ) {
712 // @todo Using Title for non-local titles is a recipe for disaster.
713 // We should use ForeignTitle here instead.
714 $revision->setTitle( Title
::newFromText( $logInfo['logtitle'] ) );
717 $revision->setNoUpdates( $this->mNoUpdates
);
719 if ( isset( $logInfo['comment'] ) ) {
720 $revision->setComment( $logInfo['comment'] );
723 if ( isset( $logInfo['contributor']['ip'] ) ) {
724 $revision->setUserIP( $logInfo['contributor']['ip'] );
727 if ( !isset( $logInfo['contributor']['username'] ) ) {
728 $revision->setUsername( $this->externalUserNames
->addPrefix( 'Unknown user' ) );
730 $revision->setUsername(
731 $this->externalUserNames
->applyPrefix( $logInfo['contributor']['username'] )
735 return $this->logItemCallback( $revision );
738 private function handlePage() {
740 $this->debug( "Enter page handler." );
741 $pageInfo = [ 'revisionCount' => 0, 'successfulRevisionCount' => 0 ];
743 // Fields that can just be stuffed in the pageInfo object
744 $normalFields = [ 'title', 'ns', 'id', 'redirect', 'restrictions' ];
749 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
750 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
751 $this->reader
->localName
== 'page' ) {
757 $tag = $this->reader
->localName
;
760 // The title is invalid, bail out of this page
762 } elseif ( !Hooks
::run( 'ImportHandlePageXMLTag', [ $this,
765 } elseif ( in_array( $tag, $normalFields ) ) {
769 // <title>Page</title>
770 // <redirect title="NewTitle"/>
772 // Because the redirect tag is built differently, we need special handling for that case.
773 if ( $tag == 'redirect' ) {
774 $pageInfo[$tag] = $this->nodeAttribute( 'title' );
776 $pageInfo[$tag] = $this->nodeContents();
778 } elseif ( $tag == 'revision' ||
$tag == 'upload' ) {
779 if ( !isset( $title ) ) {
780 $title = $this->processTitle( $pageInfo['title'],
781 $pageInfo['ns'] ??
null );
783 // $title is either an array of two titles or false.
784 if ( is_array( $title ) ) {
785 $this->pageCallback( $title );
786 list( $pageInfo['_title'], $foreignTitle ) = $title;
794 if ( $tag == 'revision' ) {
795 $this->handleRevision( $pageInfo );
797 $this->handleUpload( $pageInfo );
800 } elseif ( $tag != '#text' ) {
801 $this->warn( "Unhandled page XML tag $tag" );
806 // @note $pageInfo is only set if a valid $title is processed above with
807 // no error. If we have a valid $title, then pageCallback is called
808 // above, $pageInfo['title'] is set and we do pageOutCallback here.
809 // If $pageInfo['_title'] is not set, then $foreignTitle is also not
810 // set since they both come from $title above.
811 if ( array_key_exists( '_title', $pageInfo ) ) {
812 $this->pageOutCallback( $pageInfo['_title'], $foreignTitle,
813 $pageInfo['revisionCount'],
814 $pageInfo['successfulRevisionCount'],
820 * @param array $pageInfo
822 private function handleRevision( &$pageInfo ) {
823 $this->debug( "Enter revision handler" );
826 $normalFields = [ 'id', 'timestamp', 'comment', 'minor', 'model', 'format', 'text', 'sha1' ];
830 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
831 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
832 $this->reader
->localName
== 'revision' ) {
836 $tag = $this->reader
->localName
;
838 if ( !Hooks
::run( 'ImportHandleRevisionXMLTag', [
839 $this, $pageInfo, $revisionInfo
842 } elseif ( in_array( $tag, $normalFields ) ) {
843 $revisionInfo[$tag] = $this->nodeContents();
844 } elseif ( $tag == 'contributor' ) {
845 $revisionInfo['contributor'] = $this->handleContributor();
846 } elseif ( $tag != '#text' ) {
847 $this->warn( "Unhandled revision XML tag $tag" );
852 $pageInfo['revisionCount']++
;
853 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
854 $pageInfo['successfulRevisionCount']++
;
859 * @param array $pageInfo
860 * @param array $revisionInfo
861 * @throws MWException
864 private function processRevision( $pageInfo, $revisionInfo ) {
865 global $wgMaxArticleSize;
867 // Make sure revisions won't violate $wgMaxArticleSize, which could lead to
868 // database errors and instability. Testing for revisions with only listed
869 // content models, as other content models might use serialization formats
870 // which aren't checked against $wgMaxArticleSize.
871 if ( ( !isset( $revisionInfo['model'] ) ||
872 in_array( $revisionInfo['model'], [
880 strlen( $revisionInfo['text'] ) > $wgMaxArticleSize * 1024
882 throw new MWException( 'The text of ' .
883 ( isset( $revisionInfo['id'] ) ?
884 "the revision with ID $revisionInfo[id]" :
886 ) . " exceeds the maximum allowable size ($wgMaxArticleSize KB)" );
889 // FIXME: process schema version 11!
890 $revision = new WikiRevision( $this->config
);
892 if ( isset( $revisionInfo['id'] ) ) {
893 $revision->setID( $revisionInfo['id'] );
895 if ( isset( $revisionInfo['model'] ) ) {
896 $revision->setModel( $revisionInfo['model'] );
898 if ( isset( $revisionInfo['format'] ) ) {
899 $revision->setFormat( $revisionInfo['format'] );
901 $revision->setTitle( $pageInfo['_title'] );
903 if ( isset( $revisionInfo['text'] ) ) {
904 $handler = $revision->getContentHandler();
905 $text = $handler->importTransform(
906 $revisionInfo['text'],
907 $revision->getFormat() );
909 $revision->setText( $text );
911 $revision->setTimestamp( $revisionInfo['timestamp'] ??
wfTimestampNow() );
913 if ( isset( $revisionInfo['comment'] ) ) {
914 $revision->setComment( $revisionInfo['comment'] );
917 if ( isset( $revisionInfo['minor'] ) ) {
918 $revision->setMinor( true );
920 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
921 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
922 } elseif ( isset( $revisionInfo['contributor']['username'] ) ) {
923 $revision->setUsername(
924 $this->externalUserNames
->applyPrefix( $revisionInfo['contributor']['username'] )
927 $revision->setUsername( $this->externalUserNames
->addPrefix( 'Unknown user' ) );
929 if ( isset( $revisionInfo['sha1'] ) ) {
930 $revision->setSha1Base36( $revisionInfo['sha1'] );
932 $revision->setNoUpdates( $this->mNoUpdates
);
934 return $this->revisionCallback( $revision );
938 * @param array $pageInfo
941 private function handleUpload( &$pageInfo ) {
942 $this->debug( "Enter upload handler" );
945 $normalFields = [ 'timestamp', 'comment', 'filename', 'text',
946 'src', 'size', 'sha1base36', 'archivename', 'rel' ];
950 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
951 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
952 $this->reader
->localName
== 'upload' ) {
956 $tag = $this->reader
->localName
;
958 if ( !Hooks
::run( 'ImportHandleUploadXMLTag', [
962 } elseif ( in_array( $tag, $normalFields ) ) {
963 $uploadInfo[$tag] = $this->nodeContents();
964 } elseif ( $tag == 'contributor' ) {
965 $uploadInfo['contributor'] = $this->handleContributor();
966 } elseif ( $tag == 'contents' ) {
967 $contents = $this->nodeContents();
968 $encoding = $this->reader
->getAttribute( 'encoding' );
969 if ( $encoding === 'base64' ) {
970 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
971 $uploadInfo['isTempSrc'] = true;
973 } elseif ( $tag != '#text' ) {
974 $this->warn( "Unhandled upload XML tag $tag" );
979 if ( $this->mImageBasePath
&& isset( $uploadInfo['rel'] ) ) {
980 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
981 if ( file_exists( $path ) ) {
982 $uploadInfo['fileSrc'] = $path;
983 $uploadInfo['isTempSrc'] = false;
987 if ( $this->mImportUploads
) {
988 return $this->processUpload( $pageInfo, $uploadInfo );
993 * @param string $contents
996 private function dumpTemp( $contents ) {
997 $filename = tempnam( wfTempDir(), 'importupload' );
998 file_put_contents( $filename, $contents );
1003 * @param array $pageInfo
1004 * @param array $uploadInfo
1007 private function processUpload( $pageInfo, $uploadInfo ) {
1008 $revision = new WikiRevision( $this->config
);
1009 $text = $uploadInfo['text'] ??
'';
1011 $revision->setTitle( $pageInfo['_title'] );
1012 $revision->setID( $pageInfo['id'] );
1013 $revision->setTimestamp( $uploadInfo['timestamp'] );
1014 $revision->setText( $text );
1015 $revision->setFilename( $uploadInfo['filename'] );
1016 if ( isset( $uploadInfo['archivename'] ) ) {
1017 $revision->setArchiveName( $uploadInfo['archivename'] );
1019 $revision->setSrc( $uploadInfo['src'] );
1020 if ( isset( $uploadInfo['fileSrc'] ) ) {
1021 $revision->setFileSrc( $uploadInfo['fileSrc'],
1022 !empty( $uploadInfo['isTempSrc'] ) );
1024 if ( isset( $uploadInfo['sha1base36'] ) ) {
1025 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
1027 $revision->setSize( intval( $uploadInfo['size'] ) );
1028 $revision->setComment( $uploadInfo['comment'] );
1030 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
1031 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
1033 if ( isset( $uploadInfo['contributor']['username'] ) ) {
1034 $revision->setUsername(
1035 $this->externalUserNames
->applyPrefix( $uploadInfo['contributor']['username'] )
1038 $revision->setNoUpdates( $this->mNoUpdates
);
1040 return call_user_func( $this->mUploadCallback
, $revision );
1046 private function handleContributor() {
1047 $fields = [ 'id', 'ip', 'username' ];
1050 if ( $this->reader
->isEmptyElement
) {
1053 while ( $this->reader
->read() ) {
1054 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
1055 $this->reader
->localName
== 'contributor' ) {
1059 $tag = $this->reader
->localName
;
1061 if ( in_array( $tag, $fields ) ) {
1062 $info[$tag] = $this->nodeContents();
1070 * @param string $text
1071 * @param string|null $ns
1072 * @return array|bool
1074 private function processTitle( $text, $ns = null ) {
1075 if ( is_null( $this->foreignNamespaces
) ) {
1076 $foreignTitleFactory = new NaiveForeignTitleFactory();
1078 $foreignTitleFactory = new NamespaceAwareForeignTitleFactory(
1079 $this->foreignNamespaces
);
1082 $foreignTitle = $foreignTitleFactory->createForeignTitle( $text,
1085 $title = $this->importTitleFactory
->createTitleFromForeignTitle(
1088 $commandLineMode = $this->config
->get( 'CommandLineMode' );
1089 if ( is_null( $title ) ) {
1090 # Invalid page title? Ignore the page
1091 $this->notice( 'import-error-invalid', $foreignTitle->getFullText() );
1093 } elseif ( $title->isExternal() ) {
1094 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
1096 } elseif ( !$title->canExist() ) {
1097 $this->notice( 'import-error-special', $title->getPrefixedText() );
1099 } elseif ( !$title->userCan( 'edit' ) && !$commandLineMode ) {
1100 # Do not import if the importing wiki user cannot edit this page
1101 $this->notice( 'import-error-edit', $title->getPrefixedText() );
1103 } elseif ( !$title->exists() && !$title->userCan( 'create' ) && !$commandLineMode ) {
1104 # Do not import if the importing wiki user cannot create this page
1105 $this->notice( 'import-error-create', $title->getPrefixedText() );
1109 return [ $title, $foreignTitle ];