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;
52 * Creates an ImportXMLReader drawing from the source provided
53 * @param ImportSource $source
54 * @param Config $config
57 function __construct( ImportSource
$source, Config
$config ) {
58 if ( !class_exists( 'XMLReader' ) ) {
59 throw new Exception( 'Import requires PHP to have been compiled with libxml support' );
62 $this->reader
= new XMLReader();
63 $this->config
= $config;
65 if ( !in_array( 'uploadsource', stream_get_wrappers() ) ) {
66 stream_wrapper_register( 'uploadsource', 'UploadSourceAdapter' );
68 $id = UploadSourceAdapter
::registerSource( $source );
70 // Enable the entity loader, as it is needed for loading external URLs via
71 // XMLReader::open (T86036)
72 $oldDisable = libxml_disable_entity_loader( false );
73 if ( defined( 'LIBXML_PARSEHUGE' ) ) {
74 $status = $this->reader
->open( "uploadsource://$id", null, LIBXML_PARSEHUGE
);
76 $status = $this->reader
->open( "uploadsource://$id" );
79 $error = libxml_get_last_error();
80 libxml_disable_entity_loader( $oldDisable );
81 throw new MWException( 'Encountered an internal error while initializing WikiImporter object: ' .
84 libxml_disable_entity_loader( $oldDisable );
87 $this->setPageCallback( [ $this, 'beforeImportPage' ] );
88 $this->setRevisionCallback( [ $this, "importRevision" ] );
89 $this->setUploadCallback( [ $this, 'importUpload' ] );
90 $this->setLogItemCallback( [ $this, 'importLogItem' ] );
91 $this->setPageOutCallback( [ $this, 'finishImportPage' ] );
93 $this->importTitleFactory
= new NaiveImportTitleFactory();
97 * @return null|XMLReader
99 public function getReader() {
100 return $this->reader
;
103 public function throwXmlError( $err ) {
104 $this->debug( "FAILURE: $err" );
105 wfDebug( "WikiImporter XML error: $err\n" );
108 public function debug( $data ) {
109 if ( $this->mDebug
) {
110 wfDebug( "IMPORT: $data\n" );
114 public function warn( $data ) {
115 wfDebug( "IMPORT: $data\n" );
118 public function notice( $msg /*, $param, ...*/ ) {
119 $params = func_get_args();
120 array_shift( $params );
122 if ( is_callable( $this->mNoticeCallback
) ) {
123 call_user_func( $this->mNoticeCallback
, $msg, $params );
124 } else { # No ImportReporter -> CLI
125 echo wfMessage( $msg, $params )->text() . "\n";
133 function setDebug( $debug ) {
134 $this->mDebug
= $debug;
138 * Set 'no updates' mode. In this mode, the link tables will not be updated by the importer
139 * @param bool $noupdates
141 function setNoUpdates( $noupdates ) {
142 $this->mNoUpdates
= $noupdates;
146 * Sets 'pageOffset' value. So it will skip the first n-1 pages
147 * and start from the nth page. It's 1-based indexing.
148 * @param int $nthPage
151 function setPageOffset( $nthPage ) {
152 $this->pageOffset
= $nthPage;
156 * Set a callback that displays notice messages
158 * @param callable $callback
161 public function setNoticeCallback( $callback ) {
162 return wfSetVar( $this->mNoticeCallback
, $callback );
166 * Sets the action to perform as each new page in the stream is reached.
167 * @param callable $callback
170 public function setPageCallback( $callback ) {
171 $previous = $this->mPageCallback
;
172 $this->mPageCallback
= $callback;
177 * Sets the action to perform as each page in the stream is completed.
178 * Callback accepts the page title (as a Title object), a second object
179 * with the original title form (in case it's been overridden into a
180 * local namespace), and a count of revisions.
182 * @param callable $callback
185 public function setPageOutCallback( $callback ) {
186 $previous = $this->mPageOutCallback
;
187 $this->mPageOutCallback
= $callback;
192 * Sets the action to perform as each page revision is reached.
193 * @param callable $callback
196 public function setRevisionCallback( $callback ) {
197 $previous = $this->mRevisionCallback
;
198 $this->mRevisionCallback
= $callback;
203 * Sets the action to perform as each file upload version is reached.
204 * @param callable $callback
207 public function setUploadCallback( $callback ) {
208 $previous = $this->mUploadCallback
;
209 $this->mUploadCallback
= $callback;
214 * Sets the action to perform as each log item reached.
215 * @param callable $callback
218 public function setLogItemCallback( $callback ) {
219 $previous = $this->mLogItemCallback
;
220 $this->mLogItemCallback
= $callback;
225 * Sets the action to perform when site info is encountered
226 * @param callable $callback
229 public function setSiteInfoCallback( $callback ) {
230 $previous = $this->mSiteInfoCallback
;
231 $this->mSiteInfoCallback
= $callback;
236 * Sets the factory object to use to convert ForeignTitle objects into local
238 * @param ImportTitleFactory $factory
240 public function setImportTitleFactory( $factory ) {
241 $this->importTitleFactory
= $factory;
245 * Set a target namespace to override the defaults
246 * @param null|int $namespace
249 public function setTargetNamespace( $namespace ) {
250 if ( is_null( $namespace ) ) {
251 // Don't override namespaces
252 $this->setImportTitleFactory( new NaiveImportTitleFactory() );
256 MWNamespace
::exists( intval( $namespace ) )
258 $namespace = intval( $namespace );
259 $this->setImportTitleFactory( new NamespaceImportTitleFactory( $namespace ) );
267 * Set a target root page under which all pages are imported
268 * @param null|string $rootpage
271 public function setTargetRootPage( $rootpage ) {
272 $status = Status
::newGood();
273 if ( is_null( $rootpage ) ) {
275 $this->setImportTitleFactory( new NaiveImportTitleFactory() );
276 } elseif ( $rootpage !== '' ) {
277 $rootpage = rtrim( $rootpage, '/' ); // avoid double slashes
278 $title = Title
::newFromText( $rootpage );
280 if ( !$title ||
$title->isExternal() ) {
281 $status->fatal( 'import-rootpage-invalid' );
283 if ( !MWNamespace
::hasSubpages( $title->getNamespace() ) ) {
286 $displayNSText = $title->getNamespace() == NS_MAIN
287 ?
wfMessage( 'blanknamespace' )->text()
288 : $wgContLang->getNsText( $title->getNamespace() );
289 $status->fatal( 'import-rootpage-nosubpage', $displayNSText );
291 // set namespace to 'all', so the namespace check in processTitle() can pass
292 $this->setTargetNamespace( null );
293 $this->setImportTitleFactory( new SubpageImportTitleFactory( $title ) );
303 public function setImageBasePath( $dir ) {
304 $this->mImageBasePath
= $dir;
308 * @param bool $import
310 public function setImportUploads( $import ) {
311 $this->mImportUploads
= $import;
315 * Statistics update can cause a lot of time
318 public function disableStatisticsUpdate() {
319 $this->disableStatisticsUpdate
= true;
323 * Default per-page callback. Sets up some things related to site statistics
324 * @param array $titleAndForeignTitle Two-element array, with Title object at
325 * index 0 and ForeignTitle object at index 1
328 public function beforeImportPage( $titleAndForeignTitle ) {
329 $title = $titleAndForeignTitle[0];
330 $page = WikiPage
::factory( $title );
331 $this->countableCache
['title_' . $title->getPrefixedText()] = $page->isCountable();
336 * Default per-revision callback, performs the import.
337 * @param WikiRevision $revision
340 public function importRevision( $revision ) {
341 if ( !$revision->getContentHandler()->canBeUsedOn( $revision->getTitle() ) ) {
342 $this->notice( 'import-error-bad-location',
343 $revision->getTitle()->getPrefixedText(),
345 $revision->getModel(),
346 $revision->getFormat() );
352 return $revision->importOldRevision();
353 } catch ( MWContentSerializationException
$ex ) {
354 $this->notice( 'import-error-unserialize',
355 $revision->getTitle()->getPrefixedText(),
357 $revision->getModel(),
358 $revision->getFormat() );
365 * Default per-revision callback, performs the import.
366 * @param WikiRevision $revision
369 public function importLogItem( $revision ) {
370 return $revision->importLogItem();
375 * @param WikiRevision $revision
378 public function importUpload( $revision ) {
379 return $revision->importUpload();
383 * Mostly for hook use
384 * @param Title $title
385 * @param ForeignTitle $foreignTitle
386 * @param int $revCount
387 * @param int $sRevCount
388 * @param array $pageInfo
391 public function finishImportPage( $title, $foreignTitle, $revCount,
392 $sRevCount, $pageInfo
394 // Update article count statistics (T42009)
395 // The normal counting logic in WikiPage->doEditUpdates() is designed for
396 // one-revision-at-a-time editing, not bulk imports. In this situation it
397 // suffers from issues of replica DB lag. We let WikiPage handle the total page
398 // and revision count, and we implement our own custom logic for the
399 // article (content page) count.
400 if ( !$this->disableStatisticsUpdate
) {
401 $page = WikiPage
::factory( $title );
402 $page->loadPageData( 'fromdbmaster' );
403 $content = $page->getContent();
404 if ( $content === null ) {
405 wfDebug( __METHOD__
. ': Skipping article count adjustment for ' . $title .
406 ' because WikiPage::getContent() returned null' );
408 $editInfo = $page->prepareContentForEdit( $content );
409 $countKey = 'title_' . $title->getPrefixedText();
410 $countable = $page->isCountable( $editInfo );
411 if ( array_key_exists( $countKey, $this->countableCache
) &&
412 $countable != $this->countableCache
[$countKey] ) {
413 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [
414 'articles' => ( (int)$countable - (int)$this->countableCache
[$countKey] )
420 $args = func_get_args();
421 return Hooks
::run( 'AfterImportPage', $args );
425 * Alternate per-revision callback, for debugging.
426 * @param WikiRevision &$revision
428 public function debugRevisionHandler( &$revision ) {
429 $this->debug( "Got revision:" );
430 if ( is_object( $revision->title
) ) {
431 $this->debug( "-- Title: " . $revision->title
->getPrefixedText() );
433 $this->debug( "-- Title: <invalid>" );
435 $this->debug( "-- User: " . $revision->user_text
);
436 $this->debug( "-- Timestamp: " . $revision->timestamp
);
437 $this->debug( "-- Comment: " . $revision->comment
);
438 $this->debug( "-- Text: " . $revision->text
);
442 * Notify the callback function of site info
443 * @param array $siteInfo
446 private function siteInfoCallback( $siteInfo ) {
447 if ( isset( $this->mSiteInfoCallback
) ) {
448 return call_user_func_array( $this->mSiteInfoCallback
,
449 [ $siteInfo, $this ] );
456 * Notify the callback function when a new "<page>" is reached.
457 * @param Title $title
459 function pageCallback( $title ) {
460 if ( isset( $this->mPageCallback
) ) {
461 call_user_func( $this->mPageCallback
, $title );
466 * Notify the callback function when a "</page>" is closed.
467 * @param Title $title
468 * @param ForeignTitle $foreignTitle
469 * @param int $revCount
470 * @param int $sucCount Number of revisions for which callback returned true
471 * @param array $pageInfo Associative array of page information
473 private function pageOutCallback( $title, $foreignTitle, $revCount,
474 $sucCount, $pageInfo ) {
475 if ( isset( $this->mPageOutCallback
) ) {
476 $args = func_get_args();
477 call_user_func_array( $this->mPageOutCallback
, $args );
482 * Notify the callback function of a revision
483 * @param WikiRevision $revision
486 private function revisionCallback( $revision ) {
487 if ( isset( $this->mRevisionCallback
) ) {
488 return call_user_func_array( $this->mRevisionCallback
,
489 [ $revision, $this ] );
496 * Notify the callback function of a new log item
497 * @param WikiRevision $revision
500 private function logItemCallback( $revision ) {
501 if ( isset( $this->mLogItemCallback
) ) {
502 return call_user_func_array( $this->mLogItemCallback
,
503 [ $revision, $this ] );
510 * Retrieves the contents of the named attribute of the current element.
511 * @param string $attr The name of the attribute
512 * @return string The value of the attribute or an empty string if it is not set in the current
515 public function nodeAttribute( $attr ) {
516 return $this->reader
->getAttribute( $attr );
520 * Shouldn't something like this be built-in to XMLReader?
521 * Fetches text contents of the current element, assuming
522 * no sub-elements or such scary things.
526 public function nodeContents() {
527 if ( $this->reader
->isEmptyElement
) {
531 while ( $this->reader
->read() ) {
532 switch ( $this->reader
->nodeType
) {
533 case XMLReader
::TEXT
:
534 case XMLReader
::CDATA
:
535 case XMLReader
::SIGNIFICANT_WHITESPACE
:
536 $buffer .= $this->reader
->value
;
538 case XMLReader
::END_ELEMENT
:
543 $this->reader
->close();
548 * Primary entry point
550 * @throws MWException
553 public function doImport() {
554 // Calls to reader->read need to be wrapped in calls to
555 // libxml_disable_entity_loader() to avoid local file
556 // inclusion attacks (T48932).
557 $oldDisable = libxml_disable_entity_loader( true );
558 $this->reader
->read();
560 if ( $this->reader
->localName
!= 'mediawiki' ) {
561 libxml_disable_entity_loader( $oldDisable );
562 throw new MWException( "Expected <mediawiki> tag, got " .
563 $this->reader
->localName
);
565 $this->debug( "<mediawiki> tag is correct." );
567 $this->debug( "Starting primary dump processing loop." );
569 $keepReading = $this->reader
->read();
574 while ( $keepReading ) {
575 $tag = $this->reader
->localName
;
576 if ( $this->pageOffset
) {
577 if ( $tag === 'page' ) {
580 if ( $pageCount < $this->pageOffset
) {
581 $keepReading = $this->reader
->next();
585 $type = $this->reader
->nodeType
;
587 if ( !Hooks
::run( 'ImportHandleToplevelXMLTag', [ $this ] ) ) {
589 } elseif ( $tag == 'mediawiki' && $type == XMLReader
::END_ELEMENT
) {
591 } elseif ( $tag == 'siteinfo' ) {
592 $this->handleSiteInfo();
593 } elseif ( $tag == 'page' ) {
595 } elseif ( $tag == 'logitem' ) {
596 $this->handleLogItem();
597 } elseif ( $tag != '#text' ) {
598 $this->warn( "Unhandled top-level XML tag $tag" );
604 $keepReading = $this->reader
->next();
606 $this->debug( "Skip" );
608 $keepReading = $this->reader
->read();
611 } catch ( Exception
$ex ) {
616 libxml_disable_entity_loader( $oldDisable );
617 $this->reader
->close();
626 private function handleSiteInfo() {
627 $this->debug( "Enter site info handler." );
630 // Fields that can just be stuffed in the siteInfo object
631 $normalFields = [ 'sitename', 'base', 'generator', 'case' ];
633 while ( $this->reader
->read() ) {
634 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
635 $this->reader
->localName
== 'siteinfo' ) {
639 $tag = $this->reader
->localName
;
641 if ( $tag == 'namespace' ) {
642 $this->foreignNamespaces
[$this->nodeAttribute( 'key' )] =
643 $this->nodeContents();
644 } elseif ( in_array( $tag, $normalFields ) ) {
645 $siteInfo[$tag] = $this->nodeContents();
649 $siteInfo['_namespaces'] = $this->foreignNamespaces
;
650 $this->siteInfoCallback( $siteInfo );
653 private function handleLogItem() {
654 $this->debug( "Enter log item handler." );
657 // Fields that can just be stuffed in the pageInfo object
658 $normalFields = [ 'id', 'comment', 'type', 'action', 'timestamp',
659 'logtitle', 'params' ];
661 while ( $this->reader
->read() ) {
662 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
663 $this->reader
->localName
== 'logitem' ) {
667 $tag = $this->reader
->localName
;
669 if ( !Hooks
::run( 'ImportHandleLogItemXMLTag', [
673 } elseif ( in_array( $tag, $normalFields ) ) {
674 $logInfo[$tag] = $this->nodeContents();
675 } elseif ( $tag == 'contributor' ) {
676 $logInfo['contributor'] = $this->handleContributor();
677 } elseif ( $tag != '#text' ) {
678 $this->warn( "Unhandled log-item XML tag $tag" );
682 $this->processLogItem( $logInfo );
686 * @param array $logInfo
689 private function processLogItem( $logInfo ) {
690 $revision = new WikiRevision( $this->config
);
692 if ( isset( $logInfo['id'] ) ) {
693 $revision->setID( $logInfo['id'] );
695 $revision->setType( $logInfo['type'] );
696 $revision->setAction( $logInfo['action'] );
697 if ( isset( $logInfo['timestamp'] ) ) {
698 $revision->setTimestamp( $logInfo['timestamp'] );
700 if ( isset( $logInfo['params'] ) ) {
701 $revision->setParams( $logInfo['params'] );
703 if ( isset( $logInfo['logtitle'] ) ) {
704 // @todo Using Title for non-local titles is a recipe for disaster.
705 // We should use ForeignTitle here instead.
706 $revision->setTitle( Title
::newFromText( $logInfo['logtitle'] ) );
709 $revision->setNoUpdates( $this->mNoUpdates
);
711 if ( isset( $logInfo['comment'] ) ) {
712 $revision->setComment( $logInfo['comment'] );
715 if ( isset( $logInfo['contributor']['ip'] ) ) {
716 $revision->setUserIP( $logInfo['contributor']['ip'] );
719 if ( !isset( $logInfo['contributor']['username'] ) ) {
720 $revision->setUsername( 'Unknown user' );
722 $revision->setUsername( $logInfo['contributor']['username'] );
725 return $this->logItemCallback( $revision );
728 private function handlePage() {
730 $this->debug( "Enter page handler." );
731 $pageInfo = [ 'revisionCount' => 0, 'successfulRevisionCount' => 0 ];
733 // Fields that can just be stuffed in the pageInfo object
734 $normalFields = [ 'title', 'ns', 'id', 'redirect', 'restrictions' ];
739 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
740 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
741 $this->reader
->localName
== 'page' ) {
747 $tag = $this->reader
->localName
;
750 // The title is invalid, bail out of this page
752 } elseif ( !Hooks
::run( 'ImportHandlePageXMLTag', [ $this,
755 } elseif ( in_array( $tag, $normalFields ) ) {
759 // <title>Page</title>
760 // <redirect title="NewTitle"/>
762 // Because the redirect tag is built differently, we need special handling for that case.
763 if ( $tag == 'redirect' ) {
764 $pageInfo[$tag] = $this->nodeAttribute( 'title' );
766 $pageInfo[$tag] = $this->nodeContents();
768 } elseif ( $tag == 'revision' ||
$tag == 'upload' ) {
769 if ( !isset( $title ) ) {
770 $title = $this->processTitle( $pageInfo['title'],
771 isset( $pageInfo['ns'] ) ?
$pageInfo['ns'] : null );
773 // $title is either an array of two titles or false.
774 if ( is_array( $title ) ) {
775 $this->pageCallback( $title );
776 list( $pageInfo['_title'], $foreignTitle ) = $title;
784 if ( $tag == 'revision' ) {
785 $this->handleRevision( $pageInfo );
787 $this->handleUpload( $pageInfo );
790 } elseif ( $tag != '#text' ) {
791 $this->warn( "Unhandled page XML tag $tag" );
796 // @note $pageInfo is only set if a valid $title is processed above with
797 // no error. If we have a valid $title, then pageCallback is called
798 // above, $pageInfo['title'] is set and we do pageOutCallback here.
799 // If $pageInfo['_title'] is not set, then $foreignTitle is also not
800 // set since they both come from $title above.
801 if ( array_key_exists( '_title', $pageInfo ) ) {
802 $this->pageOutCallback( $pageInfo['_title'], $foreignTitle,
803 $pageInfo['revisionCount'],
804 $pageInfo['successfulRevisionCount'],
810 * @param array $pageInfo
812 private function handleRevision( &$pageInfo ) {
813 $this->debug( "Enter revision handler" );
816 $normalFields = [ 'id', 'timestamp', 'comment', 'minor', 'model', 'format', 'text', 'sha1' ];
820 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
821 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
822 $this->reader
->localName
== 'revision' ) {
826 $tag = $this->reader
->localName
;
828 if ( !Hooks
::run( 'ImportHandleRevisionXMLTag', [
829 $this, $pageInfo, $revisionInfo
832 } elseif ( in_array( $tag, $normalFields ) ) {
833 $revisionInfo[$tag] = $this->nodeContents();
834 } elseif ( $tag == 'contributor' ) {
835 $revisionInfo['contributor'] = $this->handleContributor();
836 } elseif ( $tag != '#text' ) {
837 $this->warn( "Unhandled revision XML tag $tag" );
842 $pageInfo['revisionCount']++
;
843 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
844 $pageInfo['successfulRevisionCount']++
;
849 * @param array $pageInfo
850 * @param array $revisionInfo
851 * @throws MWException
854 private function processRevision( $pageInfo, $revisionInfo ) {
855 global $wgMaxArticleSize;
857 // Make sure revisions won't violate $wgMaxArticleSize, which could lead to
858 // database errors and instability. Testing for revisions with only listed
859 // content models, as other content models might use serialization formats
860 // which aren't checked against $wgMaxArticleSize.
861 if ( ( !isset( $revisionInfo['model'] ) ||
862 in_array( $revisionInfo['model'], [
870 strlen( $revisionInfo['text'] ) > $wgMaxArticleSize * 1024
872 throw new MWException( 'The text of ' .
873 ( isset( $revisionInfo['id'] ) ?
874 "the revision with ID $revisionInfo[id]" :
876 ) . " exceeds the maximum allowable size ($wgMaxArticleSize KB)" );
879 $revision = new WikiRevision( $this->config
);
881 if ( isset( $revisionInfo['id'] ) ) {
882 $revision->setID( $revisionInfo['id'] );
884 if ( isset( $revisionInfo['model'] ) ) {
885 $revision->setModel( $revisionInfo['model'] );
887 if ( isset( $revisionInfo['format'] ) ) {
888 $revision->setFormat( $revisionInfo['format'] );
890 $revision->setTitle( $pageInfo['_title'] );
892 if ( isset( $revisionInfo['text'] ) ) {
893 $handler = $revision->getContentHandler();
894 $text = $handler->importTransform(
895 $revisionInfo['text'],
896 $revision->getFormat() );
898 $revision->setText( $text );
900 if ( isset( $revisionInfo['timestamp'] ) ) {
901 $revision->setTimestamp( $revisionInfo['timestamp'] );
903 $revision->setTimestamp( wfTimestampNow() );
906 if ( isset( $revisionInfo['comment'] ) ) {
907 $revision->setComment( $revisionInfo['comment'] );
910 if ( isset( $revisionInfo['minor'] ) ) {
911 $revision->setMinor( true );
913 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
914 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
915 } elseif ( isset( $revisionInfo['contributor']['username'] ) ) {
916 $revision->setUsername( $revisionInfo['contributor']['username'] );
918 $revision->setUsername( 'Unknown user' );
920 if ( isset( $revisionInfo['sha1'] ) ) {
921 $revision->setSha1Base36( $revisionInfo['sha1'] );
923 $revision->setNoUpdates( $this->mNoUpdates
);
925 return $this->revisionCallback( $revision );
929 * @param array $pageInfo
932 private function handleUpload( &$pageInfo ) {
933 $this->debug( "Enter upload handler" );
936 $normalFields = [ 'timestamp', 'comment', 'filename', 'text',
937 'src', 'size', 'sha1base36', 'archivename', 'rel' ];
941 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
942 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
943 $this->reader
->localName
== 'upload' ) {
947 $tag = $this->reader
->localName
;
949 if ( !Hooks
::run( 'ImportHandleUploadXMLTag', [
953 } elseif ( in_array( $tag, $normalFields ) ) {
954 $uploadInfo[$tag] = $this->nodeContents();
955 } elseif ( $tag == 'contributor' ) {
956 $uploadInfo['contributor'] = $this->handleContributor();
957 } elseif ( $tag == 'contents' ) {
958 $contents = $this->nodeContents();
959 $encoding = $this->reader
->getAttribute( 'encoding' );
960 if ( $encoding === 'base64' ) {
961 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
962 $uploadInfo['isTempSrc'] = true;
964 } elseif ( $tag != '#text' ) {
965 $this->warn( "Unhandled upload XML tag $tag" );
970 if ( $this->mImageBasePath
&& isset( $uploadInfo['rel'] ) ) {
971 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
972 if ( file_exists( $path ) ) {
973 $uploadInfo['fileSrc'] = $path;
974 $uploadInfo['isTempSrc'] = false;
978 if ( $this->mImportUploads
) {
979 return $this->processUpload( $pageInfo, $uploadInfo );
984 * @param string $contents
987 private function dumpTemp( $contents ) {
988 $filename = tempnam( wfTempDir(), 'importupload' );
989 file_put_contents( $filename, $contents );
994 * @param array $pageInfo
995 * @param array $uploadInfo
998 private function processUpload( $pageInfo, $uploadInfo ) {
999 $revision = new WikiRevision( $this->config
);
1000 $text = isset( $uploadInfo['text'] ) ?
$uploadInfo['text'] : '';
1002 $revision->setTitle( $pageInfo['_title'] );
1003 $revision->setID( $pageInfo['id'] );
1004 $revision->setTimestamp( $uploadInfo['timestamp'] );
1005 $revision->setText( $text );
1006 $revision->setFilename( $uploadInfo['filename'] );
1007 if ( isset( $uploadInfo['archivename'] ) ) {
1008 $revision->setArchiveName( $uploadInfo['archivename'] );
1010 $revision->setSrc( $uploadInfo['src'] );
1011 if ( isset( $uploadInfo['fileSrc'] ) ) {
1012 $revision->setFileSrc( $uploadInfo['fileSrc'],
1013 !empty( $uploadInfo['isTempSrc'] ) );
1015 if ( isset( $uploadInfo['sha1base36'] ) ) {
1016 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
1018 $revision->setSize( intval( $uploadInfo['size'] ) );
1019 $revision->setComment( $uploadInfo['comment'] );
1021 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
1022 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
1024 if ( isset( $uploadInfo['contributor']['username'] ) ) {
1025 $revision->setUsername( $uploadInfo['contributor']['username'] );
1027 $revision->setNoUpdates( $this->mNoUpdates
);
1029 return call_user_func( $this->mUploadCallback
, $revision );
1035 private function handleContributor() {
1036 $fields = [ 'id', 'ip', 'username' ];
1039 if ( $this->reader
->isEmptyElement
) {
1042 while ( $this->reader
->read() ) {
1043 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
1044 $this->reader
->localName
== 'contributor' ) {
1048 $tag = $this->reader
->localName
;
1050 if ( in_array( $tag, $fields ) ) {
1051 $info[$tag] = $this->nodeContents();
1059 * @param string $text
1060 * @param string|null $ns
1061 * @return array|bool
1063 private function processTitle( $text, $ns = null ) {
1064 if ( is_null( $this->foreignNamespaces
) ) {
1065 $foreignTitleFactory = new NaiveForeignTitleFactory();
1067 $foreignTitleFactory = new NamespaceAwareForeignTitleFactory(
1068 $this->foreignNamespaces
);
1071 $foreignTitle = $foreignTitleFactory->createForeignTitle( $text,
1074 $title = $this->importTitleFactory
->createTitleFromForeignTitle(
1077 $commandLineMode = $this->config
->get( 'CommandLineMode' );
1078 if ( is_null( $title ) ) {
1079 # Invalid page title? Ignore the page
1080 $this->notice( 'import-error-invalid', $foreignTitle->getFullText() );
1082 } elseif ( $title->isExternal() ) {
1083 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
1085 } elseif ( !$title->canExist() ) {
1086 $this->notice( 'import-error-special', $title->getPrefixedText() );
1088 } elseif ( !$title->userCan( 'edit' ) && !$commandLineMode ) {
1089 # Do not import if the importing wiki user cannot edit this page
1090 $this->notice( 'import-error-edit', $title->getPrefixedText() );
1092 } elseif ( !$title->exists() && !$title->userCan( 'create' ) && !$commandLineMode ) {
1093 # Do not import if the importing wiki user cannot create this page
1094 $this->notice( 'import-error-create', $title->getPrefixedText() );
1098 return [ $title, $foreignTitle ];