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 $editInfo = $page->prepareContentForEdit( $content );
379 $countKey = 'title_' . $title->getPrefixedText();
380 $countable = $page->isCountable( $editInfo );
381 if ( array_key_exists( $countKey, $this->countableCache
) &&
382 $countable != $this->countableCache
[ $countKey ] ) {
383 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array(
384 'articles' => ( (int)$countable - (int)$this->countableCache
[ $countKey ] )
388 $args = func_get_args();
389 return Hooks
::run( 'AfterImportPage', $args );
393 * Alternate per-revision callback, for debugging.
394 * @param WikiRevision $revision
396 public function debugRevisionHandler( &$revision ) {
397 $this->debug( "Got revision:" );
398 if ( is_object( $revision->title
) ) {
399 $this->debug( "-- Title: " . $revision->title
->getPrefixedText() );
401 $this->debug( "-- Title: <invalid>" );
403 $this->debug( "-- User: " . $revision->user_text
);
404 $this->debug( "-- Timestamp: " . $revision->timestamp
);
405 $this->debug( "-- Comment: " . $revision->comment
);
406 $this->debug( "-- Text: " . $revision->text
);
410 * Notify the callback function of site info
411 * @param array $siteInfo
414 private function siteInfoCallback( $siteInfo ) {
415 if ( isset( $this->mSiteInfoCallback
) ) {
416 return call_user_func_array( $this->mSiteInfoCallback
,
417 array( $siteInfo, $this ) );
424 * Notify the callback function when a new "<page>" is reached.
425 * @param Title $title
427 function pageCallback( $title ) {
428 if ( isset( $this->mPageCallback
) ) {
429 call_user_func( $this->mPageCallback
, $title );
434 * Notify the callback function when a "</page>" is closed.
435 * @param Title $title
436 * @param ForeignTitle $foreignTitle
437 * @param int $revCount
438 * @param int $sucCount Number of revisions for which callback returned true
439 * @param array $pageInfo Associative array of page information
441 private function pageOutCallback( $title, $foreignTitle, $revCount,
442 $sucCount, $pageInfo ) {
443 if ( isset( $this->mPageOutCallback
) ) {
444 $args = func_get_args();
445 call_user_func_array( $this->mPageOutCallback
, $args );
450 * Notify the callback function of a revision
451 * @param WikiRevision $revision
454 private function revisionCallback( $revision ) {
455 if ( isset( $this->mRevisionCallback
) ) {
456 return call_user_func_array( $this->mRevisionCallback
,
457 array( $revision, $this ) );
464 * Notify the callback function of a new log item
465 * @param WikiRevision $revision
468 private function logItemCallback( $revision ) {
469 if ( isset( $this->mLogItemCallback
) ) {
470 return call_user_func_array( $this->mLogItemCallback
,
471 array( $revision, $this ) );
478 * Retrieves the contents of the named attribute of the current element.
479 * @param string $attr The name of the attribute
480 * @return string The value of the attribute or an empty string if it is not set in the current
483 public function nodeAttribute( $attr ) {
484 return $this->reader
->getAttribute( $attr );
488 * Shouldn't something like this be built-in to XMLReader?
489 * Fetches text contents of the current element, assuming
490 * no sub-elements or such scary things.
494 public function nodeContents() {
495 if ( $this->reader
->isEmptyElement
) {
499 while ( $this->reader
->read() ) {
500 switch ( $this->reader
->nodeType
) {
501 case XMLReader
::TEXT
:
502 case XMLReader
::SIGNIFICANT_WHITESPACE
:
503 $buffer .= $this->reader
->value
;
505 case XMLReader
::END_ELEMENT
:
510 $this->reader
->close();
515 * Primary entry point
516 * @throws MWException
519 public function doImport() {
520 // Calls to reader->read need to be wrapped in calls to
521 // libxml_disable_entity_loader() to avoid local file
522 // inclusion attacks (bug 46932).
523 $oldDisable = libxml_disable_entity_loader( true );
524 $this->reader
->read();
526 if ( $this->reader
->name
!= 'mediawiki' ) {
527 libxml_disable_entity_loader( $oldDisable );
528 throw new MWException( "Expected <mediawiki> tag, got " .
529 $this->reader
->name
);
531 $this->debug( "<mediawiki> tag is correct." );
533 $this->debug( "Starting primary dump processing loop." );
535 $keepReading = $this->reader
->read();
539 while ( $keepReading ) {
540 $tag = $this->reader
->name
;
541 $type = $this->reader
->nodeType
;
543 if ( !Hooks
::run( 'ImportHandleToplevelXMLTag', array( $this ) ) ) {
545 } elseif ( $tag == 'mediawiki' && $type == XMLReader
::END_ELEMENT
) {
547 } elseif ( $tag == 'siteinfo' ) {
548 $this->handleSiteInfo();
549 } elseif ( $tag == 'page' ) {
551 } elseif ( $tag == 'logitem' ) {
552 $this->handleLogItem();
553 } elseif ( $tag != '#text' ) {
554 $this->warn( "Unhandled top-level XML tag $tag" );
560 $keepReading = $this->reader
->next();
562 $this->debug( "Skip" );
564 $keepReading = $this->reader
->read();
567 } catch ( Exception
$ex ) {
572 libxml_disable_entity_loader( $oldDisable );
573 $this->reader
->close();
582 private function handleSiteInfo() {
583 $this->debug( "Enter site info handler." );
586 // Fields that can just be stuffed in the siteInfo object
587 $normalFields = array( 'sitename', 'base', 'generator', 'case' );
589 while ( $this->reader
->read() ) {
590 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
591 $this->reader
->name
== 'siteinfo' ) {
595 $tag = $this->reader
->name
;
597 if ( $tag == 'namespace' ) {
598 $this->foreignNamespaces
[ $this->nodeAttribute( 'key' ) ] =
599 $this->nodeContents();
600 } elseif ( in_array( $tag, $normalFields ) ) {
601 $siteInfo[$tag] = $this->nodeContents();
605 $siteInfo['_namespaces'] = $this->foreignNamespaces
;
606 $this->siteInfoCallback( $siteInfo );
609 private function handleLogItem() {
610 $this->debug( "Enter log item handler." );
613 // Fields that can just be stuffed in the pageInfo object
614 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
615 'logtitle', 'params' );
617 while ( $this->reader
->read() ) {
618 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
619 $this->reader
->name
== 'logitem' ) {
623 $tag = $this->reader
->name
;
625 if ( !Hooks
::run( 'ImportHandleLogItemXMLTag', array(
629 } elseif ( in_array( $tag, $normalFields ) ) {
630 $logInfo[$tag] = $this->nodeContents();
631 } elseif ( $tag == 'contributor' ) {
632 $logInfo['contributor'] = $this->handleContributor();
633 } elseif ( $tag != '#text' ) {
634 $this->warn( "Unhandled log-item XML tag $tag" );
638 $this->processLogItem( $logInfo );
642 * @param array $logInfo
645 private function processLogItem( $logInfo ) {
646 $revision = new WikiRevision( $this->config
);
648 $revision->setID( $logInfo['id'] );
649 $revision->setType( $logInfo['type'] );
650 $revision->setAction( $logInfo['action'] );
651 $revision->setTimestamp( $logInfo['timestamp'] );
652 $revision->setParams( $logInfo['params'] );
653 $revision->setTitle( Title
::newFromText( $logInfo['logtitle'] ) );
654 $revision->setNoUpdates( $this->mNoUpdates
);
656 if ( isset( $logInfo['comment'] ) ) {
657 $revision->setComment( $logInfo['comment'] );
660 if ( isset( $logInfo['contributor']['ip'] ) ) {
661 $revision->setUserIP( $logInfo['contributor']['ip'] );
663 if ( isset( $logInfo['contributor']['username'] ) ) {
664 $revision->setUserName( $logInfo['contributor']['username'] );
667 return $this->logItemCallback( $revision );
670 private function handlePage() {
672 $this->debug( "Enter page handler." );
673 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
675 // Fields that can just be stuffed in the pageInfo object
676 $normalFields = array( 'title', 'ns', 'id', 'redirect', 'restrictions' );
681 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
682 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
683 $this->reader
->name
== 'page' ) {
689 $tag = $this->reader
->name
;
692 // The title is invalid, bail out of this page
694 } elseif ( !Hooks
::run( 'ImportHandlePageXMLTag', array( $this,
697 } elseif ( in_array( $tag, $normalFields ) ) {
701 // <title>Page</title>
702 // <redirect title="NewTitle"/>
704 // Because the redirect tag is built differently, we need special handling for that case.
705 if ( $tag == 'redirect' ) {
706 $pageInfo[$tag] = $this->nodeAttribute( 'title' );
708 $pageInfo[$tag] = $this->nodeContents();
710 } elseif ( $tag == 'revision' ||
$tag == 'upload' ) {
711 if ( !isset( $title ) ) {
712 $title = $this->processTitle( $pageInfo['title'],
713 isset( $pageInfo['ns'] ) ?
$pageInfo['ns'] : null );
720 $this->pageCallback( $title );
721 list( $pageInfo['_title'], $foreignTitle ) = $title;
725 if ( $tag == 'revision' ) {
726 $this->handleRevision( $pageInfo );
728 $this->handleUpload( $pageInfo );
731 } elseif ( $tag != '#text' ) {
732 $this->warn( "Unhandled page XML tag $tag" );
737 $this->pageOutCallback( $pageInfo['_title'], $foreignTitle,
738 $pageInfo['revisionCount'],
739 $pageInfo['successfulRevisionCount'],
744 * @param array $pageInfo
746 private function handleRevision( &$pageInfo ) {
747 $this->debug( "Enter revision handler" );
748 $revisionInfo = array();
750 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'model', 'format', 'text' );
754 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
755 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
756 $this->reader
->name
== 'revision' ) {
760 $tag = $this->reader
->name
;
762 if ( !Hooks
::run( 'ImportHandleRevisionXMLTag', array(
763 $this, $pageInfo, $revisionInfo
766 } elseif ( in_array( $tag, $normalFields ) ) {
767 $revisionInfo[$tag] = $this->nodeContents();
768 } elseif ( $tag == 'contributor' ) {
769 $revisionInfo['contributor'] = $this->handleContributor();
770 } elseif ( $tag != '#text' ) {
771 $this->warn( "Unhandled revision XML tag $tag" );
776 $pageInfo['revisionCount']++
;
777 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
778 $pageInfo['successfulRevisionCount']++
;
783 * @param array $pageInfo
784 * @param array $revisionInfo
787 private function processRevision( $pageInfo, $revisionInfo ) {
788 $revision = new WikiRevision( $this->config
);
790 if ( isset( $revisionInfo['id'] ) ) {
791 $revision->setID( $revisionInfo['id'] );
793 if ( isset( $revisionInfo['model'] ) ) {
794 $revision->setModel( $revisionInfo['model'] );
796 if ( isset( $revisionInfo['format'] ) ) {
797 $revision->setFormat( $revisionInfo['format'] );
799 $revision->setTitle( $pageInfo['_title'] );
801 if ( isset( $revisionInfo['text'] ) ) {
802 $handler = $revision->getContentHandler();
803 $text = $handler->importTransform(
804 $revisionInfo['text'],
805 $revision->getFormat() );
807 $revision->setText( $text );
809 if ( isset( $revisionInfo['timestamp'] ) ) {
810 $revision->setTimestamp( $revisionInfo['timestamp'] );
812 $revision->setTimestamp( wfTimestampNow() );
815 if ( isset( $revisionInfo['comment'] ) ) {
816 $revision->setComment( $revisionInfo['comment'] );
819 if ( isset( $revisionInfo['minor'] ) ) {
820 $revision->setMinor( true );
822 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
823 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
825 if ( isset( $revisionInfo['contributor']['username'] ) ) {
826 $revision->setUserName( $revisionInfo['contributor']['username'] );
828 $revision->setNoUpdates( $this->mNoUpdates
);
830 return $this->revisionCallback( $revision );
834 * @param array $pageInfo
837 private function handleUpload( &$pageInfo ) {
838 $this->debug( "Enter upload handler" );
839 $uploadInfo = array();
841 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
842 'src', 'size', 'sha1base36', 'archivename', 'rel' );
846 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
847 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
848 $this->reader
->name
== 'upload' ) {
852 $tag = $this->reader
->name
;
854 if ( !Hooks
::run( 'ImportHandleUploadXMLTag', array(
858 } elseif ( in_array( $tag, $normalFields ) ) {
859 $uploadInfo[$tag] = $this->nodeContents();
860 } elseif ( $tag == 'contributor' ) {
861 $uploadInfo['contributor'] = $this->handleContributor();
862 } elseif ( $tag == 'contents' ) {
863 $contents = $this->nodeContents();
864 $encoding = $this->reader
->getAttribute( 'encoding' );
865 if ( $encoding === 'base64' ) {
866 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
867 $uploadInfo['isTempSrc'] = true;
869 } elseif ( $tag != '#text' ) {
870 $this->warn( "Unhandled upload XML tag $tag" );
875 if ( $this->mImageBasePath
&& isset( $uploadInfo['rel'] ) ) {
876 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
877 if ( file_exists( $path ) ) {
878 $uploadInfo['fileSrc'] = $path;
879 $uploadInfo['isTempSrc'] = false;
883 if ( $this->mImportUploads
) {
884 return $this->processUpload( $pageInfo, $uploadInfo );
889 * @param string $contents
892 private function dumpTemp( $contents ) {
893 $filename = tempnam( wfTempDir(), 'importupload' );
894 file_put_contents( $filename, $contents );
899 * @param array $pageInfo
900 * @param array $uploadInfo
903 private function processUpload( $pageInfo, $uploadInfo ) {
904 $revision = new WikiRevision( $this->config
);
905 $text = isset( $uploadInfo['text'] ) ?
$uploadInfo['text'] : '';
907 $revision->setTitle( $pageInfo['_title'] );
908 $revision->setID( $pageInfo['id'] );
909 $revision->setTimestamp( $uploadInfo['timestamp'] );
910 $revision->setText( $text );
911 $revision->setFilename( $uploadInfo['filename'] );
912 if ( isset( $uploadInfo['archivename'] ) ) {
913 $revision->setArchiveName( $uploadInfo['archivename'] );
915 $revision->setSrc( $uploadInfo['src'] );
916 if ( isset( $uploadInfo['fileSrc'] ) ) {
917 $revision->setFileSrc( $uploadInfo['fileSrc'],
918 !empty( $uploadInfo['isTempSrc'] ) );
920 if ( isset( $uploadInfo['sha1base36'] ) ) {
921 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
923 $revision->setSize( intval( $uploadInfo['size'] ) );
924 $revision->setComment( $uploadInfo['comment'] );
926 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
927 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
929 if ( isset( $uploadInfo['contributor']['username'] ) ) {
930 $revision->setUserName( $uploadInfo['contributor']['username'] );
932 $revision->setNoUpdates( $this->mNoUpdates
);
934 return call_user_func( $this->mUploadCallback
, $revision );
940 private function handleContributor() {
941 $fields = array( 'id', 'ip', 'username' );
944 while ( $this->reader
->read() ) {
945 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
946 $this->reader
->name
== 'contributor' ) {
950 $tag = $this->reader
->name
;
952 if ( in_array( $tag, $fields ) ) {
953 $info[$tag] = $this->nodeContents();
961 * @param string $text
962 * @param string|null $ns
965 private function processTitle( $text, $ns = null ) {
966 if ( is_null( $this->foreignNamespaces
) ) {
967 $foreignTitleFactory = new NaiveForeignTitleFactory();
969 $foreignTitleFactory = new NamespaceAwareForeignTitleFactory(
970 $this->foreignNamespaces
);
973 $foreignTitle = $foreignTitleFactory->createForeignTitle( $text,
976 $title = $this->importTitleFactory
->createTitleFromForeignTitle(
979 $commandLineMode = $this->config
->get( 'CommandLineMode' );
980 if ( is_null( $title ) ) {
981 # Invalid page title? Ignore the page
982 $this->notice( 'import-error-invalid', $foreignTitle->getFullText() );
984 } elseif ( $title->isExternal() ) {
985 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
987 } elseif ( !$title->canExist() ) {
988 $this->notice( 'import-error-special', $title->getPrefixedText() );
990 } elseif ( !$title->userCan( 'edit' ) && !$commandLineMode ) {
991 # Do not import if the importing wiki user cannot edit this page
992 $this->notice( 'import-error-edit', $title->getPrefixedText() );
994 } elseif ( !$title->exists() && !$title->userCan( 'create' ) && !$commandLineMode ) {
995 # Do not import if the importing wiki user cannot create this page
996 $this->notice( 'import-error-create', $title->getPrefixedText() );
1000 return array( $title, $foreignTitle );
1004 /** This is a horrible hack used to keep source compatibility */
1005 class UploadSourceAdapter
{
1007 public static $sourceRegistrations = array();
1019 * @param ImportSource $source
1022 static function registerSource( ImportSource
$source ) {
1023 $id = wfRandomString();
1025 self
::$sourceRegistrations[$id] = $source;
1031 * @param string $path
1032 * @param string $mode
1033 * @param array $options
1034 * @param string $opened_path
1037 function stream_open( $path, $mode, $options, &$opened_path ) {
1038 $url = parse_url( $path );
1041 if ( !isset( self
::$sourceRegistrations[$id] ) ) {
1045 $this->mSource
= self
::$sourceRegistrations[$id];
1054 function stream_read( $count ) {
1058 while ( !$leave && !$this->mSource
->atEnd() &&
1059 strlen( $this->mBuffer
) < $count ) {
1060 $read = $this->mSource
->readChunk();
1062 if ( !strlen( $read ) ) {
1066 $this->mBuffer
.= $read;
1069 if ( strlen( $this->mBuffer
) ) {
1070 $return = substr( $this->mBuffer
, 0, $count );
1071 $this->mBuffer
= substr( $this->mBuffer
, $count );
1074 $this->mPosition +
= strlen( $return );
1080 * @param string $data
1083 function stream_write( $data ) {
1090 function stream_tell() {
1091 return $this->mPosition
;
1097 function stream_eof() {
1098 return $this->mSource
->atEnd();
1104 function url_stat() {
1107 $result['dev'] = $result[0] = 0;
1108 $result['ino'] = $result[1] = 0;
1109 $result['mode'] = $result[2] = 0;
1110 $result['nlink'] = $result[3] = 0;
1111 $result['uid'] = $result[4] = 0;
1112 $result['gid'] = $result[5] = 0;
1113 $result['rdev'] = $result[6] = 0;
1114 $result['size'] = $result[7] = 0;
1115 $result['atime'] = $result[8] = 0;
1116 $result['mtime'] = $result[9] = 0;
1117 $result['ctime'] = $result[10] = 0;
1118 $result['blksize'] = $result[11] = 0;
1119 $result['blocks'] = $result[12] = 0;
1126 * @todo document (e.g. one-sentence class description).
1127 * @ingroup SpecialPage
1129 class WikiRevision
{
1130 /** @todo Unused? */
1131 public $importer = null;
1134 public $title = null;
1140 public $timestamp = "20010115000000";
1144 * @todo Can't find any uses. Public, because that's suspicious. Get clarity. */
1148 public $user_text = "";
1151 public $model = null;
1154 public $format = null;
1163 public $content = null;
1165 /** @var ContentHandler */
1166 protected $contentHandler = null;
1169 public $comment = "";
1172 public $minor = false;
1178 public $action = "";
1181 public $params = "";
1184 public $fileSrc = '';
1186 /** @var bool|string */
1187 public $sha1base36 = false;
1193 public $isTemp = false;
1196 public $archiveName = '';
1198 protected $filename;
1203 /** @todo Unused? */
1207 private $mNoUpdates = false;
1209 /** @var Config $config */
1212 public function __construct( Config
$config ) {
1213 $this->config
= $config;
1217 * @param Title $title
1218 * @throws MWException
1220 function setTitle( $title ) {
1221 if ( is_object( $title ) ) {
1222 $this->title
= $title;
1223 } elseif ( is_null( $title ) ) {
1224 throw new MWException( "WikiRevision given a null title in import. "
1225 . "You may need to adjust \$wgLegalTitleChars." );
1227 throw new MWException( "WikiRevision given non-object title in import." );
1234 function setID( $id ) {
1241 function setTimestamp( $ts ) {
1242 # 2003-08-05T18:30:02Z
1243 $this->timestamp
= wfTimestamp( TS_MW
, $ts );
1247 * @param string $user
1249 function setUsername( $user ) {
1250 $this->user_text
= $user;
1256 function setUserIP( $ip ) {
1257 $this->user_text
= $ip;
1261 * @param string $model
1263 function setModel( $model ) {
1264 $this->model
= $model;
1268 * @param string $format
1270 function setFormat( $format ) {
1271 $this->format
= $format;
1275 * @param string $text
1277 function setText( $text ) {
1278 $this->text
= $text;
1282 * @param string $text
1284 function setComment( $text ) {
1285 $this->comment
= $text;
1289 * @param bool $minor
1291 function setMinor( $minor ) {
1292 $this->minor
= (bool)$minor;
1298 function setSrc( $src ) {
1303 * @param string $src
1304 * @param bool $isTemp
1306 function setFileSrc( $src, $isTemp ) {
1307 $this->fileSrc
= $src;
1308 $this->fileIsTemp
= $isTemp;
1312 * @param string $sha1base36
1314 function setSha1Base36( $sha1base36 ) {
1315 $this->sha1base36
= $sha1base36;
1319 * @param string $filename
1321 function setFilename( $filename ) {
1322 $this->filename
= $filename;
1326 * @param string $archiveName
1328 function setArchiveName( $archiveName ) {
1329 $this->archiveName
= $archiveName;
1335 function setSize( $size ) {
1336 $this->size
= intval( $size );
1340 * @param string $type
1342 function setType( $type ) {
1343 $this->type
= $type;
1347 * @param string $action
1349 function setAction( $action ) {
1350 $this->action
= $action;
1354 * @param array $params
1356 function setParams( $params ) {
1357 $this->params
= $params;
1361 * @param bool $noupdates
1363 public function setNoUpdates( $noupdates ) {
1364 $this->mNoUpdates
= $noupdates;
1370 function getTitle() {
1371 return $this->title
;
1384 function getTimestamp() {
1385 return $this->timestamp
;
1391 function getUser() {
1392 return $this->user_text
;
1398 * @deprecated Since 1.21, use getContent() instead.
1400 function getText() {
1401 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1407 * @return ContentHandler
1409 function getContentHandler() {
1410 if ( is_null( $this->contentHandler
) ) {
1411 $this->contentHandler
= ContentHandler
::getForModelID( $this->getModel() );
1414 return $this->contentHandler
;
1420 function getContent() {
1421 if ( is_null( $this->content
) ) {
1422 $handler = $this->getContentHandler();
1423 $this->content
= $handler->unserializeContent( $this->text
, $this->getFormat() );
1426 return $this->content
;
1432 function getModel() {
1433 if ( is_null( $this->model
) ) {
1434 $this->model
= $this->getTitle()->getContentModel();
1437 return $this->model
;
1443 function getFormat() {
1444 if ( is_null( $this->format
) ) {
1445 $this->format
= $this->getContentHandler()->getDefaultFormat();
1448 return $this->format
;
1454 function getComment() {
1455 return $this->comment
;
1461 function getMinor() {
1462 return $this->minor
;
1473 * @return bool|string
1475 function getSha1() {
1476 if ( $this->sha1base36
) {
1477 return wfBaseConvert( $this->sha1base36
, 36, 16 );
1485 function getFileSrc() {
1486 return $this->fileSrc
;
1492 function isTempSrc() {
1493 return $this->isTemp
;
1499 function getFilename() {
1500 return $this->filename
;
1506 function getArchiveName() {
1507 return $this->archiveName
;
1513 function getSize() {
1520 function getType() {
1527 function getAction() {
1528 return $this->action
;
1534 function getParams() {
1535 return $this->params
;
1541 function importOldRevision() {
1542 $dbw = wfGetDB( DB_MASTER
);
1544 # Sneak a single revision into place
1545 $user = User
::newFromName( $this->getUser() );
1547 $userId = intval( $user->getId() );
1548 $userText = $user->getName();
1552 $userText = $this->getUser();
1553 $userObj = new User
;
1556 // avoid memory leak...?
1557 $linkCache = LinkCache
::singleton();
1558 $linkCache->clear();
1560 $page = WikiPage
::factory( $this->title
);
1561 $page->loadPageData( 'fromdbmaster' );
1562 if ( !$page->exists() ) {
1563 # must create the page...
1564 $pageId = $page->insertOn( $dbw );
1566 $oldcountable = null;
1568 $pageId = $page->getId();
1571 $prior = $dbw->selectField( 'revision', '1',
1572 array( 'rev_page' => $pageId,
1573 'rev_timestamp' => $dbw->timestamp( $this->timestamp
),
1574 'rev_user_text' => $userText,
1575 'rev_comment' => $this->getComment() ),
1579 // @todo FIXME: This could fail slightly for multiple matches :P
1580 wfDebug( __METHOD__
. ": skipping existing revision for [[" .
1581 $this->title
->getPrefixedText() . "]], timestamp " . $this->timestamp
. "\n" );
1586 # @todo FIXME: Use original rev_id optionally (better for backups)
1588 $revision = new Revision( array(
1589 'title' => $this->title
,
1591 'content_model' => $this->getModel(),
1592 'content_format' => $this->getFormat(),
1593 //XXX: just set 'content' => $this->getContent()?
1594 'text' => $this->getContent()->serialize( $this->getFormat() ),
1595 'comment' => $this->getComment(),
1597 'user_text' => $userText,
1598 'timestamp' => $this->timestamp
,
1599 'minor_edit' => $this->minor
,
1601 $revision->insertOn( $dbw );
1602 $changed = $page->updateIfNewerOn( $dbw, $revision );
1604 if ( $changed !== false && !$this->mNoUpdates
) {
1605 wfDebug( __METHOD__
. ": running updates\n" );
1606 // countable/oldcountable stuff is handled in WikiImporter::finishImportPage
1607 $page->doEditUpdates(
1610 array( 'created' => $created, 'oldcountable' => 'no-change' )
1617 function importLogItem() {
1618 $dbw = wfGetDB( DB_MASTER
);
1619 # @todo FIXME: This will not record autoblocks
1620 if ( !$this->getTitle() ) {
1621 wfDebug( __METHOD__
. ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1622 $this->timestamp
. "\n" );
1625 # Check if it exists already
1626 // @todo FIXME: Use original log ID (better for backups)
1627 $prior = $dbw->selectField( 'logging', '1',
1628 array( 'log_type' => $this->getType(),
1629 'log_action' => $this->getAction(),
1630 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1631 'log_namespace' => $this->getTitle()->getNamespace(),
1632 'log_title' => $this->getTitle()->getDBkey(),
1633 'log_comment' => $this->getComment(),
1634 #'log_user_text' => $this->user_text,
1635 'log_params' => $this->params
),
1638 // @todo FIXME: This could fail slightly for multiple matches :P
1641 . ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp "
1642 . $this->timestamp
. "\n" );
1645 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1647 'log_id' => $log_id,
1648 'log_type' => $this->type
,
1649 'log_action' => $this->action
,
1650 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1651 'log_user' => User
::idFromName( $this->user_text
),
1652 #'log_user_text' => $this->user_text,
1653 'log_namespace' => $this->getTitle()->getNamespace(),
1654 'log_title' => $this->getTitle()->getDBkey(),
1655 'log_comment' => $this->getComment(),
1656 'log_params' => $this->params
1658 $dbw->insert( 'logging', $data, __METHOD__
);
1664 function importUpload() {
1666 $archiveName = $this->getArchiveName();
1667 if ( $archiveName ) {
1668 wfDebug( __METHOD__
. "Importing archived file as $archiveName\n" );
1669 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1670 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1672 $file = wfLocalFile( $this->getTitle() );
1673 wfDebug( __METHOD__
. 'Importing new file as ' . $file->getName() . "\n" );
1674 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1675 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1676 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1677 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1678 wfDebug( __METHOD__
. "File already exists; importing as $archiveName\n" );
1682 wfDebug( __METHOD__
. ': Bad file for ' . $this->getTitle() . "\n" );
1686 # Get the file source or download if necessary
1687 $source = $this->getFileSrc();
1688 $flags = $this->isTempSrc() ? File
::DELETE_SOURCE
: 0;
1690 $source = $this->downloadSource();
1691 $flags |
= File
::DELETE_SOURCE
;
1694 wfDebug( __METHOD__
. ": Could not fetch remote file.\n" );
1697 $sha1 = $this->getSha1();
1698 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1699 if ( $flags & File
::DELETE_SOURCE
) {
1700 # Broken file; delete it if it is a temporary file
1703 wfDebug( __METHOD__
. ": Corrupt file $source.\n" );
1707 $user = User
::newFromName( $this->user_text
);
1709 # Do the actual upload
1710 if ( $archiveName ) {
1711 $status = $file->uploadOld( $source, $archiveName,
1712 $this->getTimestamp(), $this->getComment(), $user, $flags );
1714 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1715 $flags, false, $this->getTimestamp(), $user );
1718 if ( $status->isGood() ) {
1719 wfDebug( __METHOD__
. ": Successful\n" );
1722 wfDebug( __METHOD__
. ': failed: ' . $status->getHTML() . "\n" );
1728 * @return bool|string
1730 function downloadSource() {
1731 if ( !$this->config
->get( 'EnableUploads' ) ) {
1735 $tempo = tempnam( wfTempDir(), 'download' );
1736 $f = fopen( $tempo, 'wb' );
1738 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1743 $src = $this->getSrc();
1744 $data = Http
::get( $src, array(), __METHOD__
);
1746 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1752 fwrite( $f, $data );
1761 * Source interface for XML import.
1763 interface ImportSource
{
1766 * Indicates whether the end of the input has been reached.
1767 * Will return true after a finite number of calls to readChunk.
1769 * @return bool true if there is no more input, false otherwise.
1774 * Return a chunk of the input, as a (possibly empty) string.
1775 * When the end of input is reached, readChunk() returns false.
1776 * If atEnd() returns false, readChunk() will return a string.
1777 * If atEnd() returns true, readChunk() will return false.
1779 * @return bool|string
1781 function readChunk();
1785 * Used for importing XML dumps where the content of the dump is in a string.
1786 * This class is ineffecient, and should only be used for small dumps.
1787 * For larger dumps, ImportStreamSource should be used instead.
1789 * @ingroup SpecialPage
1791 class ImportStringSource
implements ImportSource
{
1792 function __construct( $string ) {
1793 $this->mString
= $string;
1794 $this->mRead
= false;
1801 return $this->mRead
;
1805 * @return bool|string
1807 function readChunk() {
1808 if ( $this->atEnd() ) {
1811 $this->mRead
= true;
1812 return $this->mString
;
1817 * Imports a XML dump from a file (either from file upload, files on disk, or HTTP)
1818 * @ingroup SpecialPage
1820 class ImportStreamSource
implements ImportSource
{
1821 function __construct( $handle ) {
1822 $this->mHandle
= $handle;
1829 return feof( $this->mHandle
);
1835 function readChunk() {
1836 return fread( $this->mHandle
, 32768 );
1840 * @param string $filename
1843 static function newFromFile( $filename ) {
1844 wfSuppressWarnings();
1845 $file = fopen( $filename, 'rt' );
1846 wfRestoreWarnings();
1848 return Status
::newFatal( "importcantopen" );
1850 return Status
::newGood( new ImportStreamSource( $file ) );
1854 * @param string $fieldname
1857 static function newFromUpload( $fieldname = "xmlimport" ) {
1858 $upload =& $_FILES[$fieldname];
1860 if ( $upload === null ||
!$upload['name'] ) {
1861 return Status
::newFatal( 'importnofile' );
1863 if ( !empty( $upload['error'] ) ) {
1864 switch ( $upload['error'] ) {
1866 # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1867 return Status
::newFatal( 'importuploaderrorsize' );
1869 # The uploaded file exceeds the MAX_FILE_SIZE directive that
1870 # was specified in the HTML form.
1871 return Status
::newFatal( 'importuploaderrorsize' );
1873 # The uploaded file was only partially uploaded
1874 return Status
::newFatal( 'importuploaderrorpartial' );
1876 # Missing a temporary folder.
1877 return Status
::newFatal( 'importuploaderrortemp' );
1878 # case else: # Currently impossible
1882 $fname = $upload['tmp_name'];
1883 if ( is_uploaded_file( $fname ) ) {
1884 return ImportStreamSource
::newFromFile( $fname );
1886 return Status
::newFatal( 'importnofile' );
1891 * @param string $url
1892 * @param string $method
1895 static function newFromURL( $url, $method = 'GET' ) {
1896 wfDebug( __METHOD__
. ": opening $url\n" );
1897 # Use the standard HTTP fetch function; it times out
1898 # quicker and sorts out user-agent problems which might
1899 # otherwise prevent importing from large sites, such
1900 # as the Wikimedia cluster, etc.
1901 $data = Http
::request( $method, $url, array( 'followRedirects' => true ), __METHOD__
);
1902 if ( $data !== false ) {
1904 fwrite( $file, $data );
1907 return Status
::newGood( new ImportStreamSource( $file ) );
1909 return Status
::newFatal( 'importcantopen' );
1914 * @param string $interwiki
1915 * @param string $page
1916 * @param bool $history
1917 * @param bool $templates
1918 * @param int $pageLinkDepth
1921 public static function newFromInterwiki( $interwiki, $page, $history = false,
1922 $templates = false, $pageLinkDepth = 0
1924 if ( $page == '' ) {
1925 return Status
::newFatal( 'import-noarticle' );
1927 $link = Title
::newFromText( "$interwiki:Special:Export/$page" );
1928 if ( is_null( $link ) ||
!$link->isExternal() ) {
1929 return Status
::newFatal( 'importbadinterwiki' );
1933 $params['history'] = 1;
1936 $params['templates'] = 1;
1938 if ( $pageLinkDepth ) {
1939 $params['pagelink-depth'] = $pageLinkDepth;
1941 $url = $link->getFullURL( $params );
1942 # For interwikis, use POST to avoid redirects.
1943 return ImportStreamSource
::newFromURL( $url, "POST" );