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
26 use MediaWiki\MediaWikiServices
;
29 * XML file reader for the page data importer.
31 * implements Special:Import
32 * @ingroup SpecialPage
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 private $pageOffset = 0;
45 /** @var ImportTitleFactory */
46 private $importTitleFactory;
48 private $countableCache = [];
50 private $disableStatisticsUpdate = false;
53 * Creates an ImportXMLReader drawing from the source provided
54 * @param ImportSource $source
55 * @param Config $config
58 function __construct( ImportSource
$source, Config
$config = null ) {
59 if ( !class_exists( 'XMLReader' ) ) {
60 throw new Exception( 'Import requires PHP to have been compiled with libxml support' );
63 $this->reader
= new XMLReader();
65 wfDeprecated( __METHOD__
. ' without a Config instance', '1.25' );
66 $config = MediaWikiServices
::getInstance()->getMainConfig();
68 $this->config
= $config;
70 if ( !in_array( 'uploadsource', stream_get_wrappers() ) ) {
71 stream_wrapper_register( 'uploadsource', 'UploadSourceAdapter' );
73 $id = UploadSourceAdapter
::registerSource( $source );
75 // Enable the entity loader, as it is needed for loading external URLs via
76 // XMLReader::open (T86036)
77 $oldDisable = libxml_disable_entity_loader( false );
78 if ( defined( 'LIBXML_PARSEHUGE' ) ) {
79 $status = $this->reader
->open( "uploadsource://$id", null, LIBXML_PARSEHUGE
);
81 $status = $this->reader
->open( "uploadsource://$id" );
84 $error = libxml_get_last_error();
85 libxml_disable_entity_loader( $oldDisable );
86 throw new MWException( 'Encountered an internal error while initializing WikiImporter object: ' .
89 libxml_disable_entity_loader( $oldDisable );
92 $this->setPageCallback( [ $this, 'beforeImportPage' ] );
93 $this->setRevisionCallback( [ $this, "importRevision" ] );
94 $this->setUploadCallback( [ $this, 'importUpload' ] );
95 $this->setLogItemCallback( [ $this, 'importLogItem' ] );
96 $this->setPageOutCallback( [ $this, 'finishImportPage' ] );
98 $this->importTitleFactory
= new NaiveImportTitleFactory();
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 /*, $param, ...*/ ) {
124 $params = func_get_args();
125 array_shift( $params );
127 if ( is_callable( $this->mNoticeCallback
) ) {
128 call_user_func( $this->mNoticeCallback
, $msg, $params );
129 } else { # No ImportReporter -> CLI
130 echo wfMessage( $msg, $params )->text() . "\n";
138 function setDebug( $debug ) {
139 $this->mDebug
= $debug;
143 * Set 'no updates' mode. In this mode, the link tables will not be updated by the importer
144 * @param bool $noupdates
146 function setNoUpdates( $noupdates ) {
147 $this->mNoUpdates
= $noupdates;
151 * Sets 'pageOffset' value. So it will skip the first n-1 pages
152 * and start from the nth page. It's 1-based indexing.
153 * @param int $nthPage
156 function setPageOffset( $nthPage ) {
157 $this->pageOffset
= $nthPage;
161 * Set a callback that displays notice messages
163 * @param callable $callback
166 public function setNoticeCallback( $callback ) {
167 return wfSetVar( $this->mNoticeCallback
, $callback );
171 * Sets the action to perform as each new page in the stream is reached.
172 * @param callable $callback
175 public function setPageCallback( $callback ) {
176 $previous = $this->mPageCallback
;
177 $this->mPageCallback
= $callback;
182 * Sets the action to perform as each page in the stream is completed.
183 * Callback accepts the page title (as a Title object), a second object
184 * with the original title form (in case it's been overridden into a
185 * local namespace), and a count of revisions.
187 * @param callable $callback
190 public function setPageOutCallback( $callback ) {
191 $previous = $this->mPageOutCallback
;
192 $this->mPageOutCallback
= $callback;
197 * Sets the action to perform as each page revision is reached.
198 * @param callable $callback
201 public function setRevisionCallback( $callback ) {
202 $previous = $this->mRevisionCallback
;
203 $this->mRevisionCallback
= $callback;
208 * Sets the action to perform as each file upload version is reached.
209 * @param callable $callback
212 public function setUploadCallback( $callback ) {
213 $previous = $this->mUploadCallback
;
214 $this->mUploadCallback
= $callback;
219 * Sets the action to perform as each log item reached.
220 * @param callable $callback
223 public function setLogItemCallback( $callback ) {
224 $previous = $this->mLogItemCallback
;
225 $this->mLogItemCallback
= $callback;
230 * Sets the action to perform when site info is encountered
231 * @param callable $callback
234 public function setSiteInfoCallback( $callback ) {
235 $previous = $this->mSiteInfoCallback
;
236 $this->mSiteInfoCallback
= $callback;
241 * Sets the factory object to use to convert ForeignTitle objects into local
243 * @param ImportTitleFactory $factory
245 public function setImportTitleFactory( $factory ) {
246 $this->importTitleFactory
= $factory;
250 * Set a target namespace to override the defaults
251 * @param null|int $namespace
254 public function setTargetNamespace( $namespace ) {
255 if ( is_null( $namespace ) ) {
256 // Don't override namespaces
257 $this->setImportTitleFactory( new NaiveImportTitleFactory() );
261 MWNamespace
::exists( intval( $namespace ) )
263 $namespace = intval( $namespace );
264 $this->setImportTitleFactory( new NamespaceImportTitleFactory( $namespace ) );
272 * Set a target root page under which all pages are imported
273 * @param null|string $rootpage
276 public function setTargetRootPage( $rootpage ) {
277 $status = Status
::newGood();
278 if ( is_null( $rootpage ) ) {
280 $this->setImportTitleFactory( new NaiveImportTitleFactory() );
281 } elseif ( $rootpage !== '' ) {
282 $rootpage = rtrim( $rootpage, '/' ); // avoid double slashes
283 $title = Title
::newFromText( $rootpage );
285 if ( !$title ||
$title->isExternal() ) {
286 $status->fatal( 'import-rootpage-invalid' );
288 if ( !MWNamespace
::hasSubpages( $title->getNamespace() ) ) {
291 $displayNSText = $title->getNamespace() == NS_MAIN
292 ?
wfMessage( 'blanknamespace' )->text()
293 : $wgContLang->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 ) );
308 public function setImageBasePath( $dir ) {
309 $this->mImageBasePath
= $dir;
313 * @param bool $import
315 public function setImportUploads( $import ) {
316 $this->mImportUploads
= $import;
320 * Statistics update can cause a lot of time
323 public function disableStatisticsUpdate() {
324 $this->disableStatisticsUpdate
= true;
328 * Default per-page callback. Sets up some things related to site statistics
329 * @param array $titleAndForeignTitle Two-element array, with Title object at
330 * index 0 and ForeignTitle object at index 1
333 public function beforeImportPage( $titleAndForeignTitle ) {
334 $title = $titleAndForeignTitle[0];
335 $page = WikiPage
::factory( $title );
336 $this->countableCache
['title_' . $title->getPrefixedText()] = $page->isCountable();
341 * Default per-revision callback, performs the import.
342 * @param WikiRevision $revision
345 public function importRevision( $revision ) {
346 if ( !$revision->getContentHandler()->canBeUsedOn( $revision->getTitle() ) ) {
347 $this->notice( 'import-error-bad-location',
348 $revision->getTitle()->getPrefixedText(),
350 $revision->getModel(),
351 $revision->getFormat() );
357 return $revision->importOldRevision();
358 } catch ( MWContentSerializationException
$ex ) {
359 $this->notice( 'import-error-unserialize',
360 $revision->getTitle()->getPrefixedText(),
362 $revision->getModel(),
363 $revision->getFormat() );
370 * Default per-revision callback, performs the import.
371 * @param WikiRevision $revision
374 public function importLogItem( $revision ) {
375 return $revision->importLogItem();
380 * @param WikiRevision $revision
383 public function importUpload( $revision ) {
384 return $revision->importUpload();
388 * Mostly for hook use
389 * @param Title $title
390 * @param ForeignTitle $foreignTitle
391 * @param int $revCount
392 * @param int $sRevCount
393 * @param array $pageInfo
396 public function finishImportPage( $title, $foreignTitle, $revCount,
397 $sRevCount, $pageInfo ) {
399 // Update article count statistics (T42009)
400 // The normal counting logic in WikiPage->doEditUpdates() is designed for
401 // one-revision-at-a-time editing, not bulk imports. In this situation it
402 // suffers from issues of replica DB lag. We let WikiPage handle the total page
403 // and revision count, and we implement our own custom logic for the
404 // article (content page) count.
405 if ( !$this->disableStatisticsUpdate
) {
406 $page = WikiPage
::factory( $title );
407 $page->loadPageData( 'fromdbmaster' );
408 $content = $page->getContent();
409 if ( $content === null ) {
410 wfDebug( __METHOD__
. ': Skipping article count adjustment for ' . $title .
411 ' because WikiPage::getContent() returned null' );
413 $editInfo = $page->prepareContentForEdit( $content );
414 $countKey = 'title_' . $title->getPrefixedText();
415 $countable = $page->isCountable( $editInfo );
416 if ( array_key_exists( $countKey, $this->countableCache
) &&
417 $countable != $this->countableCache
[$countKey] ) {
418 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [
419 'articles' => ( (int)$countable - (int)$this->countableCache
[$countKey] )
425 $args = func_get_args();
426 return Hooks
::run( 'AfterImportPage', $args );
430 * Alternate per-revision callback, for debugging.
431 * @param WikiRevision $revision
433 public function debugRevisionHandler( &$revision ) {
434 $this->debug( "Got revision:" );
435 if ( is_object( $revision->title
) ) {
436 $this->debug( "-- Title: " . $revision->title
->getPrefixedText() );
438 $this->debug( "-- Title: <invalid>" );
440 $this->debug( "-- User: " . $revision->user_text
);
441 $this->debug( "-- Timestamp: " . $revision->timestamp
);
442 $this->debug( "-- Comment: " . $revision->comment
);
443 $this->debug( "-- Text: " . $revision->text
);
447 * Notify the callback function of site info
448 * @param array $siteInfo
451 private function siteInfoCallback( $siteInfo ) {
452 if ( isset( $this->mSiteInfoCallback
) ) {
453 return call_user_func_array( $this->mSiteInfoCallback
,
454 [ $siteInfo, $this ] );
461 * Notify the callback function when a new "<page>" is reached.
462 * @param Title $title
464 function pageCallback( $title ) {
465 if ( isset( $this->mPageCallback
) ) {
466 call_user_func( $this->mPageCallback
, $title );
471 * Notify the callback function when a "</page>" is closed.
472 * @param Title $title
473 * @param ForeignTitle $foreignTitle
474 * @param int $revCount
475 * @param int $sucCount Number of revisions for which callback returned true
476 * @param array $pageInfo Associative array of page information
478 private function pageOutCallback( $title, $foreignTitle, $revCount,
479 $sucCount, $pageInfo ) {
480 if ( isset( $this->mPageOutCallback
) ) {
481 $args = func_get_args();
482 call_user_func_array( $this->mPageOutCallback
, $args );
487 * Notify the callback function of a revision
488 * @param WikiRevision $revision
491 private function revisionCallback( $revision ) {
492 if ( isset( $this->mRevisionCallback
) ) {
493 return call_user_func_array( $this->mRevisionCallback
,
494 [ $revision, $this ] );
501 * Notify the callback function of a new log item
502 * @param WikiRevision $revision
505 private function logItemCallback( $revision ) {
506 if ( isset( $this->mLogItemCallback
) ) {
507 return call_user_func_array( $this->mLogItemCallback
,
508 [ $revision, $this ] );
515 * Retrieves the contents of the named attribute of the current element.
516 * @param string $attr The name of the attribute
517 * @return string The value of the attribute or an empty string if it is not set in the current
520 public function nodeAttribute( $attr ) {
521 return $this->reader
->getAttribute( $attr );
525 * Shouldn't something like this be built-in to XMLReader?
526 * Fetches text contents of the current element, assuming
527 * no sub-elements or such scary things.
531 public function nodeContents() {
532 if ( $this->reader
->isEmptyElement
) {
536 while ( $this->reader
->read() ) {
537 switch ( $this->reader
->nodeType
) {
538 case XMLReader
::TEXT
:
539 case XMLReader
::CDATA
:
540 case XMLReader
::SIGNIFICANT_WHITESPACE
:
541 $buffer .= $this->reader
->value
;
543 case XMLReader
::END_ELEMENT
:
548 $this->reader
->close();
553 * Primary entry point
554 * @throws MWException
557 public function doImport() {
558 // Calls to reader->read need to be wrapped in calls to
559 // libxml_disable_entity_loader() to avoid local file
560 // inclusion attacks (T48932).
561 $oldDisable = libxml_disable_entity_loader( true );
562 $this->reader
->read();
564 if ( $this->reader
->localName
!= 'mediawiki' ) {
565 libxml_disable_entity_loader( $oldDisable );
566 throw new MWException( "Expected <mediawiki> tag, got " .
567 $this->reader
->localName
);
569 $this->debug( "<mediawiki> tag is correct." );
571 $this->debug( "Starting primary dump processing loop." );
573 $keepReading = $this->reader
->read();
578 while ( $keepReading ) {
579 $tag = $this->reader
->localName
;
580 if ( $this->pageOffset
) {
581 if ( $tag === 'page' ) {
584 if ( $pageCount < $this->pageOffset
) {
585 $keepReading = $this->reader
->next();
589 $type = $this->reader
->nodeType
;
591 if ( !Hooks
::run( 'ImportHandleToplevelXMLTag', [ $this ] ) ) {
593 } elseif ( $tag == 'mediawiki' && $type == XMLReader
::END_ELEMENT
) {
595 } elseif ( $tag == 'siteinfo' ) {
596 $this->handleSiteInfo();
597 } elseif ( $tag == 'page' ) {
599 } elseif ( $tag == 'logitem' ) {
600 $this->handleLogItem();
601 } elseif ( $tag != '#text' ) {
602 $this->warn( "Unhandled top-level XML tag $tag" );
608 $keepReading = $this->reader
->next();
610 $this->debug( "Skip" );
612 $keepReading = $this->reader
->read();
615 } catch ( Exception
$ex ) {
620 libxml_disable_entity_loader( $oldDisable );
621 $this->reader
->close();
630 private function handleSiteInfo() {
631 $this->debug( "Enter site info handler." );
634 // Fields that can just be stuffed in the siteInfo object
635 $normalFields = [ 'sitename', 'base', 'generator', 'case' ];
637 while ( $this->reader
->read() ) {
638 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
639 $this->reader
->localName
== 'siteinfo' ) {
643 $tag = $this->reader
->localName
;
645 if ( $tag == 'namespace' ) {
646 $this->foreignNamespaces
[$this->nodeAttribute( 'key' )] =
647 $this->nodeContents();
648 } elseif ( in_array( $tag, $normalFields ) ) {
649 $siteInfo[$tag] = $this->nodeContents();
653 $siteInfo['_namespaces'] = $this->foreignNamespaces
;
654 $this->siteInfoCallback( $siteInfo );
657 private function handleLogItem() {
658 $this->debug( "Enter log item handler." );
661 // Fields that can just be stuffed in the pageInfo object
662 $normalFields = [ 'id', 'comment', 'type', 'action', 'timestamp',
663 'logtitle', 'params' ];
665 while ( $this->reader
->read() ) {
666 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
667 $this->reader
->localName
== 'logitem' ) {
671 $tag = $this->reader
->localName
;
673 if ( !Hooks
::run( 'ImportHandleLogItemXMLTag', [
677 } elseif ( in_array( $tag, $normalFields ) ) {
678 $logInfo[$tag] = $this->nodeContents();
679 } elseif ( $tag == 'contributor' ) {
680 $logInfo['contributor'] = $this->handleContributor();
681 } elseif ( $tag != '#text' ) {
682 $this->warn( "Unhandled log-item XML tag $tag" );
686 $this->processLogItem( $logInfo );
690 * @param array $logInfo
693 private function processLogItem( $logInfo ) {
695 $revision = new WikiRevision( $this->config
);
697 if ( isset( $logInfo['id'] ) ) {
698 $revision->setID( $logInfo['id'] );
700 $revision->setType( $logInfo['type'] );
701 $revision->setAction( $logInfo['action'] );
702 if ( isset( $logInfo['timestamp'] ) ) {
703 $revision->setTimestamp( $logInfo['timestamp'] );
705 if ( isset( $logInfo['params'] ) ) {
706 $revision->setParams( $logInfo['params'] );
708 if ( isset( $logInfo['logtitle'] ) ) {
709 // @todo Using Title for non-local titles is a recipe for disaster.
710 // We should use ForeignTitle here instead.
711 $revision->setTitle( Title
::newFromText( $logInfo['logtitle'] ) );
714 $revision->setNoUpdates( $this->mNoUpdates
);
716 if ( isset( $logInfo['comment'] ) ) {
717 $revision->setComment( $logInfo['comment'] );
720 if ( isset( $logInfo['contributor']['ip'] ) ) {
721 $revision->setUserIP( $logInfo['contributor']['ip'] );
724 if ( !isset( $logInfo['contributor']['username'] ) ) {
725 $revision->setUsername( 'Unknown user' );
727 $revision->setUsername( $logInfo['contributor']['username'] );
730 return $this->logItemCallback( $revision );
733 private function handlePage() {
735 $this->debug( "Enter page handler." );
736 $pageInfo = [ 'revisionCount' => 0, 'successfulRevisionCount' => 0 ];
738 // Fields that can just be stuffed in the pageInfo object
739 $normalFields = [ 'title', 'ns', 'id', 'redirect', 'restrictions' ];
744 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
745 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
746 $this->reader
->localName
== 'page' ) {
752 $tag = $this->reader
->localName
;
755 // The title is invalid, bail out of this page
757 } elseif ( !Hooks
::run( 'ImportHandlePageXMLTag', [ $this,
760 } elseif ( in_array( $tag, $normalFields ) ) {
764 // <title>Page</title>
765 // <redirect title="NewTitle"/>
767 // Because the redirect tag is built differently, we need special handling for that case.
768 if ( $tag == 'redirect' ) {
769 $pageInfo[$tag] = $this->nodeAttribute( 'title' );
771 $pageInfo[$tag] = $this->nodeContents();
773 } elseif ( $tag == 'revision' ||
$tag == 'upload' ) {
774 if ( !isset( $title ) ) {
775 $title = $this->processTitle( $pageInfo['title'],
776 isset( $pageInfo['ns'] ) ?
$pageInfo['ns'] : null );
778 // $title is either an array of two titles or false.
779 if ( is_array( $title ) ) {
780 $this->pageCallback( $title );
781 list( $pageInfo['_title'], $foreignTitle ) = $title;
789 if ( $tag == 'revision' ) {
790 $this->handleRevision( $pageInfo );
792 $this->handleUpload( $pageInfo );
795 } elseif ( $tag != '#text' ) {
796 $this->warn( "Unhandled page XML tag $tag" );
801 // @note $pageInfo is only set if a valid $title is processed above with
802 // no error. If we have a valid $title, then pageCallback is called
803 // above, $pageInfo['title'] is set and we do pageOutCallback here.
804 // If $pageInfo['_title'] is not set, then $foreignTitle is also not
805 // set since they both come from $title above.
806 if ( array_key_exists( '_title', $pageInfo ) ) {
807 $this->pageOutCallback( $pageInfo['_title'], $foreignTitle,
808 $pageInfo['revisionCount'],
809 $pageInfo['successfulRevisionCount'],
815 * @param array $pageInfo
817 private function handleRevision( &$pageInfo ) {
818 $this->debug( "Enter revision handler" );
821 $normalFields = [ 'id', 'timestamp', 'comment', 'minor', 'model', 'format', 'text' ];
825 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
826 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
827 $this->reader
->localName
== 'revision' ) {
831 $tag = $this->reader
->localName
;
833 if ( !Hooks
::run( 'ImportHandleRevisionXMLTag', [
834 $this, $pageInfo, $revisionInfo
837 } elseif ( in_array( $tag, $normalFields ) ) {
838 $revisionInfo[$tag] = $this->nodeContents();
839 } elseif ( $tag == 'contributor' ) {
840 $revisionInfo['contributor'] = $this->handleContributor();
841 } elseif ( $tag != '#text' ) {
842 $this->warn( "Unhandled revision XML tag $tag" );
847 $pageInfo['revisionCount']++
;
848 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
849 $pageInfo['successfulRevisionCount']++
;
854 * @param array $pageInfo
855 * @param array $revisionInfo
858 private function processRevision( $pageInfo, $revisionInfo ) {
859 global $wgMaxArticleSize;
861 // Make sure revisions won't violate $wgMaxArticleSize, which could lead to
862 // database errors and instability. Testing for revisions with only listed
863 // content models, as other content models might use serialization formats
864 // which aren't checked against $wgMaxArticleSize.
865 if ( ( !isset( $revisionInfo['model'] ) ||
866 in_array( $revisionInfo['model'], [
874 strlen( $revisionInfo['text'] ) > $wgMaxArticleSize * 1024
876 throw new MWException( 'The text of ' .
877 ( isset( $revisionInfo['id'] ) ?
878 "the revision with ID $revisionInfo[id]" :
880 ) . " exceeds the maximum allowable size ($wgMaxArticleSize KB)" );
883 $revision = new WikiRevision( $this->config
);
885 if ( isset( $revisionInfo['id'] ) ) {
886 $revision->setID( $revisionInfo['id'] );
888 if ( isset( $revisionInfo['model'] ) ) {
889 $revision->setModel( $revisionInfo['model'] );
891 if ( isset( $revisionInfo['format'] ) ) {
892 $revision->setFormat( $revisionInfo['format'] );
894 $revision->setTitle( $pageInfo['_title'] );
896 if ( isset( $revisionInfo['text'] ) ) {
897 $handler = $revision->getContentHandler();
898 $text = $handler->importTransform(
899 $revisionInfo['text'],
900 $revision->getFormat() );
902 $revision->setText( $text );
904 if ( isset( $revisionInfo['timestamp'] ) ) {
905 $revision->setTimestamp( $revisionInfo['timestamp'] );
907 $revision->setTimestamp( wfTimestampNow() );
910 if ( isset( $revisionInfo['comment'] ) ) {
911 $revision->setComment( $revisionInfo['comment'] );
914 if ( isset( $revisionInfo['minor'] ) ) {
915 $revision->setMinor( true );
917 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
918 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
919 } elseif ( isset( $revisionInfo['contributor']['username'] ) ) {
920 $revision->setUsername( $revisionInfo['contributor']['username'] );
922 $revision->setUsername( 'Unknown user' );
924 $revision->setNoUpdates( $this->mNoUpdates
);
926 return $this->revisionCallback( $revision );
930 * @param array $pageInfo
933 private function handleUpload( &$pageInfo ) {
934 $this->debug( "Enter upload handler" );
937 $normalFields = [ 'timestamp', 'comment', 'filename', 'text',
938 'src', 'size', 'sha1base36', 'archivename', 'rel' ];
942 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
943 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
944 $this->reader
->localName
== 'upload' ) {
948 $tag = $this->reader
->localName
;
950 if ( !Hooks
::run( 'ImportHandleUploadXMLTag', [
954 } elseif ( in_array( $tag, $normalFields ) ) {
955 $uploadInfo[$tag] = $this->nodeContents();
956 } elseif ( $tag == 'contributor' ) {
957 $uploadInfo['contributor'] = $this->handleContributor();
958 } elseif ( $tag == 'contents' ) {
959 $contents = $this->nodeContents();
960 $encoding = $this->reader
->getAttribute( 'encoding' );
961 if ( $encoding === 'base64' ) {
962 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
963 $uploadInfo['isTempSrc'] = true;
965 } elseif ( $tag != '#text' ) {
966 $this->warn( "Unhandled upload XML tag $tag" );
971 if ( $this->mImageBasePath
&& isset( $uploadInfo['rel'] ) ) {
972 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
973 if ( file_exists( $path ) ) {
974 $uploadInfo['fileSrc'] = $path;
975 $uploadInfo['isTempSrc'] = false;
979 if ( $this->mImportUploads
) {
980 return $this->processUpload( $pageInfo, $uploadInfo );
985 * @param string $contents
988 private function dumpTemp( $contents ) {
989 $filename = tempnam( wfTempDir(), 'importupload' );
990 file_put_contents( $filename, $contents );
995 * @param array $pageInfo
996 * @param array $uploadInfo
999 private function processUpload( $pageInfo, $uploadInfo ) {
1000 $revision = new WikiRevision( $this->config
);
1001 $text = isset( $uploadInfo['text'] ) ?
$uploadInfo['text'] : '';
1003 $revision->setTitle( $pageInfo['_title'] );
1004 $revision->setID( $pageInfo['id'] );
1005 $revision->setTimestamp( $uploadInfo['timestamp'] );
1006 $revision->setText( $text );
1007 $revision->setFilename( $uploadInfo['filename'] );
1008 if ( isset( $uploadInfo['archivename'] ) ) {
1009 $revision->setArchiveName( $uploadInfo['archivename'] );
1011 $revision->setSrc( $uploadInfo['src'] );
1012 if ( isset( $uploadInfo['fileSrc'] ) ) {
1013 $revision->setFileSrc( $uploadInfo['fileSrc'],
1014 !empty( $uploadInfo['isTempSrc'] ) );
1016 if ( isset( $uploadInfo['sha1base36'] ) ) {
1017 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
1019 $revision->setSize( intval( $uploadInfo['size'] ) );
1020 $revision->setComment( $uploadInfo['comment'] );
1022 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
1023 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
1025 if ( isset( $uploadInfo['contributor']['username'] ) ) {
1026 $revision->setUsername( $uploadInfo['contributor']['username'] );
1028 $revision->setNoUpdates( $this->mNoUpdates
);
1030 return call_user_func( $this->mUploadCallback
, $revision );
1036 private function handleContributor() {
1037 $fields = [ 'id', 'ip', 'username' ];
1040 if ( $this->reader
->isEmptyElement
) {
1043 while ( $this->reader
->read() ) {
1044 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
1045 $this->reader
->localName
== 'contributor' ) {
1049 $tag = $this->reader
->localName
;
1051 if ( in_array( $tag, $fields ) ) {
1052 $info[$tag] = $this->nodeContents();
1060 * @param string $text
1061 * @param string|null $ns
1062 * @return array|bool
1064 private function processTitle( $text, $ns = null ) {
1065 if ( is_null( $this->foreignNamespaces
) ) {
1066 $foreignTitleFactory = new NaiveForeignTitleFactory();
1068 $foreignTitleFactory = new NamespaceAwareForeignTitleFactory(
1069 $this->foreignNamespaces
);
1072 $foreignTitle = $foreignTitleFactory->createForeignTitle( $text,
1075 $title = $this->importTitleFactory
->createTitleFromForeignTitle(
1078 $commandLineMode = $this->config
->get( 'CommandLineMode' );
1079 if ( is_null( $title ) ) {
1080 # Invalid page title? Ignore the page
1081 $this->notice( 'import-error-invalid', $foreignTitle->getFullText() );
1083 } elseif ( $title->isExternal() ) {
1084 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
1086 } elseif ( !$title->canExist() ) {
1087 $this->notice( 'import-error-special', $title->getPrefixedText() );
1089 } elseif ( !$title->userCan( 'edit' ) && !$commandLineMode ) {
1090 # Do not import if the importing wiki user cannot edit this page
1091 $this->notice( 'import-error-edit', $title->getPrefixedText() );
1093 } elseif ( !$title->exists() && !$title->userCan( 'create' ) && !$commandLineMode ) {
1094 # Do not import if the importing wiki user cannot create this page
1095 $this->notice( 'import-error-create', $title->getPrefixedText() );
1099 return [ $title, $foreignTitle ];