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
562 * @throws MWException
565 public function doImport() {
566 // Calls to reader->read need to be wrapped in calls to
567 // libxml_disable_entity_loader() to avoid local file
568 // inclusion attacks (T48932).
569 $oldDisable = libxml_disable_entity_loader( true );
570 $this->reader
->read();
572 if ( $this->reader
->localName
!= 'mediawiki' ) {
573 libxml_disable_entity_loader( $oldDisable );
574 throw new MWException( "Expected <mediawiki> tag, got " .
575 $this->reader
->localName
);
577 $this->debug( "<mediawiki> tag is correct." );
579 $this->debug( "Starting primary dump processing loop." );
581 $keepReading = $this->reader
->read();
586 while ( $keepReading ) {
587 $tag = $this->reader
->localName
;
588 if ( $this->pageOffset
) {
589 if ( $tag === 'page' ) {
592 if ( $pageCount < $this->pageOffset
) {
593 $keepReading = $this->reader
->next();
597 $type = $this->reader
->nodeType
;
599 if ( !Hooks
::run( 'ImportHandleToplevelXMLTag', [ $this ] ) ) {
601 } elseif ( $tag == 'mediawiki' && $type == XMLReader
::END_ELEMENT
) {
603 } elseif ( $tag == 'siteinfo' ) {
604 $this->handleSiteInfo();
605 } elseif ( $tag == 'page' ) {
607 } elseif ( $tag == 'logitem' ) {
608 $this->handleLogItem();
609 } elseif ( $tag != '#text' ) {
610 $this->warn( "Unhandled top-level XML tag $tag" );
616 $keepReading = $this->reader
->next();
618 $this->debug( "Skip" );
620 $keepReading = $this->reader
->read();
623 } catch ( Exception
$ex ) {
628 libxml_disable_entity_loader( $oldDisable );
629 $this->reader
->close();
638 private function handleSiteInfo() {
639 $this->debug( "Enter site info handler." );
642 // Fields that can just be stuffed in the siteInfo object
643 $normalFields = [ 'sitename', 'base', 'generator', 'case' ];
645 while ( $this->reader
->read() ) {
646 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
647 $this->reader
->localName
== 'siteinfo' ) {
651 $tag = $this->reader
->localName
;
653 if ( $tag == 'namespace' ) {
654 $this->foreignNamespaces
[$this->nodeAttribute( 'key' )] =
655 $this->nodeContents();
656 } elseif ( in_array( $tag, $normalFields ) ) {
657 $siteInfo[$tag] = $this->nodeContents();
661 $siteInfo['_namespaces'] = $this->foreignNamespaces
;
662 $this->siteInfoCallback( $siteInfo );
665 private function handleLogItem() {
666 $this->debug( "Enter log item handler." );
669 // Fields that can just be stuffed in the pageInfo object
670 $normalFields = [ 'id', 'comment', 'type', 'action', 'timestamp',
671 'logtitle', 'params' ];
673 while ( $this->reader
->read() ) {
674 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
675 $this->reader
->localName
== 'logitem' ) {
679 $tag = $this->reader
->localName
;
681 if ( !Hooks
::run( 'ImportHandleLogItemXMLTag', [
685 } elseif ( in_array( $tag, $normalFields ) ) {
686 $logInfo[$tag] = $this->nodeContents();
687 } elseif ( $tag == 'contributor' ) {
688 $logInfo['contributor'] = $this->handleContributor();
689 } elseif ( $tag != '#text' ) {
690 $this->warn( "Unhandled log-item XML tag $tag" );
694 $this->processLogItem( $logInfo );
698 * @param array $logInfo
701 private function processLogItem( $logInfo ) {
702 $revision = new WikiRevision( $this->config
);
704 if ( isset( $logInfo['id'] ) ) {
705 $revision->setID( $logInfo['id'] );
707 $revision->setType( $logInfo['type'] );
708 $revision->setAction( $logInfo['action'] );
709 if ( isset( $logInfo['timestamp'] ) ) {
710 $revision->setTimestamp( $logInfo['timestamp'] );
712 if ( isset( $logInfo['params'] ) ) {
713 $revision->setParams( $logInfo['params'] );
715 if ( isset( $logInfo['logtitle'] ) ) {
716 // @todo Using Title for non-local titles is a recipe for disaster.
717 // We should use ForeignTitle here instead.
718 $revision->setTitle( Title
::newFromText( $logInfo['logtitle'] ) );
721 $revision->setNoUpdates( $this->mNoUpdates
);
723 if ( isset( $logInfo['comment'] ) ) {
724 $revision->setComment( $logInfo['comment'] );
727 if ( isset( $logInfo['contributor']['ip'] ) ) {
728 $revision->setUserIP( $logInfo['contributor']['ip'] );
731 if ( !isset( $logInfo['contributor']['username'] ) ) {
732 $revision->setUsername( $this->usernamePrefix
. '>Unknown user' );
734 $revision->setUsername( $this->prefixUsername( $logInfo['contributor']['username'] ) );
737 return $this->logItemCallback( $revision );
740 private function handlePage() {
742 $this->debug( "Enter page handler." );
743 $pageInfo = [ 'revisionCount' => 0, 'successfulRevisionCount' => 0 ];
745 // Fields that can just be stuffed in the pageInfo object
746 $normalFields = [ 'title', 'ns', 'id', 'redirect', 'restrictions' ];
751 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
752 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
753 $this->reader
->localName
== 'page' ) {
759 $tag = $this->reader
->localName
;
762 // The title is invalid, bail out of this page
764 } elseif ( !Hooks
::run( 'ImportHandlePageXMLTag', [ $this,
767 } elseif ( in_array( $tag, $normalFields ) ) {
771 // <title>Page</title>
772 // <redirect title="NewTitle"/>
774 // Because the redirect tag is built differently, we need special handling for that case.
775 if ( $tag == 'redirect' ) {
776 $pageInfo[$tag] = $this->nodeAttribute( 'title' );
778 $pageInfo[$tag] = $this->nodeContents();
780 } elseif ( $tag == 'revision' ||
$tag == 'upload' ) {
781 if ( !isset( $title ) ) {
782 $title = $this->processTitle( $pageInfo['title'],
783 isset( $pageInfo['ns'] ) ?
$pageInfo['ns'] : null );
785 // $title is either an array of two titles or false.
786 if ( is_array( $title ) ) {
787 $this->pageCallback( $title );
788 list( $pageInfo['_title'], $foreignTitle ) = $title;
796 if ( $tag == 'revision' ) {
797 $this->handleRevision( $pageInfo );
799 $this->handleUpload( $pageInfo );
802 } elseif ( $tag != '#text' ) {
803 $this->warn( "Unhandled page XML tag $tag" );
808 // @note $pageInfo is only set if a valid $title is processed above with
809 // no error. If we have a valid $title, then pageCallback is called
810 // above, $pageInfo['title'] is set and we do pageOutCallback here.
811 // If $pageInfo['_title'] is not set, then $foreignTitle is also not
812 // set since they both come from $title above.
813 if ( array_key_exists( '_title', $pageInfo ) ) {
814 $this->pageOutCallback( $pageInfo['_title'], $foreignTitle,
815 $pageInfo['revisionCount'],
816 $pageInfo['successfulRevisionCount'],
822 * @param array $pageInfo
824 private function handleRevision( &$pageInfo ) {
825 $this->debug( "Enter revision handler" );
828 $normalFields = [ 'id', 'timestamp', 'comment', 'minor', 'model', 'format', 'text', 'sha1' ];
832 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
833 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
834 $this->reader
->localName
== 'revision' ) {
838 $tag = $this->reader
->localName
;
840 if ( !Hooks
::run( 'ImportHandleRevisionXMLTag', [
841 $this, $pageInfo, $revisionInfo
844 } elseif ( in_array( $tag, $normalFields ) ) {
845 $revisionInfo[$tag] = $this->nodeContents();
846 } elseif ( $tag == 'contributor' ) {
847 $revisionInfo['contributor'] = $this->handleContributor();
848 } elseif ( $tag != '#text' ) {
849 $this->warn( "Unhandled revision XML tag $tag" );
854 $pageInfo['revisionCount']++
;
855 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
856 $pageInfo['successfulRevisionCount']++
;
861 * @param array $pageInfo
862 * @param array $revisionInfo
865 private function processRevision( $pageInfo, $revisionInfo ) {
866 global $wgMaxArticleSize;
868 // Make sure revisions won't violate $wgMaxArticleSize, which could lead to
869 // database errors and instability. Testing for revisions with only listed
870 // content models, as other content models might use serialization formats
871 // which aren't checked against $wgMaxArticleSize.
872 if ( ( !isset( $revisionInfo['model'] ) ||
873 in_array( $revisionInfo['model'], [
881 strlen( $revisionInfo['text'] ) > $wgMaxArticleSize * 1024
883 throw new MWException( 'The text of ' .
884 ( isset( $revisionInfo['id'] ) ?
885 "the revision with ID $revisionInfo[id]" :
887 ) . " exceeds the maximum allowable size ($wgMaxArticleSize KB)" );
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 if ( isset( $revisionInfo['timestamp'] ) ) {
912 $revision->setTimestamp( $revisionInfo['timestamp'] );
914 $revision->setTimestamp( wfTimestampNow() );
917 if ( isset( $revisionInfo['comment'] ) ) {
918 $revision->setComment( $revisionInfo['comment'] );
921 if ( isset( $revisionInfo['minor'] ) ) {
922 $revision->setMinor( true );
924 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
925 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
926 } elseif ( isset( $revisionInfo['contributor']['username'] ) ) {
927 $revision->setUsername( $this->prefixUsername( $revisionInfo['contributor']['username'] ) );
929 $revision->setUsername( $this->usernamePrefix
. '>Unknown user' );
931 if ( isset( $revisionInfo['sha1'] ) ) {
932 $revision->setSha1Base36( $revisionInfo['sha1'] );
934 $revision->setNoUpdates( $this->mNoUpdates
);
936 return $this->revisionCallback( $revision );
940 * @param array $pageInfo
943 private function handleUpload( &$pageInfo ) {
944 $this->debug( "Enter upload handler" );
947 $normalFields = [ 'timestamp', 'comment', 'filename', 'text',
948 'src', 'size', 'sha1base36', 'archivename', 'rel' ];
952 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
953 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
954 $this->reader
->localName
== 'upload' ) {
958 $tag = $this->reader
->localName
;
960 if ( !Hooks
::run( 'ImportHandleUploadXMLTag', [
964 } elseif ( in_array( $tag, $normalFields ) ) {
965 $uploadInfo[$tag] = $this->nodeContents();
966 } elseif ( $tag == 'contributor' ) {
967 $uploadInfo['contributor'] = $this->handleContributor();
968 } elseif ( $tag == 'contents' ) {
969 $contents = $this->nodeContents();
970 $encoding = $this->reader
->getAttribute( 'encoding' );
971 if ( $encoding === 'base64' ) {
972 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
973 $uploadInfo['isTempSrc'] = true;
975 } elseif ( $tag != '#text' ) {
976 $this->warn( "Unhandled upload XML tag $tag" );
981 if ( $this->mImageBasePath
&& isset( $uploadInfo['rel'] ) ) {
982 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
983 if ( file_exists( $path ) ) {
984 $uploadInfo['fileSrc'] = $path;
985 $uploadInfo['isTempSrc'] = false;
989 if ( $this->mImportUploads
) {
990 return $this->processUpload( $pageInfo, $uploadInfo );
995 * @param string $contents
998 private function dumpTemp( $contents ) {
999 $filename = tempnam( wfTempDir(), 'importupload' );
1000 file_put_contents( $filename, $contents );
1005 * @param array $pageInfo
1006 * @param array $uploadInfo
1009 private function processUpload( $pageInfo, $uploadInfo ) {
1010 $revision = new WikiRevision( $this->config
);
1011 $text = isset( $uploadInfo['text'] ) ?
$uploadInfo['text'] : '';
1013 $revision->setTitle( $pageInfo['_title'] );
1014 $revision->setID( $pageInfo['id'] );
1015 $revision->setTimestamp( $uploadInfo['timestamp'] );
1016 $revision->setText( $text );
1017 $revision->setFilename( $uploadInfo['filename'] );
1018 if ( isset( $uploadInfo['archivename'] ) ) {
1019 $revision->setArchiveName( $uploadInfo['archivename'] );
1021 $revision->setSrc( $uploadInfo['src'] );
1022 if ( isset( $uploadInfo['fileSrc'] ) ) {
1023 $revision->setFileSrc( $uploadInfo['fileSrc'],
1024 !empty( $uploadInfo['isTempSrc'] ) );
1026 if ( isset( $uploadInfo['sha1base36'] ) ) {
1027 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
1029 $revision->setSize( intval( $uploadInfo['size'] ) );
1030 $revision->setComment( $uploadInfo['comment'] );
1032 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
1033 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
1035 if ( isset( $uploadInfo['contributor']['username'] ) ) {
1036 $revision->setUsername( $this->prefixUsername( $uploadInfo['contributor']['username'] ) );
1038 $revision->setNoUpdates( $this->mNoUpdates
);
1040 return call_user_func( $this->mUploadCallback
, $revision );
1044 * Add an interwiki prefix to the username, if appropriate
1046 * @param string $name Name being imported
1047 * @return string Name, possibly with the prefix prepended.
1049 protected function prefixUsername( $name ) {
1050 if ( !User
::isUsableName( $name ) ) {
1054 if ( $this->assignKnownUsers
) {
1055 if ( User
::idFromName( $name ) ) {
1059 // See if any extension wants to create it.
1060 if ( !isset( $this->triedCreations
[$name] ) ) {
1061 $this->triedCreations
[$name] = true;
1062 if ( !Hooks
::run( 'ImportHandleUnknownUser', [ $name ] ) &&
1063 User
::idFromName( $name, User
::READ_LATEST
)
1070 return substr( $this->usernamePrefix
. '>' . $name, 0, 255 );
1076 private function handleContributor() {
1077 $fields = [ 'id', 'ip', 'username' ];
1080 if ( $this->reader
->isEmptyElement
) {
1083 while ( $this->reader
->read() ) {
1084 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
1085 $this->reader
->localName
== 'contributor' ) {
1089 $tag = $this->reader
->localName
;
1091 if ( in_array( $tag, $fields ) ) {
1092 $info[$tag] = $this->nodeContents();
1100 * @param string $text
1101 * @param string|null $ns
1102 * @return array|bool
1104 private function processTitle( $text, $ns = null ) {
1105 if ( is_null( $this->foreignNamespaces
) ) {
1106 $foreignTitleFactory = new NaiveForeignTitleFactory();
1108 $foreignTitleFactory = new NamespaceAwareForeignTitleFactory(
1109 $this->foreignNamespaces
);
1112 $foreignTitle = $foreignTitleFactory->createForeignTitle( $text,
1115 $title = $this->importTitleFactory
->createTitleFromForeignTitle(
1118 $commandLineMode = $this->config
->get( 'CommandLineMode' );
1119 if ( is_null( $title ) ) {
1120 # Invalid page title? Ignore the page
1121 $this->notice( 'import-error-invalid', $foreignTitle->getFullText() );
1123 } elseif ( $title->isExternal() ) {
1124 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
1126 } elseif ( !$title->canExist() ) {
1127 $this->notice( 'import-error-special', $title->getPrefixedText() );
1129 } elseif ( !$title->userCan( 'edit' ) && !$commandLineMode ) {
1130 # Do not import if the importing wiki user cannot edit this page
1131 $this->notice( 'import-error-edit', $title->getPrefixedText() );
1133 } elseif ( !$title->exists() && !$title->userCan( 'create' ) && !$commandLineMode ) {
1134 # Do not import if the importing wiki user cannot create this page
1135 $this->notice( 'import-error-create', $title->getPrefixedText() );
1139 return [ $title, $foreignTitle ];