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;
43 /** @var ImportTitleFactory */
44 private $importTitleFactory;
46 private $countableCache = [];
49 * Creates an ImportXMLReader drawing from the source provided
50 * @param ImportSource $source
51 * @param Config $config
54 function __construct( ImportSource
$source, Config
$config = null ) {
55 if ( !class_exists( 'XMLReader' ) ) {
56 throw new Exception( 'Import requires PHP to have been compiled with libxml support' );
59 $this->reader
= new XMLReader();
61 wfDeprecated( __METHOD__
. ' without a Config instance', '1.25' );
62 $config = ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
64 $this->config
= $config;
66 if ( !in_array( 'uploadsource', stream_get_wrappers() ) ) {
67 stream_wrapper_register( 'uploadsource', 'UploadSourceAdapter' );
69 $id = UploadSourceAdapter
::registerSource( $source );
71 // Enable the entity loader, as it is needed for loading external URLs via
72 // XMLReader::open (T86036)
73 $oldDisable = libxml_disable_entity_loader( false );
74 if ( defined( 'LIBXML_PARSEHUGE' ) ) {
75 $status = $this->reader
->open( "uploadsource://$id", null, LIBXML_PARSEHUGE
);
77 $status = $this->reader
->open( "uploadsource://$id" );
80 $error = libxml_get_last_error();
81 libxml_disable_entity_loader( $oldDisable );
82 throw new MWException( 'Encountered an internal error while initializing WikiImporter object: ' .
85 libxml_disable_entity_loader( $oldDisable );
88 $this->setPageCallback( [ $this, 'beforeImportPage' ] );
89 $this->setRevisionCallback( [ $this, "importRevision" ] );
90 $this->setUploadCallback( [ $this, 'importUpload' ] );
91 $this->setLogItemCallback( [ $this, 'importLogItem' ] );
92 $this->setPageOutCallback( [ $this, 'finishImportPage' ] );
94 $this->importTitleFactory
= new NaiveImportTitleFactory();
98 * @return null|XMLReader
100 public function getReader() {
101 return $this->reader
;
104 public function throwXmlError( $err ) {
105 $this->debug( "FAILURE: $err" );
106 wfDebug( "WikiImporter XML error: $err\n" );
109 public function debug( $data ) {
110 if ( $this->mDebug
) {
111 wfDebug( "IMPORT: $data\n" );
115 public function warn( $data ) {
116 wfDebug( "IMPORT: $data\n" );
119 public function notice( $msg /*, $param, ...*/ ) {
120 $params = func_get_args();
121 array_shift( $params );
123 if ( is_callable( $this->mNoticeCallback
) ) {
124 call_user_func( $this->mNoticeCallback
, $msg, $params );
125 } else { # No ImportReporter -> CLI
126 echo wfMessage( $msg, $params )->text() . "\n";
134 function setDebug( $debug ) {
135 $this->mDebug
= $debug;
139 * Set 'no updates' mode. In this mode, the link tables will not be updated by the importer
140 * @param bool $noupdates
142 function setNoUpdates( $noupdates ) {
143 $this->mNoUpdates
= $noupdates;
147 * Set a callback that displays notice messages
149 * @param callable $callback
152 public function setNoticeCallback( $callback ) {
153 return wfSetVar( $this->mNoticeCallback
, $callback );
157 * Sets the action to perform as each new page in the stream is reached.
158 * @param callable $callback
161 public function setPageCallback( $callback ) {
162 $previous = $this->mPageCallback
;
163 $this->mPageCallback
= $callback;
168 * Sets the action to perform as each page in the stream is completed.
169 * Callback accepts the page title (as a Title object), a second object
170 * with the original title form (in case it's been overridden into a
171 * local namespace), and a count of revisions.
173 * @param callable $callback
176 public function setPageOutCallback( $callback ) {
177 $previous = $this->mPageOutCallback
;
178 $this->mPageOutCallback
= $callback;
183 * Sets the action to perform as each page revision is reached.
184 * @param callable $callback
187 public function setRevisionCallback( $callback ) {
188 $previous = $this->mRevisionCallback
;
189 $this->mRevisionCallback
= $callback;
194 * Sets the action to perform as each file upload version is reached.
195 * @param callable $callback
198 public function setUploadCallback( $callback ) {
199 $previous = $this->mUploadCallback
;
200 $this->mUploadCallback
= $callback;
205 * Sets the action to perform as each log item reached.
206 * @param callable $callback
209 public function setLogItemCallback( $callback ) {
210 $previous = $this->mLogItemCallback
;
211 $this->mLogItemCallback
= $callback;
216 * Sets the action to perform when site info is encountered
217 * @param callable $callback
220 public function setSiteInfoCallback( $callback ) {
221 $previous = $this->mSiteInfoCallback
;
222 $this->mSiteInfoCallback
= $callback;
227 * Sets the factory object to use to convert ForeignTitle objects into local
229 * @param ImportTitleFactory $factory
231 public function setImportTitleFactory( $factory ) {
232 $this->importTitleFactory
= $factory;
236 * Set a target namespace to override the defaults
237 * @param null|int $namespace
240 public function setTargetNamespace( $namespace ) {
241 if ( is_null( $namespace ) ) {
242 // Don't override namespaces
243 $this->setImportTitleFactory( new NaiveImportTitleFactory() );
247 MWNamespace
::exists( intval( $namespace ) )
249 $namespace = intval( $namespace );
250 $this->setImportTitleFactory( new NamespaceImportTitleFactory( $namespace ) );
258 * Set a target root page under which all pages are imported
259 * @param null|string $rootpage
262 public function setTargetRootPage( $rootpage ) {
263 $status = Status
::newGood();
264 if ( is_null( $rootpage ) ) {
266 $this->setImportTitleFactory( new NaiveImportTitleFactory() );
267 } elseif ( $rootpage !== '' ) {
268 $rootpage = rtrim( $rootpage, '/' ); // avoid double slashes
269 $title = Title
::newFromText( $rootpage );
271 if ( !$title ||
$title->isExternal() ) {
272 $status->fatal( 'import-rootpage-invalid' );
274 if ( !MWNamespace
::hasSubpages( $title->getNamespace() ) ) {
277 $displayNSText = $title->getNamespace() == NS_MAIN
278 ?
wfMessage( 'blanknamespace' )->text()
279 : $wgContLang->getNsText( $title->getNamespace() );
280 $status->fatal( 'import-rootpage-nosubpage', $displayNSText );
282 // set namespace to 'all', so the namespace check in processTitle() can pass
283 $this->setTargetNamespace( null );
284 $this->setImportTitleFactory( new SubpageImportTitleFactory( $title ) );
294 public function setImageBasePath( $dir ) {
295 $this->mImageBasePath
= $dir;
299 * @param bool $import
301 public function setImportUploads( $import ) {
302 $this->mImportUploads
= $import;
306 * Default per-page callback. Sets up some things related to site statistics
307 * @param array $titleAndForeignTitle Two-element array, with Title object at
308 * index 0 and ForeignTitle object at index 1
311 public function beforeImportPage( $titleAndForeignTitle ) {
312 $title = $titleAndForeignTitle[0];
313 $page = WikiPage
::factory( $title );
314 $this->countableCache
['title_' . $title->getPrefixedText()] = $page->isCountable();
319 * Default per-revision callback, performs the import.
320 * @param WikiRevision $revision
323 public function importRevision( $revision ) {
324 if ( !$revision->getContentHandler()->canBeUsedOn( $revision->getTitle() ) ) {
325 $this->notice( 'import-error-bad-location',
326 $revision->getTitle()->getPrefixedText(),
328 $revision->getModel(),
329 $revision->getFormat() );
335 return $revision->importOldRevision();
336 } catch ( MWContentSerializationException
$ex ) {
337 $this->notice( 'import-error-unserialize',
338 $revision->getTitle()->getPrefixedText(),
340 $revision->getModel(),
341 $revision->getFormat() );
348 * Default per-revision callback, performs the import.
349 * @param WikiRevision $revision
352 public function importLogItem( $revision ) {
353 return $revision->importLogItem();
358 * @param WikiRevision $revision
361 public function importUpload( $revision ) {
362 return $revision->importUpload();
366 * Mostly for hook use
367 * @param Title $title
368 * @param ForeignTitle $foreignTitle
369 * @param int $revCount
370 * @param int $sRevCount
371 * @param array $pageInfo
374 public function finishImportPage( $title, $foreignTitle, $revCount,
375 $sRevCount, $pageInfo ) {
377 // Update article count statistics (T42009)
378 // The normal counting logic in WikiPage->doEditUpdates() is designed for
379 // one-revision-at-a-time editing, not bulk imports. In this situation it
380 // suffers from issues of slave lag. We let WikiPage handle the total page
381 // and revision count, and we implement our own custom logic for the
382 // article (content page) count.
383 $page = WikiPage
::factory( $title );
384 $page->loadPageData( 'fromdbmaster' );
385 $content = $page->getContent();
386 if ( $content === null ) {
387 wfDebug( __METHOD__
. ': Skipping article count adjustment for ' . $title .
388 ' because WikiPage::getContent() returned null' );
390 $editInfo = $page->prepareContentForEdit( $content );
391 $countKey = 'title_' . $title->getPrefixedText();
392 $countable = $page->isCountable( $editInfo );
393 if ( array_key_exists( $countKey, $this->countableCache
) &&
394 $countable != $this->countableCache
[$countKey] ) {
395 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [
396 'articles' => ( (int)$countable - (int)$this->countableCache
[$countKey] )
401 $args = func_get_args();
402 return Hooks
::run( 'AfterImportPage', $args );
406 * Alternate per-revision callback, for debugging.
407 * @param WikiRevision $revision
409 public function debugRevisionHandler( &$revision ) {
410 $this->debug( "Got revision:" );
411 if ( is_object( $revision->title
) ) {
412 $this->debug( "-- Title: " . $revision->title
->getPrefixedText() );
414 $this->debug( "-- Title: <invalid>" );
416 $this->debug( "-- User: " . $revision->user_text
);
417 $this->debug( "-- Timestamp: " . $revision->timestamp
);
418 $this->debug( "-- Comment: " . $revision->comment
);
419 $this->debug( "-- Text: " . $revision->text
);
423 * Notify the callback function of site info
424 * @param array $siteInfo
427 private function siteInfoCallback( $siteInfo ) {
428 if ( isset( $this->mSiteInfoCallback
) ) {
429 return call_user_func_array( $this->mSiteInfoCallback
,
430 [ $siteInfo, $this ] );
437 * Notify the callback function when a new "<page>" is reached.
438 * @param Title $title
440 function pageCallback( $title ) {
441 if ( isset( $this->mPageCallback
) ) {
442 call_user_func( $this->mPageCallback
, $title );
447 * Notify the callback function when a "</page>" is closed.
448 * @param Title $title
449 * @param ForeignTitle $foreignTitle
450 * @param int $revCount
451 * @param int $sucCount Number of revisions for which callback returned true
452 * @param array $pageInfo Associative array of page information
454 private function pageOutCallback( $title, $foreignTitle, $revCount,
455 $sucCount, $pageInfo ) {
456 if ( isset( $this->mPageOutCallback
) ) {
457 $args = func_get_args();
458 call_user_func_array( $this->mPageOutCallback
, $args );
463 * Notify the callback function of a revision
464 * @param WikiRevision $revision
467 private function revisionCallback( $revision ) {
468 if ( isset( $this->mRevisionCallback
) ) {
469 return call_user_func_array( $this->mRevisionCallback
,
470 [ $revision, $this ] );
477 * Notify the callback function of a new log item
478 * @param WikiRevision $revision
481 private function logItemCallback( $revision ) {
482 if ( isset( $this->mLogItemCallback
) ) {
483 return call_user_func_array( $this->mLogItemCallback
,
484 [ $revision, $this ] );
491 * Retrieves the contents of the named attribute of the current element.
492 * @param string $attr The name of the attribute
493 * @return string The value of the attribute or an empty string if it is not set in the current
496 public function nodeAttribute( $attr ) {
497 return $this->reader
->getAttribute( $attr );
501 * Shouldn't something like this be built-in to XMLReader?
502 * Fetches text contents of the current element, assuming
503 * no sub-elements or such scary things.
507 public function nodeContents() {
508 if ( $this->reader
->isEmptyElement
) {
512 while ( $this->reader
->read() ) {
513 switch ( $this->reader
->nodeType
) {
514 case XMLReader
::TEXT
:
515 case XMLReader
::CDATA
:
516 case XMLReader
::SIGNIFICANT_WHITESPACE
:
517 $buffer .= $this->reader
->value
;
519 case XMLReader
::END_ELEMENT
:
524 $this->reader
->close();
529 * Primary entry point
530 * @throws MWException
533 public function doImport() {
534 // Calls to reader->read need to be wrapped in calls to
535 // libxml_disable_entity_loader() to avoid local file
536 // inclusion attacks (bug 46932).
537 $oldDisable = libxml_disable_entity_loader( true );
538 $this->reader
->read();
540 if ( $this->reader
->localName
!= 'mediawiki' ) {
541 libxml_disable_entity_loader( $oldDisable );
542 throw new MWException( "Expected <mediawiki> tag, got " .
543 $this->reader
->localName
);
545 $this->debug( "<mediawiki> tag is correct." );
547 $this->debug( "Starting primary dump processing loop." );
549 $keepReading = $this->reader
->read();
553 while ( $keepReading ) {
554 $tag = $this->reader
->localName
;
555 $type = $this->reader
->nodeType
;
557 if ( !Hooks
::run( 'ImportHandleToplevelXMLTag', [ $this ] ) ) {
559 } elseif ( $tag == 'mediawiki' && $type == XMLReader
::END_ELEMENT
) {
561 } elseif ( $tag == 'siteinfo' ) {
562 $this->handleSiteInfo();
563 } elseif ( $tag == 'page' ) {
565 } elseif ( $tag == 'logitem' ) {
566 $this->handleLogItem();
567 } elseif ( $tag != '#text' ) {
568 $this->warn( "Unhandled top-level XML tag $tag" );
574 $keepReading = $this->reader
->next();
576 $this->debug( "Skip" );
578 $keepReading = $this->reader
->read();
581 } catch ( Exception
$ex ) {
586 libxml_disable_entity_loader( $oldDisable );
587 $this->reader
->close();
596 private function handleSiteInfo() {
597 $this->debug( "Enter site info handler." );
600 // Fields that can just be stuffed in the siteInfo object
601 $normalFields = [ 'sitename', 'base', 'generator', 'case' ];
603 while ( $this->reader
->read() ) {
604 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
605 $this->reader
->localName
== 'siteinfo' ) {
609 $tag = $this->reader
->localName
;
611 if ( $tag == 'namespace' ) {
612 $this->foreignNamespaces
[$this->nodeAttribute( 'key' )] =
613 $this->nodeContents();
614 } elseif ( in_array( $tag, $normalFields ) ) {
615 $siteInfo[$tag] = $this->nodeContents();
619 $siteInfo['_namespaces'] = $this->foreignNamespaces
;
620 $this->siteInfoCallback( $siteInfo );
623 private function handleLogItem() {
624 $this->debug( "Enter log item handler." );
627 // Fields that can just be stuffed in the pageInfo object
628 $normalFields = [ 'id', 'comment', 'type', 'action', 'timestamp',
629 'logtitle', 'params' ];
631 while ( $this->reader
->read() ) {
632 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
633 $this->reader
->localName
== 'logitem' ) {
637 $tag = $this->reader
->localName
;
639 if ( !Hooks
::run( 'ImportHandleLogItemXMLTag', [
643 } elseif ( in_array( $tag, $normalFields ) ) {
644 $logInfo[$tag] = $this->nodeContents();
645 } elseif ( $tag == 'contributor' ) {
646 $logInfo['contributor'] = $this->handleContributor();
647 } elseif ( $tag != '#text' ) {
648 $this->warn( "Unhandled log-item XML tag $tag" );
652 $this->processLogItem( $logInfo );
656 * @param array $logInfo
659 private function processLogItem( $logInfo ) {
661 $revision = new WikiRevision( $this->config
);
663 if ( isset( $logInfo['id'] ) ) {
664 $revision->setID( $logInfo['id'] );
666 $revision->setType( $logInfo['type'] );
667 $revision->setAction( $logInfo['action'] );
668 if ( isset( $logInfo['timestamp'] ) ) {
669 $revision->setTimestamp( $logInfo['timestamp'] );
671 if ( isset( $logInfo['params'] ) ) {
672 $revision->setParams( $logInfo['params'] );
674 if ( isset( $logInfo['logtitle'] ) ) {
675 // @todo Using Title for non-local titles is a recipe for disaster.
676 // We should use ForeignTitle here instead.
677 $revision->setTitle( Title
::newFromText( $logInfo['logtitle'] ) );
680 $revision->setNoUpdates( $this->mNoUpdates
);
682 if ( isset( $logInfo['comment'] ) ) {
683 $revision->setComment( $logInfo['comment'] );
686 if ( isset( $logInfo['contributor']['ip'] ) ) {
687 $revision->setUserIP( $logInfo['contributor']['ip'] );
690 if ( !isset( $logInfo['contributor']['username'] ) ) {
691 $revision->setUsername( 'Unknown user' );
693 $revision->setUsername( $logInfo['contributor']['username'] );
696 return $this->logItemCallback( $revision );
699 private function handlePage() {
701 $this->debug( "Enter page handler." );
702 $pageInfo = [ 'revisionCount' => 0, 'successfulRevisionCount' => 0 ];
704 // Fields that can just be stuffed in the pageInfo object
705 $normalFields = [ 'title', 'ns', 'id', 'redirect', 'restrictions' ];
710 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
711 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
712 $this->reader
->localName
== 'page' ) {
718 $tag = $this->reader
->localName
;
721 // The title is invalid, bail out of this page
723 } elseif ( !Hooks
::run( 'ImportHandlePageXMLTag', [ $this,
726 } elseif ( in_array( $tag, $normalFields ) ) {
730 // <title>Page</title>
731 // <redirect title="NewTitle"/>
733 // Because the redirect tag is built differently, we need special handling for that case.
734 if ( $tag == 'redirect' ) {
735 $pageInfo[$tag] = $this->nodeAttribute( 'title' );
737 $pageInfo[$tag] = $this->nodeContents();
739 } elseif ( $tag == 'revision' ||
$tag == 'upload' ) {
740 if ( !isset( $title ) ) {
741 $title = $this->processTitle( $pageInfo['title'],
742 isset( $pageInfo['ns'] ) ?
$pageInfo['ns'] : null );
744 // $title is either an array of two titles or false.
745 if ( is_array( $title ) ) {
746 $this->pageCallback( $title );
747 list( $pageInfo['_title'], $foreignTitle ) = $title;
755 if ( $tag == 'revision' ) {
756 $this->handleRevision( $pageInfo );
758 $this->handleUpload( $pageInfo );
761 } elseif ( $tag != '#text' ) {
762 $this->warn( "Unhandled page XML tag $tag" );
767 // @note $pageInfo is only set if a valid $title is processed above with
768 // no error. If we have a valid $title, then pageCallback is called
769 // above, $pageInfo['title'] is set and we do pageOutCallback here.
770 // If $pageInfo['_title'] is not set, then $foreignTitle is also not
771 // set since they both come from $title above.
772 if ( array_key_exists( '_title', $pageInfo ) ) {
773 $this->pageOutCallback( $pageInfo['_title'], $foreignTitle,
774 $pageInfo['revisionCount'],
775 $pageInfo['successfulRevisionCount'],
781 * @param array $pageInfo
783 private function handleRevision( &$pageInfo ) {
784 $this->debug( "Enter revision handler" );
787 $normalFields = [ 'id', 'timestamp', 'comment', 'minor', 'model', 'format', 'text' ];
791 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
792 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
793 $this->reader
->localName
== 'revision' ) {
797 $tag = $this->reader
->localName
;
799 if ( !Hooks
::run( 'ImportHandleRevisionXMLTag', [
800 $this, $pageInfo, $revisionInfo
803 } elseif ( in_array( $tag, $normalFields ) ) {
804 $revisionInfo[$tag] = $this->nodeContents();
805 } elseif ( $tag == 'contributor' ) {
806 $revisionInfo['contributor'] = $this->handleContributor();
807 } elseif ( $tag != '#text' ) {
808 $this->warn( "Unhandled revision XML tag $tag" );
813 $pageInfo['revisionCount']++
;
814 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
815 $pageInfo['successfulRevisionCount']++
;
820 * @param array $pageInfo
821 * @param array $revisionInfo
824 private function processRevision( $pageInfo, $revisionInfo ) {
825 global $wgMaxArticleSize;
827 // Make sure revisions won't violate $wgMaxArticleSize, which could lead to
828 // database errors and instability. Testing for revisions with only listed
829 // content models, as other content models might use serialization formats
830 // which aren't checked against $wgMaxArticleSize.
831 if ( ( !isset( $revisionInfo['model'] ) ||
832 in_array( $revisionInfo['model'], [
840 strlen( $revisionInfo['text'] ) > $wgMaxArticleSize * 1024
842 throw new MWException( 'The text of ' .
843 ( isset( $revisionInfo['id'] ) ?
844 "the revision with ID $revisionInfo[id]" :
846 ) . " exceeds the maximum allowable size ($wgMaxArticleSize KB)" );
849 $revision = new WikiRevision( $this->config
);
851 if ( isset( $revisionInfo['id'] ) ) {
852 $revision->setID( $revisionInfo['id'] );
854 if ( isset( $revisionInfo['model'] ) ) {
855 $revision->setModel( $revisionInfo['model'] );
857 if ( isset( $revisionInfo['format'] ) ) {
858 $revision->setFormat( $revisionInfo['format'] );
860 $revision->setTitle( $pageInfo['_title'] );
862 if ( isset( $revisionInfo['text'] ) ) {
863 $handler = $revision->getContentHandler();
864 $text = $handler->importTransform(
865 $revisionInfo['text'],
866 $revision->getFormat() );
868 $revision->setText( $text );
870 if ( isset( $revisionInfo['timestamp'] ) ) {
871 $revision->setTimestamp( $revisionInfo['timestamp'] );
873 $revision->setTimestamp( wfTimestampNow() );
876 if ( isset( $revisionInfo['comment'] ) ) {
877 $revision->setComment( $revisionInfo['comment'] );
880 if ( isset( $revisionInfo['minor'] ) ) {
881 $revision->setMinor( true );
883 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
884 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
885 } elseif ( isset( $revisionInfo['contributor']['username'] ) ) {
886 $revision->setUsername( $revisionInfo['contributor']['username'] );
888 $revision->setUsername( 'Unknown user' );
890 $revision->setNoUpdates( $this->mNoUpdates
);
892 return $this->revisionCallback( $revision );
896 * @param array $pageInfo
899 private function handleUpload( &$pageInfo ) {
900 $this->debug( "Enter upload handler" );
903 $normalFields = [ 'timestamp', 'comment', 'filename', 'text',
904 'src', 'size', 'sha1base36', 'archivename', 'rel' ];
908 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
909 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
910 $this->reader
->localName
== 'upload' ) {
914 $tag = $this->reader
->localName
;
916 if ( !Hooks
::run( 'ImportHandleUploadXMLTag', [
920 } elseif ( in_array( $tag, $normalFields ) ) {
921 $uploadInfo[$tag] = $this->nodeContents();
922 } elseif ( $tag == 'contributor' ) {
923 $uploadInfo['contributor'] = $this->handleContributor();
924 } elseif ( $tag == 'contents' ) {
925 $contents = $this->nodeContents();
926 $encoding = $this->reader
->getAttribute( 'encoding' );
927 if ( $encoding === 'base64' ) {
928 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
929 $uploadInfo['isTempSrc'] = true;
931 } elseif ( $tag != '#text' ) {
932 $this->warn( "Unhandled upload XML tag $tag" );
937 if ( $this->mImageBasePath
&& isset( $uploadInfo['rel'] ) ) {
938 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
939 if ( file_exists( $path ) ) {
940 $uploadInfo['fileSrc'] = $path;
941 $uploadInfo['isTempSrc'] = false;
945 if ( $this->mImportUploads
) {
946 return $this->processUpload( $pageInfo, $uploadInfo );
951 * @param string $contents
954 private function dumpTemp( $contents ) {
955 $filename = tempnam( wfTempDir(), 'importupload' );
956 file_put_contents( $filename, $contents );
961 * @param array $pageInfo
962 * @param array $uploadInfo
965 private function processUpload( $pageInfo, $uploadInfo ) {
966 $revision = new WikiRevision( $this->config
);
967 $text = isset( $uploadInfo['text'] ) ?
$uploadInfo['text'] : '';
969 $revision->setTitle( $pageInfo['_title'] );
970 $revision->setID( $pageInfo['id'] );
971 $revision->setTimestamp( $uploadInfo['timestamp'] );
972 $revision->setText( $text );
973 $revision->setFilename( $uploadInfo['filename'] );
974 if ( isset( $uploadInfo['archivename'] ) ) {
975 $revision->setArchiveName( $uploadInfo['archivename'] );
977 $revision->setSrc( $uploadInfo['src'] );
978 if ( isset( $uploadInfo['fileSrc'] ) ) {
979 $revision->setFileSrc( $uploadInfo['fileSrc'],
980 !empty( $uploadInfo['isTempSrc'] ) );
982 if ( isset( $uploadInfo['sha1base36'] ) ) {
983 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
985 $revision->setSize( intval( $uploadInfo['size'] ) );
986 $revision->setComment( $uploadInfo['comment'] );
988 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
989 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
991 if ( isset( $uploadInfo['contributor']['username'] ) ) {
992 $revision->setUsername( $uploadInfo['contributor']['username'] );
994 $revision->setNoUpdates( $this->mNoUpdates
);
996 return call_user_func( $this->mUploadCallback
, $revision );
1002 private function handleContributor() {
1003 $fields = [ 'id', 'ip', 'username' ];
1006 if ( $this->reader
->isEmptyElement
) {
1009 while ( $this->reader
->read() ) {
1010 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
1011 $this->reader
->localName
== 'contributor' ) {
1015 $tag = $this->reader
->localName
;
1017 if ( in_array( $tag, $fields ) ) {
1018 $info[$tag] = $this->nodeContents();
1026 * @param string $text
1027 * @param string|null $ns
1028 * @return array|bool
1030 private function processTitle( $text, $ns = null ) {
1031 if ( is_null( $this->foreignNamespaces
) ) {
1032 $foreignTitleFactory = new NaiveForeignTitleFactory();
1034 $foreignTitleFactory = new NamespaceAwareForeignTitleFactory(
1035 $this->foreignNamespaces
);
1038 $foreignTitle = $foreignTitleFactory->createForeignTitle( $text,
1041 $title = $this->importTitleFactory
->createTitleFromForeignTitle(
1044 $commandLineMode = $this->config
->get( 'CommandLineMode' );
1045 if ( is_null( $title ) ) {
1046 # Invalid page title? Ignore the page
1047 $this->notice( 'import-error-invalid', $foreignTitle->getFullText() );
1049 } elseif ( $title->isExternal() ) {
1050 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
1052 } elseif ( !$title->canExist() ) {
1053 $this->notice( 'import-error-special', $title->getPrefixedText() );
1055 } elseif ( !$title->userCan( 'edit' ) && !$commandLineMode ) {
1056 # Do not import if the importing wiki user cannot edit this page
1057 $this->notice( 'import-error-edit', $title->getPrefixedText() );
1059 } elseif ( !$title->exists() && !$title->userCan( 'create' ) && !$commandLineMode ) {
1060 # Do not import if the importing wiki user cannot create this page
1061 $this->notice( 'import-error-create', $title->getPrefixedText() );
1065 return [ $title, $foreignTitle ];