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