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 $mLogItemCallback, $mUploadCallback, $mRevisionCallback, $mPageCallback;
36 private $mSiteInfoCallback, $mTargetNamespace, $mTargetRootPage, $mPageOutCallback;
37 private $mNoticeCallback, $mDebug;
38 private $mImportUploads, $mImageBasePath;
39 private $mNoUpdates = false;
42 * Creates an ImportXMLReader drawing from the source provided
43 * @param string $source
45 function __construct( $source ) {
46 $this->reader
= new XMLReader();
48 stream_wrapper_register( 'uploadsource', 'UploadSourceAdapter' );
49 $id = UploadSourceAdapter
::registerSource( $source );
50 if ( defined( 'LIBXML_PARSEHUGE' ) ) {
51 $this->reader
->open( "uploadsource://$id", null, LIBXML_PARSEHUGE
);
53 $this->reader
->open( "uploadsource://$id" );
57 $this->setRevisionCallback( array( $this, "importRevision" ) );
58 $this->setUploadCallback( array( $this, 'importUpload' ) );
59 $this->setLogItemCallback( array( $this, 'importLogItem' ) );
60 $this->setPageOutCallback( array( $this, 'finishImportPage' ) );
64 * @return null|XMLReader
66 public function getReader() {
70 public function throwXmlError( $err ) {
71 $this->debug( "FAILURE: $err" );
72 wfDebug( "WikiImporter XML error: $err\n" );
75 public function debug( $data ) {
76 if ( $this->mDebug
) {
77 wfDebug( "IMPORT: $data\n" );
81 public function warn( $data ) {
82 wfDebug( "IMPORT: $data\n" );
85 public function notice( $msg /*, $param, ...*/ ) {
86 $params = func_get_args();
87 array_shift( $params );
89 if ( is_callable( $this->mNoticeCallback
) ) {
90 call_user_func( $this->mNoticeCallback
, $msg, $params );
91 } else { # No ImportReporter -> CLI
92 echo wfMessage( $msg, $params )->text() . "\n";
100 function setDebug( $debug ) {
101 $this->mDebug
= $debug;
105 * Set 'no updates' mode. In this mode, the link tables will not be updated by the importer
106 * @param bool $noupdates
108 function setNoUpdates( $noupdates ) {
109 $this->mNoUpdates
= $noupdates;
113 * Set a callback that displays notice messages
115 * @param callable $callback
118 public function setNoticeCallback( $callback ) {
119 return wfSetVar( $this->mNoticeCallback
, $callback );
123 * Sets the action to perform as each new page in the stream is reached.
124 * @param callable $callback
127 public function setPageCallback( $callback ) {
128 $previous = $this->mPageCallback
;
129 $this->mPageCallback
= $callback;
134 * Sets the action to perform as each page in the stream is completed.
135 * Callback accepts the page title (as a Title object), a second object
136 * with the original title form (in case it's been overridden into a
137 * local namespace), and a count of revisions.
139 * @param callable $callback
142 public function setPageOutCallback( $callback ) {
143 $previous = $this->mPageOutCallback
;
144 $this->mPageOutCallback
= $callback;
149 * Sets the action to perform as each page revision is reached.
150 * @param callable $callback
153 public function setRevisionCallback( $callback ) {
154 $previous = $this->mRevisionCallback
;
155 $this->mRevisionCallback
= $callback;
160 * Sets the action to perform as each file upload version is reached.
161 * @param callable $callback
164 public function setUploadCallback( $callback ) {
165 $previous = $this->mUploadCallback
;
166 $this->mUploadCallback
= $callback;
171 * Sets the action to perform as each log item reached.
172 * @param callable $callback
175 public function setLogItemCallback( $callback ) {
176 $previous = $this->mLogItemCallback
;
177 $this->mLogItemCallback
= $callback;
182 * Sets the action to perform when site info is encountered
183 * @param callable $callback
186 public function setSiteInfoCallback( $callback ) {
187 $previous = $this->mSiteInfoCallback
;
188 $this->mSiteInfoCallback
= $callback;
193 * Set a target namespace to override the defaults
194 * @param null|int $namespace
197 public function setTargetNamespace( $namespace ) {
198 if ( is_null( $namespace ) ) {
199 // Don't override namespaces
200 $this->mTargetNamespace
= null;
201 } elseif ( $namespace >= 0 ) {
202 // @todo FIXME: Check for validity
203 $this->mTargetNamespace
= intval( $namespace );
210 * Set a target root page under which all pages are imported
211 * @param null|string $rootpage
214 public function setTargetRootPage( $rootpage ) {
215 $status = Status
::newGood();
216 if ( is_null( $rootpage ) ) {
218 $this->mTargetRootPage
= null;
219 } elseif ( $rootpage !== '' ) {
220 $rootpage = rtrim( $rootpage, '/' ); //avoid double slashes
221 $title = Title
::newFromText( $rootpage, !is_null( $this->mTargetNamespace
)
222 ?
$this->mTargetNamespace
226 if ( !$title ||
$title->isExternal() ) {
227 $status->fatal( 'import-rootpage-invalid' );
229 if ( !MWNamespace
::hasSubpages( $title->getNamespace() ) ) {
232 $displayNSText = $title->getNamespace() == NS_MAIN
233 ?
wfMessage( 'blanknamespace' )->text()
234 : $wgContLang->getNsText( $title->getNamespace() );
235 $status->fatal( 'import-rootpage-nosubpage', $displayNSText );
237 // set namespace to 'all', so the namespace check in processTitle() can passed
238 $this->setTargetNamespace( null );
239 $this->mTargetRootPage
= $title->getPrefixedDBkey();
249 public function setImageBasePath( $dir ) {
250 $this->mImageBasePath
= $dir;
254 * @param bool $import
256 public function setImportUploads( $import ) {
257 $this->mImportUploads
= $import;
261 * Default per-revision callback, performs the import.
262 * @param WikiRevision $revision
265 public function importRevision( $revision ) {
266 if ( !$revision->getContent()->getContentHandler()->canBeUsedOn( $revision->getTitle() ) ) {
267 $this->notice( 'import-error-bad-location',
268 $revision->getTitle()->getPrefixedText(),
270 $revision->getModel(),
271 $revision->getFormat() );
277 $dbw = wfGetDB( DB_MASTER
);
278 return $dbw->deadlockLoop( array( $revision, 'importOldRevision' ) );
279 } catch ( MWContentSerializationException
$ex ) {
280 $this->notice( 'import-error-unserialize',
281 $revision->getTitle()->getPrefixedText(),
283 $revision->getModel(),
284 $revision->getFormat() );
291 * Default per-revision callback, performs the import.
292 * @param WikiRevision $revision
295 public function importLogItem( $revision ) {
296 $dbw = wfGetDB( DB_MASTER
);
297 return $dbw->deadlockLoop( array( $revision, 'importLogItem' ) );
302 * @param WikiRevision $revision
305 public function importUpload( $revision ) {
306 $dbw = wfGetDB( DB_MASTER
);
307 return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
311 * Mostly for hook use
312 * @param Title $title
313 * @param string $origTitle
314 * @param int $revCount
315 * @param int $sRevCount
316 * @param array $pageInfo
319 public function finishImportPage( $title, $origTitle, $revCount, $sRevCount, $pageInfo ) {
320 $args = func_get_args();
321 return wfRunHooks( 'AfterImportPage', $args );
325 * Alternate per-revision callback, for debugging.
326 * @param WikiRevision $revision
328 public function debugRevisionHandler( &$revision ) {
329 $this->debug( "Got revision:" );
330 if ( is_object( $revision->title
) ) {
331 $this->debug( "-- Title: " . $revision->title
->getPrefixedText() );
333 $this->debug( "-- Title: <invalid>" );
335 $this->debug( "-- User: " . $revision->user_text
);
336 $this->debug( "-- Timestamp: " . $revision->timestamp
);
337 $this->debug( "-- Comment: " . $revision->comment
);
338 $this->debug( "-- Text: " . $revision->text
);
342 * Notify the callback function when a new "<page>" is reached.
343 * @param Title $title
345 function pageCallback( $title ) {
346 if ( isset( $this->mPageCallback
) ) {
347 call_user_func( $this->mPageCallback
, $title );
352 * Notify the callback function when a "</page>" is closed.
353 * @param Title $title
354 * @param Title $origTitle
355 * @param int $revCount
356 * @param int $sucCount Number of revisions for which callback returned true
357 * @param array $pageInfo Associative array of page information
359 private function pageOutCallback( $title, $origTitle, $revCount, $sucCount, $pageInfo ) {
360 if ( isset( $this->mPageOutCallback
) ) {
361 $args = func_get_args();
362 call_user_func_array( $this->mPageOutCallback
, $args );
367 * Notify the callback function of a revision
368 * @param WikiRevision $revision
371 private function revisionCallback( $revision ) {
372 if ( isset( $this->mRevisionCallback
) ) {
373 return call_user_func_array( $this->mRevisionCallback
,
374 array( $revision, $this ) );
381 * Notify the callback function of a new log item
382 * @param WikiRevision $revision
385 private function logItemCallback( $revision ) {
386 if ( isset( $this->mLogItemCallback
) ) {
387 return call_user_func_array( $this->mLogItemCallback
,
388 array( $revision, $this ) );
395 * Shouldn't something like this be built-in to XMLReader?
396 * Fetches text contents of the current element, assuming
397 * no sub-elements or such scary things.
401 public function nodeContents() {
402 if ( $this->reader
->isEmptyElement
) {
406 while ( $this->reader
->read() ) {
407 switch ( $this->reader
->nodeType
) {
408 case XmlReader
::TEXT
:
409 case XmlReader
::SIGNIFICANT_WHITESPACE
:
410 $buffer .= $this->reader
->value
;
412 case XmlReader
::END_ELEMENT
:
417 $this->reader
->close();
423 /** Left in for debugging */
424 private function dumpElement() {
425 static $lookup = null;
427 $xmlReaderConstants = array(
442 "SIGNIFICANT_WHITESPACE",
449 foreach ( $xmlReaderConstants as $name ) {
450 $lookup[constant( "XmlReader::$name" )] = $name;
455 $lookup[$this->reader
->nodeType
],
462 * Primary entry point
463 * @throws MWException
466 public function doImport() {
468 // Calls to reader->read need to be wrapped in calls to
469 // libxml_disable_entity_loader() to avoid local file
470 // inclusion attacks (bug 46932).
471 $oldDisable = libxml_disable_entity_loader( true );
472 $this->reader
->read();
474 if ( $this->reader
->name
!= 'mediawiki' ) {
475 libxml_disable_entity_loader( $oldDisable );
476 throw new MWException( "Expected <mediawiki> tag, got " .
477 $this->reader
->name
);
479 $this->debug( "<mediawiki> tag is correct." );
481 $this->debug( "Starting primary dump processing loop." );
483 $keepReading = $this->reader
->read();
485 while ( $keepReading ) {
486 $tag = $this->reader
->name
;
487 $type = $this->reader
->nodeType
;
489 if ( !wfRunHooks( 'ImportHandleToplevelXMLTag', array( $this ) ) ) {
491 } elseif ( $tag == 'mediawiki' && $type == XmlReader
::END_ELEMENT
) {
493 } elseif ( $tag == 'siteinfo' ) {
494 $this->handleSiteInfo();
495 } elseif ( $tag == 'page' ) {
497 } elseif ( $tag == 'logitem' ) {
498 $this->handleLogItem();
499 } elseif ( $tag != '#text' ) {
500 $this->warn( "Unhandled top-level XML tag $tag" );
506 $keepReading = $this->reader
->next();
508 $this->debug( "Skip" );
510 $keepReading = $this->reader
->read();
514 libxml_disable_entity_loader( $oldDisable );
520 * @throws MWException
522 private function handleSiteInfo() {
523 // Site info is useful, but not actually used for dump imports.
524 // Includes a quick short-circuit to save performance.
525 if ( ! $this->mSiteInfoCallback
) {
526 $this->reader
->next();
529 throw new MWException( "SiteInfo tag is not yet handled, do not set mSiteInfoCallback" );
532 private function handleLogItem() {
533 $this->debug( "Enter log item handler." );
536 // Fields that can just be stuffed in the pageInfo object
537 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
538 'logtitle', 'params' );
540 while ( $this->reader
->read() ) {
541 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
542 $this->reader
->name
== 'logitem' ) {
546 $tag = $this->reader
->name
;
548 if ( !wfRunHooks( 'ImportHandleLogItemXMLTag', array(
552 } elseif ( in_array( $tag, $normalFields ) ) {
553 $logInfo[$tag] = $this->nodeContents();
554 } elseif ( $tag == 'contributor' ) {
555 $logInfo['contributor'] = $this->handleContributor();
556 } elseif ( $tag != '#text' ) {
557 $this->warn( "Unhandled log-item XML tag $tag" );
561 $this->processLogItem( $logInfo );
565 * @param array $logInfo
568 private function processLogItem( $logInfo ) {
569 $revision = new WikiRevision
;
571 $revision->setID( $logInfo['id'] );
572 $revision->setType( $logInfo['type'] );
573 $revision->setAction( $logInfo['action'] );
574 $revision->setTimestamp( $logInfo['timestamp'] );
575 $revision->setParams( $logInfo['params'] );
576 $revision->setTitle( Title
::newFromText( $logInfo['logtitle'] ) );
577 $revision->setNoUpdates( $this->mNoUpdates
);
579 if ( isset( $logInfo['comment'] ) ) {
580 $revision->setComment( $logInfo['comment'] );
583 if ( isset( $logInfo['contributor']['ip'] ) ) {
584 $revision->setUserIP( $logInfo['contributor']['ip'] );
586 if ( isset( $logInfo['contributor']['username'] ) ) {
587 $revision->setUserName( $logInfo['contributor']['username'] );
590 return $this->logItemCallback( $revision );
593 private function handlePage() {
595 $this->debug( "Enter page handler." );
596 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
598 // Fields that can just be stuffed in the pageInfo object
599 $normalFields = array( 'title', 'id', 'redirect', 'restrictions' );
604 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
605 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
606 $this->reader
->name
== 'page' ) {
610 $tag = $this->reader
->name
;
613 // The title is invalid, bail out of this page
615 } elseif ( !wfRunHooks( 'ImportHandlePageXMLTag', array( $this,
618 } elseif ( in_array( $tag, $normalFields ) ) {
619 $pageInfo[$tag] = $this->nodeContents();
620 if ( $tag == 'title' ) {
621 $title = $this->processTitle( $pageInfo['title'] );
628 $this->pageCallback( $title );
629 list( $pageInfo['_title'], $origTitle ) = $title;
631 } elseif ( $tag == 'revision' ) {
632 $this->handleRevision( $pageInfo );
633 } elseif ( $tag == 'upload' ) {
634 $this->handleUpload( $pageInfo );
635 } elseif ( $tag != '#text' ) {
636 $this->warn( "Unhandled page XML tag $tag" );
641 $this->pageOutCallback( $pageInfo['_title'], $origTitle,
642 $pageInfo['revisionCount'],
643 $pageInfo['successfulRevisionCount'],
648 * @param array $pageInfo
650 private function handleRevision( &$pageInfo ) {
651 $this->debug( "Enter revision handler" );
652 $revisionInfo = array();
654 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'model', 'format', 'text' );
658 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
659 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
660 $this->reader
->name
== 'revision' ) {
664 $tag = $this->reader
->name
;
666 if ( !wfRunHooks( 'ImportHandleRevisionXMLTag', array(
667 $this, $pageInfo, $revisionInfo
670 } elseif ( in_array( $tag, $normalFields ) ) {
671 $revisionInfo[$tag] = $this->nodeContents();
672 } elseif ( $tag == 'contributor' ) {
673 $revisionInfo['contributor'] = $this->handleContributor();
674 } elseif ( $tag != '#text' ) {
675 $this->warn( "Unhandled revision XML tag $tag" );
680 $pageInfo['revisionCount']++
;
681 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
682 $pageInfo['successfulRevisionCount']++
;
687 * @param array $pageInfo
688 * @param array $revisionInfo
691 private function processRevision( $pageInfo, $revisionInfo ) {
692 $revision = new WikiRevision
;
694 if ( isset( $revisionInfo['id'] ) ) {
695 $revision->setID( $revisionInfo['id'] );
697 if ( isset( $revisionInfo['text'] ) ) {
698 $revision->setText( $revisionInfo['text'] );
700 if ( isset( $revisionInfo['model'] ) ) {
701 $revision->setModel( $revisionInfo['model'] );
703 if ( isset( $revisionInfo['format'] ) ) {
704 $revision->setFormat( $revisionInfo['format'] );
706 $revision->setTitle( $pageInfo['_title'] );
708 if ( isset( $revisionInfo['timestamp'] ) ) {
709 $revision->setTimestamp( $revisionInfo['timestamp'] );
711 $revision->setTimestamp( wfTimestampNow() );
714 if ( isset( $revisionInfo['comment'] ) ) {
715 $revision->setComment( $revisionInfo['comment'] );
718 if ( isset( $revisionInfo['minor'] ) ) {
719 $revision->setMinor( true );
721 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
722 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
724 if ( isset( $revisionInfo['contributor']['username'] ) ) {
725 $revision->setUserName( $revisionInfo['contributor']['username'] );
727 $revision->setNoUpdates( $this->mNoUpdates
);
729 return $this->revisionCallback( $revision );
733 * @param array $pageInfo
736 private function handleUpload( &$pageInfo ) {
737 $this->debug( "Enter upload handler" );
738 $uploadInfo = array();
740 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
741 'src', 'size', 'sha1base36', 'archivename', 'rel' );
745 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
746 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
747 $this->reader
->name
== 'upload' ) {
751 $tag = $this->reader
->name
;
753 if ( !wfRunHooks( 'ImportHandleUploadXMLTag', array(
757 } elseif ( in_array( $tag, $normalFields ) ) {
758 $uploadInfo[$tag] = $this->nodeContents();
759 } elseif ( $tag == 'contributor' ) {
760 $uploadInfo['contributor'] = $this->handleContributor();
761 } elseif ( $tag == 'contents' ) {
762 $contents = $this->nodeContents();
763 $encoding = $this->reader
->getAttribute( 'encoding' );
764 if ( $encoding === 'base64' ) {
765 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
766 $uploadInfo['isTempSrc'] = true;
768 } elseif ( $tag != '#text' ) {
769 $this->warn( "Unhandled upload XML tag $tag" );
774 if ( $this->mImageBasePath
&& isset( $uploadInfo['rel'] ) ) {
775 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
776 if ( file_exists( $path ) ) {
777 $uploadInfo['fileSrc'] = $path;
778 $uploadInfo['isTempSrc'] = false;
782 if ( $this->mImportUploads
) {
783 return $this->processUpload( $pageInfo, $uploadInfo );
788 * @param string $contents
791 private function dumpTemp( $contents ) {
792 $filename = tempnam( wfTempDir(), 'importupload' );
793 file_put_contents( $filename, $contents );
798 * @param array $pageInfo
799 * @param array $uploadInfo
802 private function processUpload( $pageInfo, $uploadInfo ) {
803 $revision = new WikiRevision
;
804 $text = isset( $uploadInfo['text'] ) ?
$uploadInfo['text'] : '';
806 $revision->setTitle( $pageInfo['_title'] );
807 $revision->setID( $pageInfo['id'] );
808 $revision->setTimestamp( $uploadInfo['timestamp'] );
809 $revision->setText( $text );
810 $revision->setFilename( $uploadInfo['filename'] );
811 if ( isset( $uploadInfo['archivename'] ) ) {
812 $revision->setArchiveName( $uploadInfo['archivename'] );
814 $revision->setSrc( $uploadInfo['src'] );
815 if ( isset( $uploadInfo['fileSrc'] ) ) {
816 $revision->setFileSrc( $uploadInfo['fileSrc'],
817 !empty( $uploadInfo['isTempSrc'] ) );
819 if ( isset( $uploadInfo['sha1base36'] ) ) {
820 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
822 $revision->setSize( intval( $uploadInfo['size'] ) );
823 $revision->setComment( $uploadInfo['comment'] );
825 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
826 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
828 if ( isset( $uploadInfo['contributor']['username'] ) ) {
829 $revision->setUserName( $uploadInfo['contributor']['username'] );
831 $revision->setNoUpdates( $this->mNoUpdates
);
833 return call_user_func( $this->mUploadCallback
, $revision );
839 private function handleContributor() {
840 $fields = array( 'id', 'ip', 'username' );
843 while ( $this->reader
->read() ) {
844 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
845 $this->reader
->name
== 'contributor' ) {
849 $tag = $this->reader
->name
;
851 if ( in_array( $tag, $fields ) ) {
852 $info[$tag] = $this->nodeContents();
860 * @param string $text
863 private function processTitle( $text ) {
864 global $wgCommandLineMode;
867 $origTitle = Title
::newFromText( $workTitle );
869 if ( !is_null( $this->mTargetNamespace
) && !is_null( $origTitle ) ) {
870 # makeTitleSafe, because $origTitle can have a interwiki (different setting of interwiki map)
871 # and than dbKey can begin with a lowercase char
872 $title = Title
::makeTitleSafe( $this->mTargetNamespace
,
873 $origTitle->getDBkey() );
875 if ( !is_null( $this->mTargetRootPage
) ) {
876 $workTitle = $this->mTargetRootPage
. '/' . $workTitle;
878 $title = Title
::newFromText( $workTitle );
881 if ( is_null( $title ) ) {
882 # Invalid page title? Ignore the page
883 $this->notice( 'import-error-invalid', $workTitle );
885 } elseif ( $title->isExternal() ) {
886 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
888 } elseif ( !$title->canExist() ) {
889 $this->notice( 'import-error-special', $title->getPrefixedText() );
891 } elseif ( !$title->userCan( 'edit' ) && !$wgCommandLineMode ) {
892 # Do not import if the importing wiki user cannot edit this page
893 $this->notice( 'import-error-edit', $title->getPrefixedText() );
895 } elseif ( !$title->exists() && !$title->userCan( 'create' ) && !$wgCommandLineMode ) {
896 # Do not import if the importing wiki user cannot create this page
897 $this->notice( 'import-error-create', $title->getPrefixedText() );
901 return array( $title, $origTitle );
905 /** This is a horrible hack used to keep source compatibility */
906 class UploadSourceAdapter
{
908 private static $sourceRegistrations = array();
920 * @param string $source
923 static function registerSource( $source ) {
924 $id = wfRandomString();
926 self
::$sourceRegistrations[$id] = $source;
932 * @param string $path
933 * @param string $mode
934 * @param array $options
935 * @param string $opened_path
938 function stream_open( $path, $mode, $options, &$opened_path ) {
939 $url = parse_url( $path );
942 if ( !isset( self
::$sourceRegistrations[$id] ) ) {
946 $this->mSource
= self
::$sourceRegistrations[$id];
955 function stream_read( $count ) {
959 while ( !$leave && !$this->mSource
->atEnd() &&
960 strlen( $this->mBuffer
) < $count ) {
961 $read = $this->mSource
->readChunk();
963 if ( !strlen( $read ) ) {
967 $this->mBuffer
.= $read;
970 if ( strlen( $this->mBuffer
) ) {
971 $return = substr( $this->mBuffer
, 0, $count );
972 $this->mBuffer
= substr( $this->mBuffer
, $count );
975 $this->mPosition +
= strlen( $return );
981 * @param string $data
984 function stream_write( $data ) {
991 function stream_tell() {
992 return $this->mPosition
;
998 function stream_eof() {
999 return $this->mSource
->atEnd();
1005 function url_stat() {
1008 $result['dev'] = $result[0] = 0;
1009 $result['ino'] = $result[1] = 0;
1010 $result['mode'] = $result[2] = 0;
1011 $result['nlink'] = $result[3] = 0;
1012 $result['uid'] = $result[4] = 0;
1013 $result['gid'] = $result[5] = 0;
1014 $result['rdev'] = $result[6] = 0;
1015 $result['size'] = $result[7] = 0;
1016 $result['atime'] = $result[8] = 0;
1017 $result['mtime'] = $result[9] = 0;
1018 $result['ctime'] = $result[10] = 0;
1019 $result['blksize'] = $result[11] = 0;
1020 $result['blocks'] = $result[12] = 0;
1026 class XMLReader2
extends XMLReader
{
1029 * @return bool|string
1031 function nodeContents() {
1032 if ( $this->isEmptyElement
) {
1036 while ( $this->read() ) {
1037 switch ( $this->nodeType
) {
1038 case XmlReader
::TEXT
:
1039 case XmlReader
::SIGNIFICANT_WHITESPACE
:
1040 $buffer .= $this->value
;
1042 case XmlReader
::END_ELEMENT
:
1046 return $this->close();
1051 * @todo document (e.g. one-sentence class description).
1052 * @ingroup SpecialPage
1054 class WikiRevision
{
1055 /** @todo Unused? */
1056 private $importer = null;
1059 public $title = null;
1065 public $timestamp = "20010115000000";
1069 * @todo Can't find any uses. Public, because that's suspicious. Get clarity. */
1073 public $user_text = "";
1076 protected $model = null;
1079 protected $format = null;
1088 protected $content = null;
1091 public $comment = "";
1094 protected $minor = false;
1097 protected $type = "";
1100 protected $action = "";
1103 protected $params = "";
1106 protected $fileSrc = '';
1108 /** @var bool|string */
1109 protected $sha1base36 = false;
1115 private $isTemp = false;
1118 protected $archiveName = '';
1120 protected $filename;
1125 /** @todo Unused? */
1126 private $fileIsTemp;
1129 private $mNoUpdates = false;
1132 * @param Title $title
1133 * @throws MWException
1135 function setTitle( $title ) {
1136 if ( is_object( $title ) ) {
1137 $this->title
= $title;
1138 } elseif ( is_null( $title ) ) {
1139 throw new MWException( "WikiRevision given a null title in import. "
1140 . "You may need to adjust \$wgLegalTitleChars." );
1142 throw new MWException( "WikiRevision given non-object title in import." );
1149 function setID( $id ) {
1156 function setTimestamp( $ts ) {
1157 # 2003-08-05T18:30:02Z
1158 $this->timestamp
= wfTimestamp( TS_MW
, $ts );
1162 * @param string $user
1164 function setUsername( $user ) {
1165 $this->user_text
= $user;
1171 function setUserIP( $ip ) {
1172 $this->user_text
= $ip;
1176 * @param string $model
1178 function setModel( $model ) {
1179 $this->model
= $model;
1183 * @param string $format
1185 function setFormat( $format ) {
1186 $this->format
= $format;
1190 * @param string $text
1192 function setText( $text ) {
1193 $this->text
= $text;
1197 * @param string $text
1199 function setComment( $text ) {
1200 $this->comment
= $text;
1204 * @param bool $minor
1206 function setMinor( $minor ) {
1207 $this->minor
= (bool)$minor;
1213 function setSrc( $src ) {
1218 * @param string $src
1219 * @param bool $isTemp
1221 function setFileSrc( $src, $isTemp ) {
1222 $this->fileSrc
= $src;
1223 $this->fileIsTemp
= $isTemp;
1227 * @param string $sha1base36
1229 function setSha1Base36( $sha1base36 ) {
1230 $this->sha1base36
= $sha1base36;
1234 * @param string $filename
1236 function setFilename( $filename ) {
1237 $this->filename
= $filename;
1241 * @param string $archiveName
1243 function setArchiveName( $archiveName ) {
1244 $this->archiveName
= $archiveName;
1250 function setSize( $size ) {
1251 $this->size
= intval( $size );
1255 * @param string $type
1257 function setType( $type ) {
1258 $this->type
= $type;
1262 * @param string $action
1264 function setAction( $action ) {
1265 $this->action
= $action;
1269 * @param array $params
1271 function setParams( $params ) {
1272 $this->params
= $params;
1276 * @param bool $noupdates
1278 public function setNoUpdates( $noupdates ) {
1279 $this->mNoUpdates
= $noupdates;
1285 function getTitle() {
1286 return $this->title
;
1299 function getTimestamp() {
1300 return $this->timestamp
;
1306 function getUser() {
1307 return $this->user_text
;
1313 * @deprecated Since 1.21, use getContent() instead.
1315 function getText() {
1316 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1324 function getContent() {
1325 if ( is_null( $this->content
) ) {
1327 ContentHandler
::makeContent(
1335 return $this->content
;
1341 function getModel() {
1342 if ( is_null( $this->model
) ) {
1343 $this->model
= $this->getTitle()->getContentModel();
1346 return $this->model
;
1352 function getFormat() {
1353 if ( is_null( $this->model
) ) {
1354 $this->format
= ContentHandler
::getForTitle( $this->getTitle() )->getDefaultFormat();
1357 return $this->format
;
1363 function getComment() {
1364 return $this->comment
;
1370 function getMinor() {
1371 return $this->minor
;
1382 * @return bool|string
1384 function getSha1() {
1385 if ( $this->sha1base36
) {
1386 return wfBaseConvert( $this->sha1base36
, 36, 16 );
1394 function getFileSrc() {
1395 return $this->fileSrc
;
1401 function isTempSrc() {
1402 return $this->isTemp
;
1408 function getFilename() {
1409 return $this->filename
;
1415 function getArchiveName() {
1416 return $this->archiveName
;
1422 function getSize() {
1429 function getType() {
1436 function getAction() {
1437 return $this->action
;
1443 function getParams() {
1444 return $this->params
;
1450 function importOldRevision() {
1451 $dbw = wfGetDB( DB_MASTER
);
1453 # Sneak a single revision into place
1454 $user = User
::newFromName( $this->getUser() );
1456 $userId = intval( $user->getId() );
1457 $userText = $user->getName();
1461 $userText = $this->getUser();
1462 $userObj = new User
;
1465 // avoid memory leak...?
1466 $linkCache = LinkCache
::singleton();
1467 $linkCache->clear();
1469 $page = WikiPage
::factory( $this->title
);
1470 if ( !$page->exists() ) {
1471 # must create the page...
1472 $pageId = $page->insertOn( $dbw );
1474 $oldcountable = null;
1476 $pageId = $page->getId();
1479 $prior = $dbw->selectField( 'revision', '1',
1480 array( 'rev_page' => $pageId,
1481 'rev_timestamp' => $dbw->timestamp( $this->timestamp
),
1482 'rev_user_text' => $userText,
1483 'rev_comment' => $this->getComment() ),
1487 // @todo FIXME: This could fail slightly for multiple matches :P
1488 wfDebug( __METHOD__
. ": skipping existing revision for [[" .
1489 $this->title
->getPrefixedText() . "]], timestamp " . $this->timestamp
. "\n" );
1492 $oldcountable = $page->isCountable();
1495 # @todo FIXME: Use original rev_id optionally (better for backups)
1497 $revision = new Revision( array(
1498 'title' => $this->title
,
1500 'content_model' => $this->getModel(),
1501 'content_format' => $this->getFormat(),
1502 //XXX: just set 'content' => $this->getContent()?
1503 'text' => $this->getContent()->serialize( $this->getFormat() ),
1504 'comment' => $this->getComment(),
1506 'user_text' => $userText,
1507 'timestamp' => $this->timestamp
,
1508 'minor_edit' => $this->minor
,
1510 $revision->insertOn( $dbw );
1511 $changed = $page->updateIfNewerOn( $dbw, $revision );
1513 if ( $changed !== false && !$this->mNoUpdates
) {
1514 wfDebug( __METHOD__
. ": running updates\n" );
1515 $page->doEditUpdates(
1518 array( 'created' => $created, 'oldcountable' => $oldcountable )
1528 function importLogItem() {
1529 $dbw = wfGetDB( DB_MASTER
);
1530 # @todo FIXME: This will not record autoblocks
1531 if ( !$this->getTitle() ) {
1532 wfDebug( __METHOD__
. ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1533 $this->timestamp
. "\n" );
1536 # Check if it exists already
1537 // @todo FIXME: Use original log ID (better for backups)
1538 $prior = $dbw->selectField( 'logging', '1',
1539 array( 'log_type' => $this->getType(),
1540 'log_action' => $this->getAction(),
1541 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1542 'log_namespace' => $this->getTitle()->getNamespace(),
1543 'log_title' => $this->getTitle()->getDBkey(),
1544 'log_comment' => $this->getComment(),
1545 #'log_user_text' => $this->user_text,
1546 'log_params' => $this->params
),
1549 // @todo FIXME: This could fail slightly for multiple matches :P
1552 . ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp "
1553 . $this->timestamp
. "\n" );
1556 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1558 'log_id' => $log_id,
1559 'log_type' => $this->type
,
1560 'log_action' => $this->action
,
1561 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1562 'log_user' => User
::idFromName( $this->user_text
),
1563 #'log_user_text' => $this->user_text,
1564 'log_namespace' => $this->getTitle()->getNamespace(),
1565 'log_title' => $this->getTitle()->getDBkey(),
1566 'log_comment' => $this->getComment(),
1567 'log_params' => $this->params
1569 $dbw->insert( 'logging', $data, __METHOD__
);
1575 function importUpload() {
1577 $archiveName = $this->getArchiveName();
1578 if ( $archiveName ) {
1579 wfDebug( __METHOD__
. "Importing archived file as $archiveName\n" );
1580 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1581 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1583 $file = wfLocalFile( $this->getTitle() );
1584 wfDebug( __METHOD__
. 'Importing new file as ' . $file->getName() . "\n" );
1585 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1586 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1587 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1588 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1589 wfDebug( __METHOD__
. "File already exists; importing as $archiveName\n" );
1593 wfDebug( __METHOD__
. ': Bad file for ' . $this->getTitle() . "\n" );
1597 # Get the file source or download if necessary
1598 $source = $this->getFileSrc();
1599 $flags = $this->isTempSrc() ? File
::DELETE_SOURCE
: 0;
1601 $source = $this->downloadSource();
1602 $flags |
= File
::DELETE_SOURCE
;
1605 wfDebug( __METHOD__
. ": Could not fetch remote file.\n" );
1608 $sha1 = $this->getSha1();
1609 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1610 if ( $flags & File
::DELETE_SOURCE
) {
1611 # Broken file; delete it if it is a temporary file
1614 wfDebug( __METHOD__
. ": Corrupt file $source.\n" );
1618 $user = User
::newFromName( $this->user_text
);
1620 # Do the actual upload
1621 if ( $archiveName ) {
1622 $status = $file->uploadOld( $source, $archiveName,
1623 $this->getTimestamp(), $this->getComment(), $user, $flags );
1625 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1626 $flags, false, $this->getTimestamp(), $user );
1629 if ( $status->isGood() ) {
1630 wfDebug( __METHOD__
. ": Successful\n" );
1633 wfDebug( __METHOD__
. ': failed: ' . $status->getXml() . "\n" );
1639 * @return bool|string
1641 function downloadSource() {
1642 global $wgEnableUploads;
1643 if ( !$wgEnableUploads ) {
1647 $tempo = tempnam( wfTempDir(), 'download' );
1648 $f = fopen( $tempo, 'wb' );
1650 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1655 $src = $this->getSrc();
1656 $data = Http
::get( $src );
1658 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1664 fwrite( $f, $data );
1673 * @todo document (e.g. one-sentence class description).
1674 * @ingroup SpecialPage
1676 class ImportStringSource
{
1677 function __construct( $string ) {
1678 $this->mString
= $string;
1679 $this->mRead
= false;
1686 return $this->mRead
;
1690 * @return bool|string
1692 function readChunk() {
1693 if ( $this->atEnd() ) {
1696 $this->mRead
= true;
1697 return $this->mString
;
1702 * @todo document (e.g. one-sentence class description).
1703 * @ingroup SpecialPage
1705 class ImportStreamSource
{
1706 function __construct( $handle ) {
1707 $this->mHandle
= $handle;
1714 return feof( $this->mHandle
);
1720 function readChunk() {
1721 return fread( $this->mHandle
, 32768 );
1725 * @param string $filename
1728 static function newFromFile( $filename ) {
1729 wfSuppressWarnings();
1730 $file = fopen( $filename, 'rt' );
1731 wfRestoreWarnings();
1733 return Status
::newFatal( "importcantopen" );
1735 return Status
::newGood( new ImportStreamSource( $file ) );
1739 * @param string $fieldname
1742 static function newFromUpload( $fieldname = "xmlimport" ) {
1743 $upload =& $_FILES[$fieldname];
1745 if ( $upload === null ||
!$upload['name'] ) {
1746 return Status
::newFatal( 'importnofile' );
1748 if ( !empty( $upload['error'] ) ) {
1749 switch ( $upload['error'] ) {
1751 # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1752 return Status
::newFatal( 'importuploaderrorsize' );
1754 # The uploaded file exceeds the MAX_FILE_SIZE directive that
1755 # was specified in the HTML form.
1756 return Status
::newFatal( 'importuploaderrorsize' );
1758 # The uploaded file was only partially uploaded
1759 return Status
::newFatal( 'importuploaderrorpartial' );
1761 # Missing a temporary folder.
1762 return Status
::newFatal( 'importuploaderrortemp' );
1763 # case else: # Currently impossible
1767 $fname = $upload['tmp_name'];
1768 if ( is_uploaded_file( $fname ) ) {
1769 return ImportStreamSource
::newFromFile( $fname );
1771 return Status
::newFatal( 'importnofile' );
1776 * @param string $url
1777 * @param string $method
1780 static function newFromURL( $url, $method = 'GET' ) {
1781 wfDebug( __METHOD__
. ": opening $url\n" );
1782 # Use the standard HTTP fetch function; it times out
1783 # quicker and sorts out user-agent problems which might
1784 # otherwise prevent importing from large sites, such
1785 # as the Wikimedia cluster, etc.
1786 $data = Http
::request( $method, $url, array( 'followRedirects' => true ) );
1787 if ( $data !== false ) {
1789 fwrite( $file, $data );
1792 return Status
::newGood( new ImportStreamSource( $file ) );
1794 return Status
::newFatal( 'importcantopen' );
1799 * @param string $interwiki
1800 * @param string $page
1801 * @param bool $history
1802 * @param bool $templates
1803 * @param int $pageLinkDepth
1806 public static function newFromInterwiki( $interwiki, $page, $history = false,
1807 $templates = false, $pageLinkDepth = 0
1809 if ( $page == '' ) {
1810 return Status
::newFatal( 'import-noarticle' );
1812 $link = Title
::newFromText( "$interwiki:Special:Export/$page" );
1813 if ( is_null( $link ) ||
!$link->isExternal() ) {
1814 return Status
::newFatal( 'importbadinterwiki' );
1818 $params['history'] = 1;
1821 $params['templates'] = 1;
1823 if ( $pageLinkDepth ) {
1824 $params['pagelink-depth'] = $pageLinkDepth;
1826 $url = $link->getFullURL( $params );
1827 # For interwikis, use POST to avoid redirects.
1828 return ImportStreamSource
::newFromURL( $url, "POST" );