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, $mTargetNamespace, $mPageOutCallback;
38 private $mNoticeCallback, $mDebug;
39 private $mImportUploads, $mImageBasePath;
40 private $mNoUpdates = false;
43 /** @var ImportTitleFactory */
44 private $importTitleFactory;
46 private $countableCache = array();
49 * Creates an ImportXMLReader drawing from the source provided
50 * @param ImportSource $source
51 * @param Config $config
53 function __construct( ImportSource
$source, Config
$config = null ) {
54 $this->reader
= new XMLReader();
56 wfDeprecated( __METHOD__
. ' without a Config instance', '1.25' );
57 $config = ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
59 $this->config
= $config;
61 if ( !in_array( 'uploadsource', stream_get_wrappers() ) ) {
62 stream_wrapper_register( 'uploadsource', 'UploadSourceAdapter' );
64 $id = UploadSourceAdapter
::registerSource( $source );
65 if ( defined( 'LIBXML_PARSEHUGE' ) ) {
66 $this->reader
->open( "uploadsource://$id", null, LIBXML_PARSEHUGE
);
68 $this->reader
->open( "uploadsource://$id" );
72 $this->setPageCallback( array( $this, 'beforeImportPage' ) );
73 $this->setRevisionCallback( array( $this, "importRevision" ) );
74 $this->setUploadCallback( array( $this, 'importUpload' ) );
75 $this->setLogItemCallback( array( $this, 'importLogItem' ) );
76 $this->setPageOutCallback( array( $this, 'finishImportPage' ) );
78 $this->importTitleFactory
= new NaiveImportTitleFactory();
82 * @return null|XMLReader
84 public function getReader() {
88 public function throwXmlError( $err ) {
89 $this->debug( "FAILURE: $err" );
90 wfDebug( "WikiImporter XML error: $err\n" );
93 public function debug( $data ) {
94 if ( $this->mDebug
) {
95 wfDebug( "IMPORT: $data\n" );
99 public function warn( $data ) {
100 wfDebug( "IMPORT: $data\n" );
103 public function notice( $msg /*, $param, ...*/ ) {
104 $params = func_get_args();
105 array_shift( $params );
107 if ( is_callable( $this->mNoticeCallback
) ) {
108 call_user_func( $this->mNoticeCallback
, $msg, $params );
109 } else { # No ImportReporter -> CLI
110 echo wfMessage( $msg, $params )->text() . "\n";
118 function setDebug( $debug ) {
119 $this->mDebug
= $debug;
123 * Set 'no updates' mode. In this mode, the link tables will not be updated by the importer
124 * @param bool $noupdates
126 function setNoUpdates( $noupdates ) {
127 $this->mNoUpdates
= $noupdates;
131 * Set a callback that displays notice messages
133 * @param callable $callback
136 public function setNoticeCallback( $callback ) {
137 return wfSetVar( $this->mNoticeCallback
, $callback );
141 * Sets the action to perform as each new page in the stream is reached.
142 * @param callable $callback
145 public function setPageCallback( $callback ) {
146 $previous = $this->mPageCallback
;
147 $this->mPageCallback
= $callback;
152 * Sets the action to perform as each page in the stream is completed.
153 * Callback accepts the page title (as a Title object), a second object
154 * with the original title form (in case it's been overridden into a
155 * local namespace), and a count of revisions.
157 * @param callable $callback
160 public function setPageOutCallback( $callback ) {
161 $previous = $this->mPageOutCallback
;
162 $this->mPageOutCallback
= $callback;
167 * Sets the action to perform as each page revision is reached.
168 * @param callable $callback
171 public function setRevisionCallback( $callback ) {
172 $previous = $this->mRevisionCallback
;
173 $this->mRevisionCallback
= $callback;
178 * Sets the action to perform as each file upload version is reached.
179 * @param callable $callback
182 public function setUploadCallback( $callback ) {
183 $previous = $this->mUploadCallback
;
184 $this->mUploadCallback
= $callback;
189 * Sets the action to perform as each log item reached.
190 * @param callable $callback
193 public function setLogItemCallback( $callback ) {
194 $previous = $this->mLogItemCallback
;
195 $this->mLogItemCallback
= $callback;
200 * Sets the action to perform when site info is encountered
201 * @param callable $callback
204 public function setSiteInfoCallback( $callback ) {
205 $previous = $this->mSiteInfoCallback
;
206 $this->mSiteInfoCallback
= $callback;
211 * Sets the factory object to use to convert ForeignTitle objects into local
213 * @param ImportTitleFactory $factory
215 public function setImportTitleFactory( $factory ) {
216 $this->importTitleFactory
= $factory;
220 * Set a target namespace to override the defaults
221 * @param null|int $namespace
224 public function setTargetNamespace( $namespace ) {
225 if ( is_null( $namespace ) ) {
226 // Don't override namespaces
227 $this->mTargetNamespace
= null;
228 $this->setImportTitleFactory( new NaiveImportTitleFactory() );
232 MWNamespace
::exists( intval( $namespace ) )
234 $namespace = intval( $namespace );
235 $this->mTargetNamespace
= $namespace;
236 $this->setImportTitleFactory( new NamespaceImportTitleFactory( $namespace ) );
244 * Set a target root page under which all pages are imported
245 * @param null|string $rootpage
248 public function setTargetRootPage( $rootpage ) {
249 $status = Status
::newGood();
250 if ( is_null( $rootpage ) ) {
252 $this->setImportTitleFactory( new NaiveImportTitleFactory() );
253 } elseif ( $rootpage !== '' ) {
254 $rootpage = rtrim( $rootpage, '/' ); //avoid double slashes
255 $title = Title
::newFromText( $rootpage, !is_null( $this->mTargetNamespace
)
256 ?
$this->mTargetNamespace
260 if ( !$title ||
$title->isExternal() ) {
261 $status->fatal( 'import-rootpage-invalid' );
263 if ( !MWNamespace
::hasSubpages( $title->getNamespace() ) ) {
266 $displayNSText = $title->getNamespace() == NS_MAIN
267 ?
wfMessage( 'blanknamespace' )->text()
268 : $wgContLang->getNsText( $title->getNamespace() );
269 $status->fatal( 'import-rootpage-nosubpage', $displayNSText );
271 // set namespace to 'all', so the namespace check in processTitle() can pass
272 $this->setTargetNamespace( null );
273 $this->setImportTitleFactory( new SubpageImportTitleFactory( $title ) );
283 public function setImageBasePath( $dir ) {
284 $this->mImageBasePath
= $dir;
288 * @param bool $import
290 public function setImportUploads( $import ) {
291 $this->mImportUploads
= $import;
295 * Default per-page callback. Sets up some things related to site statistics
296 * @param array $titleAndForeignTitle Two-element array, with Title object at
297 * index 0 and ForeignTitle object at index 1
300 public function beforeImportPage( $titleAndForeignTitle ) {
301 $title = $titleAndForeignTitle[0];
302 $page = WikiPage
::factory( $title );
303 $this->countableCache
['title_' . $title->getPrefixedText()] = $page->isCountable();
308 * Default per-revision callback, performs the import.
309 * @param WikiRevision $revision
312 public function importRevision( $revision ) {
313 if ( !$revision->getContentHandler()->canBeUsedOn( $revision->getTitle() ) ) {
314 $this->notice( 'import-error-bad-location',
315 $revision->getTitle()->getPrefixedText(),
317 $revision->getModel(),
318 $revision->getFormat() );
324 $dbw = wfGetDB( DB_MASTER
);
325 return $dbw->deadlockLoop( array( $revision, 'importOldRevision' ) );
326 } catch ( MWContentSerializationException
$ex ) {
327 $this->notice( 'import-error-unserialize',
328 $revision->getTitle()->getPrefixedText(),
330 $revision->getModel(),
331 $revision->getFormat() );
338 * Default per-revision callback, performs the import.
339 * @param WikiRevision $revision
342 public function importLogItem( $revision ) {
343 $dbw = wfGetDB( DB_MASTER
);
344 return $dbw->deadlockLoop( array( $revision, 'importLogItem' ) );
349 * @param WikiRevision $revision
352 public function importUpload( $revision ) {
353 $dbw = wfGetDB( DB_MASTER
);
354 return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
358 * Mostly for hook use
359 * @param Title $title
360 * @param ForeignTitle $foreignTitle
361 * @param int $revCount
362 * @param int $sRevCount
363 * @param array $pageInfo
366 public function finishImportPage( $title, $foreignTitle, $revCount,
367 $sRevCount, $pageInfo ) {
369 // Update article count statistics (T42009)
370 // The normal counting logic in WikiPage->doEditUpdates() is designed for
371 // one-revision-at-a-time editing, not bulk imports. In this situation it
372 // suffers from issues of slave lag. We let WikiPage handle the total page
373 // and revision count, and we implement our own custom logic for the
374 // article (content page) count.
375 $page = WikiPage
::factory( $title );
376 $page->loadPageData( 'fromdbmaster' );
377 $content = $page->getContent();
378 if ( $content === null ) {
379 wfDebug( __METHOD__
. ': Skipping article count adjustment for ' . $title .
380 ' because WikiPage::getContent() returned null' );
382 $editInfo = $page->prepareContentForEdit( $content );
383 $countKey = 'title_' . $title->getPrefixedText();
384 $countable = $page->isCountable( $editInfo );
385 if ( array_key_exists( $countKey, $this->countableCache
) &&
386 $countable != $this->countableCache
[ $countKey ] ) {
387 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array(
388 'articles' => ( (int)$countable - (int)$this->countableCache
[ $countKey ] )
393 $args = func_get_args();
394 return Hooks
::run( 'AfterImportPage', $args );
398 * Alternate per-revision callback, for debugging.
399 * @param WikiRevision $revision
401 public function debugRevisionHandler( &$revision ) {
402 $this->debug( "Got revision:" );
403 if ( is_object( $revision->title
) ) {
404 $this->debug( "-- Title: " . $revision->title
->getPrefixedText() );
406 $this->debug( "-- Title: <invalid>" );
408 $this->debug( "-- User: " . $revision->user_text
);
409 $this->debug( "-- Timestamp: " . $revision->timestamp
);
410 $this->debug( "-- Comment: " . $revision->comment
);
411 $this->debug( "-- Text: " . $revision->text
);
415 * Notify the callback function of site info
416 * @param array $siteInfo
419 private function siteInfoCallback( $siteInfo ) {
420 if ( isset( $this->mSiteInfoCallback
) ) {
421 return call_user_func_array( $this->mSiteInfoCallback
,
422 array( $siteInfo, $this ) );
429 * Notify the callback function when a new "<page>" is reached.
430 * @param Title $title
432 function pageCallback( $title ) {
433 if ( isset( $this->mPageCallback
) ) {
434 call_user_func( $this->mPageCallback
, $title );
439 * Notify the callback function when a "</page>" is closed.
440 * @param Title $title
441 * @param ForeignTitle $foreignTitle
442 * @param int $revCount
443 * @param int $sucCount Number of revisions for which callback returned true
444 * @param array $pageInfo Associative array of page information
446 private function pageOutCallback( $title, $foreignTitle, $revCount,
447 $sucCount, $pageInfo ) {
448 if ( isset( $this->mPageOutCallback
) ) {
449 $args = func_get_args();
450 call_user_func_array( $this->mPageOutCallback
, $args );
455 * Notify the callback function of a revision
456 * @param WikiRevision $revision
459 private function revisionCallback( $revision ) {
460 if ( isset( $this->mRevisionCallback
) ) {
461 return call_user_func_array( $this->mRevisionCallback
,
462 array( $revision, $this ) );
469 * Notify the callback function of a new log item
470 * @param WikiRevision $revision
473 private function logItemCallback( $revision ) {
474 if ( isset( $this->mLogItemCallback
) ) {
475 return call_user_func_array( $this->mLogItemCallback
,
476 array( $revision, $this ) );
483 * Retrieves the contents of the named attribute of the current element.
484 * @param string $attr The name of the attribute
485 * @return string The value of the attribute or an empty string if it is not set in the current
488 public function nodeAttribute( $attr ) {
489 return $this->reader
->getAttribute( $attr );
493 * Shouldn't something like this be built-in to XMLReader?
494 * Fetches text contents of the current element, assuming
495 * no sub-elements or such scary things.
499 public function nodeContents() {
500 if ( $this->reader
->isEmptyElement
) {
504 while ( $this->reader
->read() ) {
505 switch ( $this->reader
->nodeType
) {
506 case XMLReader
::TEXT
:
507 case XMLReader
::SIGNIFICANT_WHITESPACE
:
508 $buffer .= $this->reader
->value
;
510 case XMLReader
::END_ELEMENT
:
515 $this->reader
->close();
520 * Primary entry point
521 * @throws MWException
524 public function doImport() {
525 // Calls to reader->read need to be wrapped in calls to
526 // libxml_disable_entity_loader() to avoid local file
527 // inclusion attacks (bug 46932).
528 $oldDisable = libxml_disable_entity_loader( true );
529 $this->reader
->read();
531 if ( $this->reader
->name
!= 'mediawiki' ) {
532 libxml_disable_entity_loader( $oldDisable );
533 throw new MWException( "Expected <mediawiki> tag, got " .
534 $this->reader
->name
);
536 $this->debug( "<mediawiki> tag is correct." );
538 $this->debug( "Starting primary dump processing loop." );
540 $keepReading = $this->reader
->read();
544 while ( $keepReading ) {
545 $tag = $this->reader
->name
;
546 $type = $this->reader
->nodeType
;
548 if ( !Hooks
::run( 'ImportHandleToplevelXMLTag', array( $this ) ) ) {
550 } elseif ( $tag == 'mediawiki' && $type == XMLReader
::END_ELEMENT
) {
552 } elseif ( $tag == 'siteinfo' ) {
553 $this->handleSiteInfo();
554 } elseif ( $tag == 'page' ) {
556 } elseif ( $tag == 'logitem' ) {
557 $this->handleLogItem();
558 } elseif ( $tag != '#text' ) {
559 $this->warn( "Unhandled top-level XML tag $tag" );
565 $keepReading = $this->reader
->next();
567 $this->debug( "Skip" );
569 $keepReading = $this->reader
->read();
572 } catch ( Exception
$ex ) {
577 libxml_disable_entity_loader( $oldDisable );
578 $this->reader
->close();
587 private function handleSiteInfo() {
588 $this->debug( "Enter site info handler." );
591 // Fields that can just be stuffed in the siteInfo object
592 $normalFields = array( 'sitename', 'base', 'generator', 'case' );
594 while ( $this->reader
->read() ) {
595 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
596 $this->reader
->name
== 'siteinfo' ) {
600 $tag = $this->reader
->name
;
602 if ( $tag == 'namespace' ) {
603 $this->foreignNamespaces
[ $this->nodeAttribute( 'key' ) ] =
604 $this->nodeContents();
605 } elseif ( in_array( $tag, $normalFields ) ) {
606 $siteInfo[$tag] = $this->nodeContents();
610 $siteInfo['_namespaces'] = $this->foreignNamespaces
;
611 $this->siteInfoCallback( $siteInfo );
614 private function handleLogItem() {
615 $this->debug( "Enter log item handler." );
618 // Fields that can just be stuffed in the pageInfo object
619 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
620 'logtitle', 'params' );
622 while ( $this->reader
->read() ) {
623 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
624 $this->reader
->name
== 'logitem' ) {
628 $tag = $this->reader
->name
;
630 if ( !Hooks
::run( 'ImportHandleLogItemXMLTag', array(
634 } elseif ( in_array( $tag, $normalFields ) ) {
635 $logInfo[$tag] = $this->nodeContents();
636 } elseif ( $tag == 'contributor' ) {
637 $logInfo['contributor'] = $this->handleContributor();
638 } elseif ( $tag != '#text' ) {
639 $this->warn( "Unhandled log-item XML tag $tag" );
643 $this->processLogItem( $logInfo );
647 * @param array $logInfo
650 private function processLogItem( $logInfo ) {
651 $revision = new WikiRevision( $this->config
);
653 $revision->setID( $logInfo['id'] );
654 $revision->setType( $logInfo['type'] );
655 $revision->setAction( $logInfo['action'] );
656 $revision->setTimestamp( $logInfo['timestamp'] );
657 $revision->setParams( $logInfo['params'] );
658 $revision->setTitle( Title
::newFromText( $logInfo['logtitle'] ) );
659 $revision->setNoUpdates( $this->mNoUpdates
);
661 if ( isset( $logInfo['comment'] ) ) {
662 $revision->setComment( $logInfo['comment'] );
665 if ( isset( $logInfo['contributor']['ip'] ) ) {
666 $revision->setUserIP( $logInfo['contributor']['ip'] );
668 if ( isset( $logInfo['contributor']['username'] ) ) {
669 $revision->setUserName( $logInfo['contributor']['username'] );
672 return $this->logItemCallback( $revision );
675 private function handlePage() {
677 $this->debug( "Enter page handler." );
678 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
680 // Fields that can just be stuffed in the pageInfo object
681 $normalFields = array( 'title', 'ns', 'id', 'redirect', 'restrictions' );
686 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
687 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
688 $this->reader
->name
== 'page' ) {
694 $tag = $this->reader
->name
;
697 // The title is invalid, bail out of this page
699 } elseif ( !Hooks
::run( 'ImportHandlePageXMLTag', array( $this,
702 } elseif ( in_array( $tag, $normalFields ) ) {
706 // <title>Page</title>
707 // <redirect title="NewTitle"/>
709 // Because the redirect tag is built differently, we need special handling for that case.
710 if ( $tag == 'redirect' ) {
711 $pageInfo[$tag] = $this->nodeAttribute( 'title' );
713 $pageInfo[$tag] = $this->nodeContents();
715 } elseif ( $tag == 'revision' ||
$tag == 'upload' ) {
716 if ( !isset( $title ) ) {
717 $title = $this->processTitle( $pageInfo['title'],
718 isset( $pageInfo['ns'] ) ?
$pageInfo['ns'] : null );
725 $this->pageCallback( $title );
726 list( $pageInfo['_title'], $foreignTitle ) = $title;
730 if ( $tag == 'revision' ) {
731 $this->handleRevision( $pageInfo );
733 $this->handleUpload( $pageInfo );
736 } elseif ( $tag != '#text' ) {
737 $this->warn( "Unhandled page XML tag $tag" );
742 $this->pageOutCallback( $pageInfo['_title'], $foreignTitle,
743 $pageInfo['revisionCount'],
744 $pageInfo['successfulRevisionCount'],
749 * @param array $pageInfo
751 private function handleRevision( &$pageInfo ) {
752 $this->debug( "Enter revision handler" );
753 $revisionInfo = array();
755 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'model', 'format', 'text' );
759 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
760 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
761 $this->reader
->name
== 'revision' ) {
765 $tag = $this->reader
->name
;
767 if ( !Hooks
::run( 'ImportHandleRevisionXMLTag', array(
768 $this, $pageInfo, $revisionInfo
771 } elseif ( in_array( $tag, $normalFields ) ) {
772 $revisionInfo[$tag] = $this->nodeContents();
773 } elseif ( $tag == 'contributor' ) {
774 $revisionInfo['contributor'] = $this->handleContributor();
775 } elseif ( $tag != '#text' ) {
776 $this->warn( "Unhandled revision XML tag $tag" );
781 $pageInfo['revisionCount']++
;
782 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
783 $pageInfo['successfulRevisionCount']++
;
788 * @param array $pageInfo
789 * @param array $revisionInfo
792 private function processRevision( $pageInfo, $revisionInfo ) {
793 $revision = new WikiRevision( $this->config
);
795 if ( isset( $revisionInfo['id'] ) ) {
796 $revision->setID( $revisionInfo['id'] );
798 if ( isset( $revisionInfo['model'] ) ) {
799 $revision->setModel( $revisionInfo['model'] );
801 if ( isset( $revisionInfo['format'] ) ) {
802 $revision->setFormat( $revisionInfo['format'] );
804 $revision->setTitle( $pageInfo['_title'] );
806 if ( isset( $revisionInfo['text'] ) ) {
807 $handler = $revision->getContentHandler();
808 $text = $handler->importTransform(
809 $revisionInfo['text'],
810 $revision->getFormat() );
812 $revision->setText( $text );
814 if ( isset( $revisionInfo['timestamp'] ) ) {
815 $revision->setTimestamp( $revisionInfo['timestamp'] );
817 $revision->setTimestamp( wfTimestampNow() );
820 if ( isset( $revisionInfo['comment'] ) ) {
821 $revision->setComment( $revisionInfo['comment'] );
824 if ( isset( $revisionInfo['minor'] ) ) {
825 $revision->setMinor( true );
827 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
828 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
830 if ( isset( $revisionInfo['contributor']['username'] ) ) {
831 $revision->setUserName( $revisionInfo['contributor']['username'] );
833 $revision->setNoUpdates( $this->mNoUpdates
);
835 return $this->revisionCallback( $revision );
839 * @param array $pageInfo
842 private function handleUpload( &$pageInfo ) {
843 $this->debug( "Enter upload handler" );
844 $uploadInfo = array();
846 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
847 'src', 'size', 'sha1base36', 'archivename', 'rel' );
851 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
852 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
853 $this->reader
->name
== 'upload' ) {
857 $tag = $this->reader
->name
;
859 if ( !Hooks
::run( 'ImportHandleUploadXMLTag', array(
863 } elseif ( in_array( $tag, $normalFields ) ) {
864 $uploadInfo[$tag] = $this->nodeContents();
865 } elseif ( $tag == 'contributor' ) {
866 $uploadInfo['contributor'] = $this->handleContributor();
867 } elseif ( $tag == 'contents' ) {
868 $contents = $this->nodeContents();
869 $encoding = $this->reader
->getAttribute( 'encoding' );
870 if ( $encoding === 'base64' ) {
871 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
872 $uploadInfo['isTempSrc'] = true;
874 } elseif ( $tag != '#text' ) {
875 $this->warn( "Unhandled upload XML tag $tag" );
880 if ( $this->mImageBasePath
&& isset( $uploadInfo['rel'] ) ) {
881 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
882 if ( file_exists( $path ) ) {
883 $uploadInfo['fileSrc'] = $path;
884 $uploadInfo['isTempSrc'] = false;
888 if ( $this->mImportUploads
) {
889 return $this->processUpload( $pageInfo, $uploadInfo );
894 * @param string $contents
897 private function dumpTemp( $contents ) {
898 $filename = tempnam( wfTempDir(), 'importupload' );
899 file_put_contents( $filename, $contents );
904 * @param array $pageInfo
905 * @param array $uploadInfo
908 private function processUpload( $pageInfo, $uploadInfo ) {
909 $revision = new WikiRevision( $this->config
);
910 $text = isset( $uploadInfo['text'] ) ?
$uploadInfo['text'] : '';
912 $revision->setTitle( $pageInfo['_title'] );
913 $revision->setID( $pageInfo['id'] );
914 $revision->setTimestamp( $uploadInfo['timestamp'] );
915 $revision->setText( $text );
916 $revision->setFilename( $uploadInfo['filename'] );
917 if ( isset( $uploadInfo['archivename'] ) ) {
918 $revision->setArchiveName( $uploadInfo['archivename'] );
920 $revision->setSrc( $uploadInfo['src'] );
921 if ( isset( $uploadInfo['fileSrc'] ) ) {
922 $revision->setFileSrc( $uploadInfo['fileSrc'],
923 !empty( $uploadInfo['isTempSrc'] ) );
925 if ( isset( $uploadInfo['sha1base36'] ) ) {
926 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
928 $revision->setSize( intval( $uploadInfo['size'] ) );
929 $revision->setComment( $uploadInfo['comment'] );
931 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
932 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
934 if ( isset( $uploadInfo['contributor']['username'] ) ) {
935 $revision->setUserName( $uploadInfo['contributor']['username'] );
937 $revision->setNoUpdates( $this->mNoUpdates
);
939 return call_user_func( $this->mUploadCallback
, $revision );
945 private function handleContributor() {
946 $fields = array( 'id', 'ip', 'username' );
949 while ( $this->reader
->read() ) {
950 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
951 $this->reader
->name
== 'contributor' ) {
955 $tag = $this->reader
->name
;
957 if ( in_array( $tag, $fields ) ) {
958 $info[$tag] = $this->nodeContents();
966 * @param string $text
967 * @param string|null $ns
970 private function processTitle( $text, $ns = null ) {
971 if ( is_null( $this->foreignNamespaces
) ) {
972 $foreignTitleFactory = new NaiveForeignTitleFactory();
974 $foreignTitleFactory = new NamespaceAwareForeignTitleFactory(
975 $this->foreignNamespaces
);
978 $foreignTitle = $foreignTitleFactory->createForeignTitle( $text,
981 $title = $this->importTitleFactory
->createTitleFromForeignTitle(
984 $commandLineMode = $this->config
->get( 'CommandLineMode' );
985 if ( is_null( $title ) ) {
986 # Invalid page title? Ignore the page
987 $this->notice( 'import-error-invalid', $foreignTitle->getFullText() );
989 } elseif ( $title->isExternal() ) {
990 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
992 } elseif ( !$title->canExist() ) {
993 $this->notice( 'import-error-special', $title->getPrefixedText() );
995 } elseif ( !$title->userCan( 'edit' ) && !$commandLineMode ) {
996 # Do not import if the importing wiki user cannot edit this page
997 $this->notice( 'import-error-edit', $title->getPrefixedText() );
999 } elseif ( !$title->exists() && !$title->userCan( 'create' ) && !$commandLineMode ) {
1000 # Do not import if the importing wiki user cannot create this page
1001 $this->notice( 'import-error-create', $title->getPrefixedText() );
1005 return array( $title, $foreignTitle );
1009 /** This is a horrible hack used to keep source compatibility */
1010 class UploadSourceAdapter
{
1012 public static $sourceRegistrations = array();
1024 * @param ImportSource $source
1027 static function registerSource( ImportSource
$source ) {
1028 $id = wfRandomString();
1030 self
::$sourceRegistrations[$id] = $source;
1036 * @param string $path
1037 * @param string $mode
1038 * @param array $options
1039 * @param string $opened_path
1042 function stream_open( $path, $mode, $options, &$opened_path ) {
1043 $url = parse_url( $path );
1046 if ( !isset( self
::$sourceRegistrations[$id] ) ) {
1050 $this->mSource
= self
::$sourceRegistrations[$id];
1059 function stream_read( $count ) {
1063 while ( !$leave && !$this->mSource
->atEnd() &&
1064 strlen( $this->mBuffer
) < $count ) {
1065 $read = $this->mSource
->readChunk();
1067 if ( !strlen( $read ) ) {
1071 $this->mBuffer
.= $read;
1074 if ( strlen( $this->mBuffer
) ) {
1075 $return = substr( $this->mBuffer
, 0, $count );
1076 $this->mBuffer
= substr( $this->mBuffer
, $count );
1079 $this->mPosition +
= strlen( $return );
1085 * @param string $data
1088 function stream_write( $data ) {
1095 function stream_tell() {
1096 return $this->mPosition
;
1102 function stream_eof() {
1103 return $this->mSource
->atEnd();
1109 function url_stat() {
1112 $result['dev'] = $result[0] = 0;
1113 $result['ino'] = $result[1] = 0;
1114 $result['mode'] = $result[2] = 0;
1115 $result['nlink'] = $result[3] = 0;
1116 $result['uid'] = $result[4] = 0;
1117 $result['gid'] = $result[5] = 0;
1118 $result['rdev'] = $result[6] = 0;
1119 $result['size'] = $result[7] = 0;
1120 $result['atime'] = $result[8] = 0;
1121 $result['mtime'] = $result[9] = 0;
1122 $result['ctime'] = $result[10] = 0;
1123 $result['blksize'] = $result[11] = 0;
1124 $result['blocks'] = $result[12] = 0;
1131 * @todo document (e.g. one-sentence class description).
1132 * @ingroup SpecialPage
1134 class WikiRevision
{
1135 /** @todo Unused? */
1136 public $importer = null;
1139 public $title = null;
1145 public $timestamp = "20010115000000";
1149 * @todo Can't find any uses. Public, because that's suspicious. Get clarity. */
1153 public $user_text = "";
1156 public $model = null;
1159 public $format = null;
1168 public $content = null;
1170 /** @var ContentHandler */
1171 protected $contentHandler = null;
1174 public $comment = "";
1177 public $minor = false;
1183 public $action = "";
1186 public $params = "";
1189 public $fileSrc = '';
1191 /** @var bool|string */
1192 public $sha1base36 = false;
1198 public $isTemp = false;
1201 public $archiveName = '';
1203 protected $filename;
1208 /** @todo Unused? */
1212 private $mNoUpdates = false;
1214 /** @var Config $config */
1217 public function __construct( Config
$config ) {
1218 $this->config
= $config;
1222 * @param Title $title
1223 * @throws MWException
1225 function setTitle( $title ) {
1226 if ( is_object( $title ) ) {
1227 $this->title
= $title;
1228 } elseif ( is_null( $title ) ) {
1229 throw new MWException( "WikiRevision given a null title in import. "
1230 . "You may need to adjust \$wgLegalTitleChars." );
1232 throw new MWException( "WikiRevision given non-object title in import." );
1239 function setID( $id ) {
1246 function setTimestamp( $ts ) {
1247 # 2003-08-05T18:30:02Z
1248 $this->timestamp
= wfTimestamp( TS_MW
, $ts );
1252 * @param string $user
1254 function setUsername( $user ) {
1255 $this->user_text
= $user;
1261 function setUserIP( $ip ) {
1262 $this->user_text
= $ip;
1266 * @param string $model
1268 function setModel( $model ) {
1269 $this->model
= $model;
1273 * @param string $format
1275 function setFormat( $format ) {
1276 $this->format
= $format;
1280 * @param string $text
1282 function setText( $text ) {
1283 $this->text
= $text;
1287 * @param string $text
1289 function setComment( $text ) {
1290 $this->comment
= $text;
1294 * @param bool $minor
1296 function setMinor( $minor ) {
1297 $this->minor
= (bool)$minor;
1303 function setSrc( $src ) {
1308 * @param string $src
1309 * @param bool $isTemp
1311 function setFileSrc( $src, $isTemp ) {
1312 $this->fileSrc
= $src;
1313 $this->fileIsTemp
= $isTemp;
1317 * @param string $sha1base36
1319 function setSha1Base36( $sha1base36 ) {
1320 $this->sha1base36
= $sha1base36;
1324 * @param string $filename
1326 function setFilename( $filename ) {
1327 $this->filename
= $filename;
1331 * @param string $archiveName
1333 function setArchiveName( $archiveName ) {
1334 $this->archiveName
= $archiveName;
1340 function setSize( $size ) {
1341 $this->size
= intval( $size );
1345 * @param string $type
1347 function setType( $type ) {
1348 $this->type
= $type;
1352 * @param string $action
1354 function setAction( $action ) {
1355 $this->action
= $action;
1359 * @param array $params
1361 function setParams( $params ) {
1362 $this->params
= $params;
1366 * @param bool $noupdates
1368 public function setNoUpdates( $noupdates ) {
1369 $this->mNoUpdates
= $noupdates;
1375 function getTitle() {
1376 return $this->title
;
1389 function getTimestamp() {
1390 return $this->timestamp
;
1396 function getUser() {
1397 return $this->user_text
;
1403 * @deprecated Since 1.21, use getContent() instead.
1405 function getText() {
1406 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1412 * @return ContentHandler
1414 function getContentHandler() {
1415 if ( is_null( $this->contentHandler
) ) {
1416 $this->contentHandler
= ContentHandler
::getForModelID( $this->getModel() );
1419 return $this->contentHandler
;
1425 function getContent() {
1426 if ( is_null( $this->content
) ) {
1427 $handler = $this->getContentHandler();
1428 $this->content
= $handler->unserializeContent( $this->text
, $this->getFormat() );
1431 return $this->content
;
1437 function getModel() {
1438 if ( is_null( $this->model
) ) {
1439 $this->model
= $this->getTitle()->getContentModel();
1442 return $this->model
;
1448 function getFormat() {
1449 if ( is_null( $this->format
) ) {
1450 $this->format
= $this->getContentHandler()->getDefaultFormat();
1453 return $this->format
;
1459 function getComment() {
1460 return $this->comment
;
1466 function getMinor() {
1467 return $this->minor
;
1478 * @return bool|string
1480 function getSha1() {
1481 if ( $this->sha1base36
) {
1482 return wfBaseConvert( $this->sha1base36
, 36, 16 );
1490 function getFileSrc() {
1491 return $this->fileSrc
;
1497 function isTempSrc() {
1498 return $this->isTemp
;
1504 function getFilename() {
1505 return $this->filename
;
1511 function getArchiveName() {
1512 return $this->archiveName
;
1518 function getSize() {
1525 function getType() {
1532 function getAction() {
1533 return $this->action
;
1539 function getParams() {
1540 return $this->params
;
1546 function importOldRevision() {
1547 $dbw = wfGetDB( DB_MASTER
);
1549 # Sneak a single revision into place
1550 $user = User
::newFromName( $this->getUser() );
1552 $userId = intval( $user->getId() );
1553 $userText = $user->getName();
1557 $userText = $this->getUser();
1558 $userObj = new User
;
1561 // avoid memory leak...?
1562 $linkCache = LinkCache
::singleton();
1563 $linkCache->clear();
1565 $page = WikiPage
::factory( $this->title
);
1566 $page->loadPageData( 'fromdbmaster' );
1567 if ( !$page->exists() ) {
1568 # must create the page...
1569 $pageId = $page->insertOn( $dbw );
1571 $oldcountable = null;
1573 $pageId = $page->getId();
1576 $prior = $dbw->selectField( 'revision', '1',
1577 array( 'rev_page' => $pageId,
1578 'rev_timestamp' => $dbw->timestamp( $this->timestamp
),
1579 'rev_user_text' => $userText,
1580 'rev_comment' => $this->getComment() ),
1584 // @todo FIXME: This could fail slightly for multiple matches :P
1585 wfDebug( __METHOD__
. ": skipping existing revision for [[" .
1586 $this->title
->getPrefixedText() . "]], timestamp " . $this->timestamp
. "\n" );
1591 # @todo FIXME: Use original rev_id optionally (better for backups)
1593 $revision = new Revision( array(
1594 'title' => $this->title
,
1596 'content_model' => $this->getModel(),
1597 'content_format' => $this->getFormat(),
1598 //XXX: just set 'content' => $this->getContent()?
1599 'text' => $this->getContent()->serialize( $this->getFormat() ),
1600 'comment' => $this->getComment(),
1602 'user_text' => $userText,
1603 'timestamp' => $this->timestamp
,
1604 'minor_edit' => $this->minor
,
1606 $revision->insertOn( $dbw );
1607 $changed = $page->updateIfNewerOn( $dbw, $revision );
1609 if ( $changed !== false && !$this->mNoUpdates
) {
1610 wfDebug( __METHOD__
. ": running updates\n" );
1611 // countable/oldcountable stuff is handled in WikiImporter::finishImportPage
1612 $page->doEditUpdates(
1615 array( 'created' => $created, 'oldcountable' => 'no-change' )
1622 function importLogItem() {
1623 $dbw = wfGetDB( DB_MASTER
);
1624 # @todo FIXME: This will not record autoblocks
1625 if ( !$this->getTitle() ) {
1626 wfDebug( __METHOD__
. ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1627 $this->timestamp
. "\n" );
1630 # Check if it exists already
1631 // @todo FIXME: Use original log ID (better for backups)
1632 $prior = $dbw->selectField( 'logging', '1',
1633 array( 'log_type' => $this->getType(),
1634 'log_action' => $this->getAction(),
1635 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1636 'log_namespace' => $this->getTitle()->getNamespace(),
1637 'log_title' => $this->getTitle()->getDBkey(),
1638 'log_comment' => $this->getComment(),
1639 #'log_user_text' => $this->user_text,
1640 'log_params' => $this->params
),
1643 // @todo FIXME: This could fail slightly for multiple matches :P
1646 . ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp "
1647 . $this->timestamp
. "\n" );
1650 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1652 'log_id' => $log_id,
1653 'log_type' => $this->type
,
1654 'log_action' => $this->action
,
1655 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1656 'log_user' => User
::idFromName( $this->user_text
),
1657 #'log_user_text' => $this->user_text,
1658 'log_namespace' => $this->getTitle()->getNamespace(),
1659 'log_title' => $this->getTitle()->getDBkey(),
1660 'log_comment' => $this->getComment(),
1661 'log_params' => $this->params
1663 $dbw->insert( 'logging', $data, __METHOD__
);
1669 function importUpload() {
1671 $archiveName = $this->getArchiveName();
1672 if ( $archiveName ) {
1673 wfDebug( __METHOD__
. "Importing archived file as $archiveName\n" );
1674 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1675 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1677 $file = wfLocalFile( $this->getTitle() );
1678 $file->load( File
::READ_LATEST
);
1679 wfDebug( __METHOD__
. 'Importing new file as ' . $file->getName() . "\n" );
1680 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1681 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1682 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1683 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1684 wfDebug( __METHOD__
. "File already exists; importing as $archiveName\n" );
1688 wfDebug( __METHOD__
. ': Bad file for ' . $this->getTitle() . "\n" );
1692 # Get the file source or download if necessary
1693 $source = $this->getFileSrc();
1694 $flags = $this->isTempSrc() ? File
::DELETE_SOURCE
: 0;
1696 $source = $this->downloadSource();
1697 $flags |
= File
::DELETE_SOURCE
;
1700 wfDebug( __METHOD__
. ": Could not fetch remote file.\n" );
1703 $sha1 = $this->getSha1();
1704 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1705 if ( $flags & File
::DELETE_SOURCE
) {
1706 # Broken file; delete it if it is a temporary file
1709 wfDebug( __METHOD__
. ": Corrupt file $source.\n" );
1713 $user = User
::newFromName( $this->user_text
);
1715 # Do the actual upload
1716 if ( $archiveName ) {
1717 $status = $file->uploadOld( $source, $archiveName,
1718 $this->getTimestamp(), $this->getComment(), $user, $flags );
1720 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1721 $flags, false, $this->getTimestamp(), $user );
1724 if ( $status->isGood() ) {
1725 wfDebug( __METHOD__
. ": Successful\n" );
1728 wfDebug( __METHOD__
. ': failed: ' . $status->getHTML() . "\n" );
1734 * @return bool|string
1736 function downloadSource() {
1737 if ( !$this->config
->get( 'EnableUploads' ) ) {
1741 $tempo = tempnam( wfTempDir(), 'download' );
1742 $f = fopen( $tempo, 'wb' );
1744 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1749 $src = $this->getSrc();
1750 $data = Http
::get( $src, array(), __METHOD__
);
1752 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1758 fwrite( $f, $data );
1767 * Source interface for XML import.
1769 interface ImportSource
{
1772 * Indicates whether the end of the input has been reached.
1773 * Will return true after a finite number of calls to readChunk.
1775 * @return bool true if there is no more input, false otherwise.
1780 * Return a chunk of the input, as a (possibly empty) string.
1781 * When the end of input is reached, readChunk() returns false.
1782 * If atEnd() returns false, readChunk() will return a string.
1783 * If atEnd() returns true, readChunk() will return false.
1785 * @return bool|string
1787 function readChunk();
1791 * Used for importing XML dumps where the content of the dump is in a string.
1792 * This class is ineffecient, and should only be used for small dumps.
1793 * For larger dumps, ImportStreamSource should be used instead.
1795 * @ingroup SpecialPage
1797 class ImportStringSource
implements ImportSource
{
1798 function __construct( $string ) {
1799 $this->mString
= $string;
1800 $this->mRead
= false;
1807 return $this->mRead
;
1811 * @return bool|string
1813 function readChunk() {
1814 if ( $this->atEnd() ) {
1817 $this->mRead
= true;
1818 return $this->mString
;
1823 * Imports a XML dump from a file (either from file upload, files on disk, or HTTP)
1824 * @ingroup SpecialPage
1826 class ImportStreamSource
implements ImportSource
{
1827 function __construct( $handle ) {
1828 $this->mHandle
= $handle;
1835 return feof( $this->mHandle
);
1841 function readChunk() {
1842 return fread( $this->mHandle
, 32768 );
1846 * @param string $filename
1849 static function newFromFile( $filename ) {
1850 wfSuppressWarnings();
1851 $file = fopen( $filename, 'rt' );
1852 wfRestoreWarnings();
1854 return Status
::newFatal( "importcantopen" );
1856 return Status
::newGood( new ImportStreamSource( $file ) );
1860 * @param string $fieldname
1863 static function newFromUpload( $fieldname = "xmlimport" ) {
1864 $upload =& $_FILES[$fieldname];
1866 if ( $upload === null ||
!$upload['name'] ) {
1867 return Status
::newFatal( 'importnofile' );
1869 if ( !empty( $upload['error'] ) ) {
1870 switch ( $upload['error'] ) {
1872 # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1873 return Status
::newFatal( 'importuploaderrorsize' );
1875 # The uploaded file exceeds the MAX_FILE_SIZE directive that
1876 # was specified in the HTML form.
1877 return Status
::newFatal( 'importuploaderrorsize' );
1879 # The uploaded file was only partially uploaded
1880 return Status
::newFatal( 'importuploaderrorpartial' );
1882 # Missing a temporary folder.
1883 return Status
::newFatal( 'importuploaderrortemp' );
1884 # case else: # Currently impossible
1888 $fname = $upload['tmp_name'];
1889 if ( is_uploaded_file( $fname ) ) {
1890 return ImportStreamSource
::newFromFile( $fname );
1892 return Status
::newFatal( 'importnofile' );
1897 * @param string $url
1898 * @param string $method
1901 static function newFromURL( $url, $method = 'GET' ) {
1902 wfDebug( __METHOD__
. ": opening $url\n" );
1903 # Use the standard HTTP fetch function; it times out
1904 # quicker and sorts out user-agent problems which might
1905 # otherwise prevent importing from large sites, such
1906 # as the Wikimedia cluster, etc.
1907 $data = Http
::request( $method, $url, array( 'followRedirects' => true ), __METHOD__
);
1908 if ( $data !== false ) {
1910 fwrite( $file, $data );
1913 return Status
::newGood( new ImportStreamSource( $file ) );
1915 return Status
::newFatal( 'importcantopen' );
1920 * @param string $interwiki
1921 * @param string $page
1922 * @param bool $history
1923 * @param bool $templates
1924 * @param int $pageLinkDepth
1927 public static function newFromInterwiki( $interwiki, $page, $history = false,
1928 $templates = false, $pageLinkDepth = 0
1930 if ( $page == '' ) {
1931 return Status
::newFatal( 'import-noarticle' );
1933 $link = Title
::newFromText( "$interwiki:Special:Export/$page" );
1934 if ( is_null( $link ) ||
!$link->isExternal() ) {
1935 return Status
::newFatal( 'importbadinterwiki' );
1939 $params['history'] = 1;
1942 $params['templates'] = 1;
1944 if ( $pageLinkDepth ) {
1945 $params['pagelink-depth'] = $pageLinkDepth;
1947 $url = $link->getFullURL( $params );
1948 # For interwikis, use POST to avoid redirects.
1949 return ImportStreamSource
::newFromURL( $url, "POST" );