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
28 * XML file reader for the page data importer.
30 * implements Special:Import
31 * @ingroup SpecialPage
34 private $reader = null;
35 private $foreignNamespaces = null;
36 private $mLogItemCallback, $mUploadCallback, $mRevisionCallback, $mPageCallback;
37 private $mSiteInfoCallback, $mPageOutCallback;
38 private $mNoticeCallback, $mDebug;
39 private $mImportUploads, $mImageBasePath;
40 private $mNoUpdates = false;
41 private $pageOffset = 0;
44 /** @var ImportTitleFactory */
45 private $importTitleFactory;
47 private $countableCache = [];
49 private $disableStatisticsUpdate = false;
50 private $usernamePrefix = 'imported';
51 private $assignKnownUsers = false;
52 private $triedCreations = [];
55 * Creates an ImportXMLReader drawing from the source provided
56 * @param ImportSource $source
57 * @param Config $config
60 function __construct( ImportSource
$source, Config
$config ) {
61 if ( !class_exists( 'XMLReader' ) ) {
62 throw new Exception( 'Import requires PHP to have been compiled with libxml support' );
65 $this->reader
= new XMLReader();
66 $this->config
= $config;
68 if ( !in_array( 'uploadsource', stream_get_wrappers() ) ) {
69 stream_wrapper_register( 'uploadsource', 'UploadSourceAdapter' );
71 $id = UploadSourceAdapter
::registerSource( $source );
73 // Enable the entity loader, as it is needed for loading external URLs via
74 // XMLReader::open (T86036)
75 $oldDisable = libxml_disable_entity_loader( false );
76 if ( defined( 'LIBXML_PARSEHUGE' ) ) {
77 $status = $this->reader
->open( "uploadsource://$id", null, LIBXML_PARSEHUGE
);
79 $status = $this->reader
->open( "uploadsource://$id" );
82 $error = libxml_get_last_error();
83 libxml_disable_entity_loader( $oldDisable );
84 throw new MWException( 'Encountered an internal error while initializing WikiImporter object: ' .
87 libxml_disable_entity_loader( $oldDisable );
90 $this->setPageCallback( [ $this, 'beforeImportPage' ] );
91 $this->setRevisionCallback( [ $this, "importRevision" ] );
92 $this->setUploadCallback( [ $this, 'importUpload' ] );
93 $this->setLogItemCallback( [ $this, 'importLogItem' ] );
94 $this->setPageOutCallback( [ $this, 'finishImportPage' ] );
96 $this->importTitleFactory
= new NaiveImportTitleFactory();
100 * @return null|XMLReader
102 public function getReader() {
103 return $this->reader
;
106 public function throwXmlError( $err ) {
107 $this->debug( "FAILURE: $err" );
108 wfDebug( "WikiImporter XML error: $err\n" );
111 public function debug( $data ) {
112 if ( $this->mDebug
) {
113 wfDebug( "IMPORT: $data\n" );
117 public function warn( $data ) {
118 wfDebug( "IMPORT: $data\n" );
121 public function notice( $msg /*, $param, ...*/ ) {
122 $params = func_get_args();
123 array_shift( $params );
125 if ( is_callable( $this->mNoticeCallback
) ) {
126 call_user_func( $this->mNoticeCallback
, $msg, $params );
127 } else { # No ImportReporter -> CLI
128 echo wfMessage( $msg, $params )->text() . "\n";
136 function setDebug( $debug ) {
137 $this->mDebug
= $debug;
141 * Set 'no updates' mode. In this mode, the link tables will not be updated by the importer
142 * @param bool $noupdates
144 function setNoUpdates( $noupdates ) {
145 $this->mNoUpdates
= $noupdates;
149 * Sets 'pageOffset' value. So it will skip the first n-1 pages
150 * and start from the nth page. It's 1-based indexing.
151 * @param int $nthPage
154 function setPageOffset( $nthPage ) {
155 $this->pageOffset
= $nthPage;
159 * Set a callback that displays notice messages
161 * @param callable $callback
164 public function setNoticeCallback( $callback ) {
165 return wfSetVar( $this->mNoticeCallback
, $callback );
169 * Sets the action to perform as each new page in the stream is reached.
170 * @param callable $callback
173 public function setPageCallback( $callback ) {
174 $previous = $this->mPageCallback
;
175 $this->mPageCallback
= $callback;
180 * Sets the action to perform as each page in the stream is completed.
181 * Callback accepts the page title (as a Title object), a second object
182 * with the original title form (in case it's been overridden into a
183 * local namespace), and a count of revisions.
185 * @param callable $callback
188 public function setPageOutCallback( $callback ) {
189 $previous = $this->mPageOutCallback
;
190 $this->mPageOutCallback
= $callback;
195 * Sets the action to perform as each page revision is reached.
196 * @param callable $callback
199 public function setRevisionCallback( $callback ) {
200 $previous = $this->mRevisionCallback
;
201 $this->mRevisionCallback
= $callback;
206 * Sets the action to perform as each file upload version is reached.
207 * @param callable $callback
210 public function setUploadCallback( $callback ) {
211 $previous = $this->mUploadCallback
;
212 $this->mUploadCallback
= $callback;
217 * Sets the action to perform as each log item reached.
218 * @param callable $callback
221 public function setLogItemCallback( $callback ) {
222 $previous = $this->mLogItemCallback
;
223 $this->mLogItemCallback
= $callback;
228 * Sets the action to perform when site info is encountered
229 * @param callable $callback
232 public function setSiteInfoCallback( $callback ) {
233 $previous = $this->mSiteInfoCallback
;
234 $this->mSiteInfoCallback
= $callback;
239 * Sets the factory object to use to convert ForeignTitle objects into local
241 * @param ImportTitleFactory $factory
243 public function setImportTitleFactory( $factory ) {
244 $this->importTitleFactory
= $factory;
248 * Set a target namespace to override the defaults
249 * @param null|int $namespace
252 public function setTargetNamespace( $namespace ) {
253 if ( is_null( $namespace ) ) {
254 // Don't override namespaces
255 $this->setImportTitleFactory( new NaiveImportTitleFactory() );
259 MWNamespace
::exists( intval( $namespace ) )
261 $namespace = intval( $namespace );
262 $this->setImportTitleFactory( new NamespaceImportTitleFactory( $namespace ) );
270 * Set a target root page under which all pages are imported
271 * @param null|string $rootpage
274 public function setTargetRootPage( $rootpage ) {
275 $status = Status
::newGood();
276 if ( is_null( $rootpage ) ) {
278 $this->setImportTitleFactory( new NaiveImportTitleFactory() );
279 } elseif ( $rootpage !== '' ) {
280 $rootpage = rtrim( $rootpage, '/' ); // avoid double slashes
281 $title = Title
::newFromText( $rootpage );
283 if ( !$title ||
$title->isExternal() ) {
284 $status->fatal( 'import-rootpage-invalid' );
286 if ( !MWNamespace
::hasSubpages( $title->getNamespace() ) ) {
289 $displayNSText = $title->getNamespace() == NS_MAIN
290 ?
wfMessage( 'blanknamespace' )->text()
291 : $wgContLang->getNsText( $title->getNamespace() );
292 $status->fatal( 'import-rootpage-nosubpage', $displayNSText );
294 // set namespace to 'all', so the namespace check in processTitle() can pass
295 $this->setTargetNamespace( null );
296 $this->setImportTitleFactory( new SubpageImportTitleFactory( $title ) );
306 public function setImageBasePath( $dir ) {
307 $this->mImageBasePath
= $dir;
311 * @param bool $import
313 public function setImportUploads( $import ) {
314 $this->mImportUploads
= $import;
319 * @param string $usernamePrefix Prefix to apply to unknown (and possibly also known) usernames
320 * @param bool $assignKnownUsers Whether to apply the prefix to usernames that exist locally
322 public function setUsernamePrefix( $usernamePrefix, $assignKnownUsers ) {
323 $this->usernamePrefix
= rtrim( (string)$usernamePrefix, ':>' );
324 $this->assignKnownUsers
= (bool)$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 $args = func_get_args();
434 return Hooks
::run( 'AfterImportPage', $args );
438 * Alternate per-revision callback, for debugging.
439 * @param WikiRevision &$revision
441 public function debugRevisionHandler( &$revision ) {
442 $this->debug( "Got revision:" );
443 if ( is_object( $revision->title
) ) {
444 $this->debug( "-- Title: " . $revision->title
->getPrefixedText() );
446 $this->debug( "-- Title: <invalid>" );
448 $this->debug( "-- User: " . $revision->user_text
);
449 $this->debug( "-- Timestamp: " . $revision->timestamp
);
450 $this->debug( "-- Comment: " . $revision->comment
);
451 $this->debug( "-- Text: " . $revision->text
);
455 * Notify the callback function of site info
456 * @param array $siteInfo
459 private function siteInfoCallback( $siteInfo ) {
460 if ( isset( $this->mSiteInfoCallback
) ) {
461 return call_user_func_array( $this->mSiteInfoCallback
,
462 [ $siteInfo, $this ] );
469 * Notify the callback function when a new "<page>" is reached.
470 * @param Title $title
472 function pageCallback( $title ) {
473 if ( isset( $this->mPageCallback
) ) {
474 call_user_func( $this->mPageCallback
, $title );
479 * Notify the callback function when a "</page>" is closed.
480 * @param Title $title
481 * @param ForeignTitle $foreignTitle
482 * @param int $revCount
483 * @param int $sucCount Number of revisions for which callback returned true
484 * @param array $pageInfo Associative array of page information
486 private function pageOutCallback( $title, $foreignTitle, $revCount,
487 $sucCount, $pageInfo ) {
488 if ( isset( $this->mPageOutCallback
) ) {
489 $args = func_get_args();
490 call_user_func_array( $this->mPageOutCallback
, $args );
495 * Notify the callback function of a revision
496 * @param WikiRevision $revision
499 private function revisionCallback( $revision ) {
500 if ( isset( $this->mRevisionCallback
) ) {
501 return call_user_func_array( $this->mRevisionCallback
,
502 [ $revision, $this ] );
509 * Notify the callback function of a new log item
510 * @param WikiRevision $revision
513 private function logItemCallback( $revision ) {
514 if ( isset( $this->mLogItemCallback
) ) {
515 return call_user_func_array( $this->mLogItemCallback
,
516 [ $revision, $this ] );
523 * Retrieves the contents of the named attribute of the current element.
524 * @param string $attr The name of the attribute
525 * @return string The value of the attribute or an empty string if it is not set in the current
528 public function nodeAttribute( $attr ) {
529 return $this->reader
->getAttribute( $attr );
533 * Shouldn't something like this be built-in to XMLReader?
534 * Fetches text contents of the current element, assuming
535 * no sub-elements or such scary things.
539 public function nodeContents() {
540 if ( $this->reader
->isEmptyElement
) {
544 while ( $this->reader
->read() ) {
545 switch ( $this->reader
->nodeType
) {
546 case XMLReader
::TEXT
:
547 case XMLReader
::CDATA
:
548 case XMLReader
::SIGNIFICANT_WHITESPACE
:
549 $buffer .= $this->reader
->value
;
551 case XMLReader
::END_ELEMENT
:
556 $this->reader
->close();
561 * Primary entry point
563 * @throws MWException
566 public function doImport() {
567 // Calls to reader->read need to be wrapped in calls to
568 // libxml_disable_entity_loader() to avoid local file
569 // inclusion attacks (T48932).
570 $oldDisable = libxml_disable_entity_loader( true );
571 $this->reader
->read();
573 if ( $this->reader
->localName
!= 'mediawiki' ) {
574 libxml_disable_entity_loader( $oldDisable );
575 throw new MWException( "Expected <mediawiki> tag, got " .
576 $this->reader
->localName
);
578 $this->debug( "<mediawiki> tag is correct." );
580 $this->debug( "Starting primary dump processing loop." );
582 $keepReading = $this->reader
->read();
587 while ( $keepReading ) {
588 $tag = $this->reader
->localName
;
589 if ( $this->pageOffset
) {
590 if ( $tag === 'page' ) {
593 if ( $pageCount < $this->pageOffset
) {
594 $keepReading = $this->reader
->next();
598 $type = $this->reader
->nodeType
;
600 if ( !Hooks
::run( 'ImportHandleToplevelXMLTag', [ $this ] ) ) {
602 } elseif ( $tag == 'mediawiki' && $type == XMLReader
::END_ELEMENT
) {
604 } elseif ( $tag == 'siteinfo' ) {
605 $this->handleSiteInfo();
606 } elseif ( $tag == 'page' ) {
608 } elseif ( $tag == 'logitem' ) {
609 $this->handleLogItem();
610 } elseif ( $tag != '#text' ) {
611 $this->warn( "Unhandled top-level XML tag $tag" );
617 $keepReading = $this->reader
->next();
619 $this->debug( "Skip" );
621 $keepReading = $this->reader
->read();
624 } catch ( Exception
$ex ) {
629 libxml_disable_entity_loader( $oldDisable );
630 $this->reader
->close();
639 private function handleSiteInfo() {
640 $this->debug( "Enter site info handler." );
643 // Fields that can just be stuffed in the siteInfo object
644 $normalFields = [ 'sitename', 'base', 'generator', 'case' ];
646 while ( $this->reader
->read() ) {
647 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
648 $this->reader
->localName
== 'siteinfo' ) {
652 $tag = $this->reader
->localName
;
654 if ( $tag == 'namespace' ) {
655 $this->foreignNamespaces
[$this->nodeAttribute( 'key' )] =
656 $this->nodeContents();
657 } elseif ( in_array( $tag, $normalFields ) ) {
658 $siteInfo[$tag] = $this->nodeContents();
662 $siteInfo['_namespaces'] = $this->foreignNamespaces
;
663 $this->siteInfoCallback( $siteInfo );
666 private function handleLogItem() {
667 $this->debug( "Enter log item handler." );
670 // Fields that can just be stuffed in the pageInfo object
671 $normalFields = [ 'id', 'comment', 'type', 'action', 'timestamp',
672 'logtitle', 'params' ];
674 while ( $this->reader
->read() ) {
675 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
676 $this->reader
->localName
== 'logitem' ) {
680 $tag = $this->reader
->localName
;
682 if ( !Hooks
::run( 'ImportHandleLogItemXMLTag', [
686 } elseif ( in_array( $tag, $normalFields ) ) {
687 $logInfo[$tag] = $this->nodeContents();
688 } elseif ( $tag == 'contributor' ) {
689 $logInfo['contributor'] = $this->handleContributor();
690 } elseif ( $tag != '#text' ) {
691 $this->warn( "Unhandled log-item XML tag $tag" );
695 $this->processLogItem( $logInfo );
699 * @param array $logInfo
702 private function processLogItem( $logInfo ) {
703 $revision = new WikiRevision( $this->config
);
705 if ( isset( $logInfo['id'] ) ) {
706 $revision->setID( $logInfo['id'] );
708 $revision->setType( $logInfo['type'] );
709 $revision->setAction( $logInfo['action'] );
710 if ( isset( $logInfo['timestamp'] ) ) {
711 $revision->setTimestamp( $logInfo['timestamp'] );
713 if ( isset( $logInfo['params'] ) ) {
714 $revision->setParams( $logInfo['params'] );
716 if ( isset( $logInfo['logtitle'] ) ) {
717 // @todo Using Title for non-local titles is a recipe for disaster.
718 // We should use ForeignTitle here instead.
719 $revision->setTitle( Title
::newFromText( $logInfo['logtitle'] ) );
722 $revision->setNoUpdates( $this->mNoUpdates
);
724 if ( isset( $logInfo['comment'] ) ) {
725 $revision->setComment( $logInfo['comment'] );
728 if ( isset( $logInfo['contributor']['ip'] ) ) {
729 $revision->setUserIP( $logInfo['contributor']['ip'] );
732 if ( !isset( $logInfo['contributor']['username'] ) ) {
733 $revision->setUsername( $this->usernamePrefix
. '>Unknown user' );
735 $revision->setUsername( $this->prefixUsername( $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 isset( $pageInfo['ns'] ) ?
$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 $revision = new WikiRevision( $this->config
);
894 if ( isset( $revisionInfo['id'] ) ) {
895 $revision->setID( $revisionInfo['id'] );
897 if ( isset( $revisionInfo['model'] ) ) {
898 $revision->setModel( $revisionInfo['model'] );
900 if ( isset( $revisionInfo['format'] ) ) {
901 $revision->setFormat( $revisionInfo['format'] );
903 $revision->setTitle( $pageInfo['_title'] );
905 if ( isset( $revisionInfo['text'] ) ) {
906 $handler = $revision->getContentHandler();
907 $text = $handler->importTransform(
908 $revisionInfo['text'],
909 $revision->getFormat() );
911 $revision->setText( $text );
913 if ( isset( $revisionInfo['timestamp'] ) ) {
914 $revision->setTimestamp( $revisionInfo['timestamp'] );
916 $revision->setTimestamp( wfTimestampNow() );
919 if ( isset( $revisionInfo['comment'] ) ) {
920 $revision->setComment( $revisionInfo['comment'] );
923 if ( isset( $revisionInfo['minor'] ) ) {
924 $revision->setMinor( true );
926 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
927 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
928 } elseif ( isset( $revisionInfo['contributor']['username'] ) ) {
929 $revision->setUsername( $this->prefixUsername( $revisionInfo['contributor']['username'] ) );
931 $revision->setUsername( $this->usernamePrefix
. '>Unknown user' );
933 if ( isset( $revisionInfo['sha1'] ) ) {
934 $revision->setSha1Base36( $revisionInfo['sha1'] );
936 $revision->setNoUpdates( $this->mNoUpdates
);
938 return $this->revisionCallback( $revision );
942 * @param array $pageInfo
945 private function handleUpload( &$pageInfo ) {
946 $this->debug( "Enter upload handler" );
949 $normalFields = [ 'timestamp', 'comment', 'filename', 'text',
950 'src', 'size', 'sha1base36', 'archivename', 'rel' ];
954 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
955 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
956 $this->reader
->localName
== 'upload' ) {
960 $tag = $this->reader
->localName
;
962 if ( !Hooks
::run( 'ImportHandleUploadXMLTag', [
966 } elseif ( in_array( $tag, $normalFields ) ) {
967 $uploadInfo[$tag] = $this->nodeContents();
968 } elseif ( $tag == 'contributor' ) {
969 $uploadInfo['contributor'] = $this->handleContributor();
970 } elseif ( $tag == 'contents' ) {
971 $contents = $this->nodeContents();
972 $encoding = $this->reader
->getAttribute( 'encoding' );
973 if ( $encoding === 'base64' ) {
974 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
975 $uploadInfo['isTempSrc'] = true;
977 } elseif ( $tag != '#text' ) {
978 $this->warn( "Unhandled upload XML tag $tag" );
983 if ( $this->mImageBasePath
&& isset( $uploadInfo['rel'] ) ) {
984 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
985 if ( file_exists( $path ) ) {
986 $uploadInfo['fileSrc'] = $path;
987 $uploadInfo['isTempSrc'] = false;
991 if ( $this->mImportUploads
) {
992 return $this->processUpload( $pageInfo, $uploadInfo );
997 * @param string $contents
1000 private function dumpTemp( $contents ) {
1001 $filename = tempnam( wfTempDir(), 'importupload' );
1002 file_put_contents( $filename, $contents );
1007 * @param array $pageInfo
1008 * @param array $uploadInfo
1011 private function processUpload( $pageInfo, $uploadInfo ) {
1012 $revision = new WikiRevision( $this->config
);
1013 $text = isset( $uploadInfo['text'] ) ?
$uploadInfo['text'] : '';
1015 $revision->setTitle( $pageInfo['_title'] );
1016 $revision->setID( $pageInfo['id'] );
1017 $revision->setTimestamp( $uploadInfo['timestamp'] );
1018 $revision->setText( $text );
1019 $revision->setFilename( $uploadInfo['filename'] );
1020 if ( isset( $uploadInfo['archivename'] ) ) {
1021 $revision->setArchiveName( $uploadInfo['archivename'] );
1023 $revision->setSrc( $uploadInfo['src'] );
1024 if ( isset( $uploadInfo['fileSrc'] ) ) {
1025 $revision->setFileSrc( $uploadInfo['fileSrc'],
1026 !empty( $uploadInfo['isTempSrc'] ) );
1028 if ( isset( $uploadInfo['sha1base36'] ) ) {
1029 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
1031 $revision->setSize( intval( $uploadInfo['size'] ) );
1032 $revision->setComment( $uploadInfo['comment'] );
1034 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
1035 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
1037 if ( isset( $uploadInfo['contributor']['username'] ) ) {
1038 $revision->setUsername( $this->prefixUsername( $uploadInfo['contributor']['username'] ) );
1040 $revision->setNoUpdates( $this->mNoUpdates
);
1042 return call_user_func( $this->mUploadCallback
, $revision );
1046 * Add an interwiki prefix to the username, if appropriate
1048 * @param string $name Name being imported
1049 * @return string Name, possibly with the prefix prepended.
1051 protected function prefixUsername( $name ) {
1052 if ( !User
::isUsableName( $name ) ) {
1056 if ( $this->assignKnownUsers
) {
1057 if ( User
::idFromName( $name ) ) {
1061 // See if any extension wants to create it.
1062 if ( !isset( $this->triedCreations
[$name] ) ) {
1063 $this->triedCreations
[$name] = true;
1064 if ( !Hooks
::run( 'ImportHandleUnknownUser', [ $name ] ) &&
1065 User
::idFromName( $name, User
::READ_LATEST
)
1072 return substr( $this->usernamePrefix
. '>' . $name, 0, 255 );
1078 private function handleContributor() {
1079 $fields = [ 'id', 'ip', 'username' ];
1082 if ( $this->reader
->isEmptyElement
) {
1085 while ( $this->reader
->read() ) {
1086 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
1087 $this->reader
->localName
== 'contributor' ) {
1091 $tag = $this->reader
->localName
;
1093 if ( in_array( $tag, $fields ) ) {
1094 $info[$tag] = $this->nodeContents();
1102 * @param string $text
1103 * @param string|null $ns
1104 * @return array|bool
1106 private function processTitle( $text, $ns = null ) {
1107 if ( is_null( $this->foreignNamespaces
) ) {
1108 $foreignTitleFactory = new NaiveForeignTitleFactory();
1110 $foreignTitleFactory = new NamespaceAwareForeignTitleFactory(
1111 $this->foreignNamespaces
);
1114 $foreignTitle = $foreignTitleFactory->createForeignTitle( $text,
1117 $title = $this->importTitleFactory
->createTitleFromForeignTitle(
1120 $commandLineMode = $this->config
->get( 'CommandLineMode' );
1121 if ( is_null( $title ) ) {
1122 # Invalid page title? Ignore the page
1123 $this->notice( 'import-error-invalid', $foreignTitle->getFullText() );
1125 } elseif ( $title->isExternal() ) {
1126 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
1128 } elseif ( !$title->canExist() ) {
1129 $this->notice( 'import-error-special', $title->getPrefixedText() );
1131 } elseif ( !$title->userCan( 'edit' ) && !$commandLineMode ) {
1132 # Do not import if the importing wiki user cannot edit this page
1133 $this->notice( 'import-error-edit', $title->getPrefixedText() );
1135 } elseif ( !$title->exists() && !$title->userCan( 'create' ) && !$commandLineMode ) {
1136 # Do not import if the importing wiki user cannot create this page
1137 $this->notice( 'import-error-create', $title->getPrefixedText() );
1141 return [ $title, $foreignTitle ];