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->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['model'] ) ) {
698 $revision->setModel( $revisionInfo['model'] );
700 if ( isset( $revisionInfo['format'] ) ) {
701 $revision->setFormat( $revisionInfo['format'] );
703 $revision->setTitle( $pageInfo['_title'] );
705 if ( isset( $revisionInfo['text'] ) ) {
706 $handler = $revision->getContentHandler();
707 $text = $handler->importTransform(
708 $revisionInfo['text'],
709 $revision->getFormat() );
711 $revision->setText( $text );
713 if ( isset( $revisionInfo['timestamp'] ) ) {
714 $revision->setTimestamp( $revisionInfo['timestamp'] );
716 $revision->setTimestamp( wfTimestampNow() );
719 if ( isset( $revisionInfo['comment'] ) ) {
720 $revision->setComment( $revisionInfo['comment'] );
723 if ( isset( $revisionInfo['minor'] ) ) {
724 $revision->setMinor( true );
726 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
727 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
729 if ( isset( $revisionInfo['contributor']['username'] ) ) {
730 $revision->setUserName( $revisionInfo['contributor']['username'] );
732 $revision->setNoUpdates( $this->mNoUpdates
);
734 return $this->revisionCallback( $revision );
738 * @param array $pageInfo
741 private function handleUpload( &$pageInfo ) {
742 $this->debug( "Enter upload handler" );
743 $uploadInfo = array();
745 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
746 'src', 'size', 'sha1base36', 'archivename', 'rel' );
750 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
751 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
752 $this->reader
->name
== 'upload' ) {
756 $tag = $this->reader
->name
;
758 if ( !wfRunHooks( 'ImportHandleUploadXMLTag', array(
762 } elseif ( in_array( $tag, $normalFields ) ) {
763 $uploadInfo[$tag] = $this->nodeContents();
764 } elseif ( $tag == 'contributor' ) {
765 $uploadInfo['contributor'] = $this->handleContributor();
766 } elseif ( $tag == 'contents' ) {
767 $contents = $this->nodeContents();
768 $encoding = $this->reader
->getAttribute( 'encoding' );
769 if ( $encoding === 'base64' ) {
770 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
771 $uploadInfo['isTempSrc'] = true;
773 } elseif ( $tag != '#text' ) {
774 $this->warn( "Unhandled upload XML tag $tag" );
779 if ( $this->mImageBasePath
&& isset( $uploadInfo['rel'] ) ) {
780 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
781 if ( file_exists( $path ) ) {
782 $uploadInfo['fileSrc'] = $path;
783 $uploadInfo['isTempSrc'] = false;
787 if ( $this->mImportUploads
) {
788 return $this->processUpload( $pageInfo, $uploadInfo );
793 * @param string $contents
796 private function dumpTemp( $contents ) {
797 $filename = tempnam( wfTempDir(), 'importupload' );
798 file_put_contents( $filename, $contents );
803 * @param array $pageInfo
804 * @param array $uploadInfo
807 private function processUpload( $pageInfo, $uploadInfo ) {
808 $revision = new WikiRevision
;
809 $text = isset( $uploadInfo['text'] ) ?
$uploadInfo['text'] : '';
811 $revision->setTitle( $pageInfo['_title'] );
812 $revision->setID( $pageInfo['id'] );
813 $revision->setTimestamp( $uploadInfo['timestamp'] );
814 $revision->setText( $text );
815 $revision->setFilename( $uploadInfo['filename'] );
816 if ( isset( $uploadInfo['archivename'] ) ) {
817 $revision->setArchiveName( $uploadInfo['archivename'] );
819 $revision->setSrc( $uploadInfo['src'] );
820 if ( isset( $uploadInfo['fileSrc'] ) ) {
821 $revision->setFileSrc( $uploadInfo['fileSrc'],
822 !empty( $uploadInfo['isTempSrc'] ) );
824 if ( isset( $uploadInfo['sha1base36'] ) ) {
825 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
827 $revision->setSize( intval( $uploadInfo['size'] ) );
828 $revision->setComment( $uploadInfo['comment'] );
830 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
831 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
833 if ( isset( $uploadInfo['contributor']['username'] ) ) {
834 $revision->setUserName( $uploadInfo['contributor']['username'] );
836 $revision->setNoUpdates( $this->mNoUpdates
);
838 return call_user_func( $this->mUploadCallback
, $revision );
844 private function handleContributor() {
845 $fields = array( 'id', 'ip', 'username' );
848 while ( $this->reader
->read() ) {
849 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
850 $this->reader
->name
== 'contributor' ) {
854 $tag = $this->reader
->name
;
856 if ( in_array( $tag, $fields ) ) {
857 $info[$tag] = $this->nodeContents();
865 * @param string $text
868 private function processTitle( $text ) {
869 global $wgCommandLineMode;
872 $origTitle = Title
::newFromText( $workTitle );
874 if ( !is_null( $this->mTargetNamespace
) && !is_null( $origTitle ) ) {
875 # makeTitleSafe, because $origTitle can have a interwiki (different setting of interwiki map)
876 # and than dbKey can begin with a lowercase char
877 $title = Title
::makeTitleSafe( $this->mTargetNamespace
,
878 $origTitle->getDBkey() );
880 if ( !is_null( $this->mTargetRootPage
) ) {
881 $workTitle = $this->mTargetRootPage
. '/' . $workTitle;
883 $title = Title
::newFromText( $workTitle );
886 if ( is_null( $title ) ) {
887 # Invalid page title? Ignore the page
888 $this->notice( 'import-error-invalid', $workTitle );
890 } elseif ( $title->isExternal() ) {
891 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
893 } elseif ( !$title->canExist() ) {
894 $this->notice( 'import-error-special', $title->getPrefixedText() );
896 } elseif ( !$title->userCan( 'edit' ) && !$wgCommandLineMode ) {
897 # Do not import if the importing wiki user cannot edit this page
898 $this->notice( 'import-error-edit', $title->getPrefixedText() );
900 } elseif ( !$title->exists() && !$title->userCan( 'create' ) && !$wgCommandLineMode ) {
901 # Do not import if the importing wiki user cannot create this page
902 $this->notice( 'import-error-create', $title->getPrefixedText() );
906 return array( $title, $origTitle );
910 /** This is a horrible hack used to keep source compatibility */
911 class UploadSourceAdapter
{
913 private static $sourceRegistrations = array();
925 * @param string $source
928 static function registerSource( $source ) {
929 $id = wfRandomString();
931 self
::$sourceRegistrations[$id] = $source;
937 * @param string $path
938 * @param string $mode
939 * @param array $options
940 * @param string $opened_path
943 function stream_open( $path, $mode, $options, &$opened_path ) {
944 $url = parse_url( $path );
947 if ( !isset( self
::$sourceRegistrations[$id] ) ) {
951 $this->mSource
= self
::$sourceRegistrations[$id];
960 function stream_read( $count ) {
964 while ( !$leave && !$this->mSource
->atEnd() &&
965 strlen( $this->mBuffer
) < $count ) {
966 $read = $this->mSource
->readChunk();
968 if ( !strlen( $read ) ) {
972 $this->mBuffer
.= $read;
975 if ( strlen( $this->mBuffer
) ) {
976 $return = substr( $this->mBuffer
, 0, $count );
977 $this->mBuffer
= substr( $this->mBuffer
, $count );
980 $this->mPosition +
= strlen( $return );
986 * @param string $data
989 function stream_write( $data ) {
996 function stream_tell() {
997 return $this->mPosition
;
1003 function stream_eof() {
1004 return $this->mSource
->atEnd();
1010 function url_stat() {
1013 $result['dev'] = $result[0] = 0;
1014 $result['ino'] = $result[1] = 0;
1015 $result['mode'] = $result[2] = 0;
1016 $result['nlink'] = $result[3] = 0;
1017 $result['uid'] = $result[4] = 0;
1018 $result['gid'] = $result[5] = 0;
1019 $result['rdev'] = $result[6] = 0;
1020 $result['size'] = $result[7] = 0;
1021 $result['atime'] = $result[8] = 0;
1022 $result['mtime'] = $result[9] = 0;
1023 $result['ctime'] = $result[10] = 0;
1024 $result['blksize'] = $result[11] = 0;
1025 $result['blocks'] = $result[12] = 0;
1031 class XMLReader2
extends XMLReader
{
1034 * @return bool|string
1036 function nodeContents() {
1037 if ( $this->isEmptyElement
) {
1041 while ( $this->read() ) {
1042 switch ( $this->nodeType
) {
1043 case XmlReader
::TEXT
:
1044 case XmlReader
::SIGNIFICANT_WHITESPACE
:
1045 $buffer .= $this->value
;
1047 case XmlReader
::END_ELEMENT
:
1051 return $this->close();
1056 * @todo document (e.g. one-sentence class description).
1057 * @ingroup SpecialPage
1059 class WikiRevision
{
1060 /** @todo Unused? */
1061 private $importer = null;
1064 public $title = null;
1070 public $timestamp = "20010115000000";
1074 * @todo Can't find any uses. Public, because that's suspicious. Get clarity. */
1078 public $user_text = "";
1081 protected $model = null;
1084 protected $format = null;
1093 protected $content = null;
1095 /** @var ContentHandler */
1096 protected $contentHandler = null;
1099 public $comment = "";
1102 protected $minor = false;
1105 protected $type = "";
1108 protected $action = "";
1111 protected $params = "";
1114 protected $fileSrc = '';
1116 /** @var bool|string */
1117 protected $sha1base36 = false;
1123 private $isTemp = false;
1126 protected $archiveName = '';
1128 protected $filename;
1133 /** @todo Unused? */
1134 private $fileIsTemp;
1137 private $mNoUpdates = false;
1140 * @param Title $title
1141 * @throws MWException
1143 function setTitle( $title ) {
1144 if ( is_object( $title ) ) {
1145 $this->title
= $title;
1146 } elseif ( is_null( $title ) ) {
1147 throw new MWException( "WikiRevision given a null title in import. "
1148 . "You may need to adjust \$wgLegalTitleChars." );
1150 throw new MWException( "WikiRevision given non-object title in import." );
1157 function setID( $id ) {
1164 function setTimestamp( $ts ) {
1165 # 2003-08-05T18:30:02Z
1166 $this->timestamp
= wfTimestamp( TS_MW
, $ts );
1170 * @param string $user
1172 function setUsername( $user ) {
1173 $this->user_text
= $user;
1179 function setUserIP( $ip ) {
1180 $this->user_text
= $ip;
1184 * @param string $model
1186 function setModel( $model ) {
1187 $this->model
= $model;
1191 * @param string $format
1193 function setFormat( $format ) {
1194 $this->format
= $format;
1198 * @param string $text
1200 function setText( $text ) {
1201 $this->text
= $text;
1205 * @param string $text
1207 function setComment( $text ) {
1208 $this->comment
= $text;
1212 * @param bool $minor
1214 function setMinor( $minor ) {
1215 $this->minor
= (bool)$minor;
1221 function setSrc( $src ) {
1226 * @param string $src
1227 * @param bool $isTemp
1229 function setFileSrc( $src, $isTemp ) {
1230 $this->fileSrc
= $src;
1231 $this->fileIsTemp
= $isTemp;
1235 * @param string $sha1base36
1237 function setSha1Base36( $sha1base36 ) {
1238 $this->sha1base36
= $sha1base36;
1242 * @param string $filename
1244 function setFilename( $filename ) {
1245 $this->filename
= $filename;
1249 * @param string $archiveName
1251 function setArchiveName( $archiveName ) {
1252 $this->archiveName
= $archiveName;
1258 function setSize( $size ) {
1259 $this->size
= intval( $size );
1263 * @param string $type
1265 function setType( $type ) {
1266 $this->type
= $type;
1270 * @param string $action
1272 function setAction( $action ) {
1273 $this->action
= $action;
1277 * @param array $params
1279 function setParams( $params ) {
1280 $this->params
= $params;
1284 * @param bool $noupdates
1286 public function setNoUpdates( $noupdates ) {
1287 $this->mNoUpdates
= $noupdates;
1293 function getTitle() {
1294 return $this->title
;
1307 function getTimestamp() {
1308 return $this->timestamp
;
1314 function getUser() {
1315 return $this->user_text
;
1321 * @deprecated Since 1.21, use getContent() instead.
1323 function getText() {
1324 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1330 * @return ContentHandler
1332 function getContentHandler() {
1333 if ( is_null( $this->contentHandler
) ) {
1334 $this->contentHandler
= ContentHandler
::getForModelID( $this->getModel() );
1337 return $this->contentHandler
;
1343 function getContent() {
1344 if ( is_null( $this->content
) ) {
1345 $handler = $this->getContentHandler();
1346 $this->content
= $handler->unserializeContent( $this->text
, $this->getFormat() );
1349 return $this->content
;
1355 function getModel() {
1356 if ( is_null( $this->model
) ) {
1357 $this->model
= $this->getTitle()->getContentModel();
1360 return $this->model
;
1366 function getFormat() {
1367 if ( is_null( $this->format
) ) {
1368 $this->format
= $this->getContentHandler()->getDefaultFormat();
1371 return $this->format
;
1377 function getComment() {
1378 return $this->comment
;
1384 function getMinor() {
1385 return $this->minor
;
1396 * @return bool|string
1398 function getSha1() {
1399 if ( $this->sha1base36
) {
1400 return wfBaseConvert( $this->sha1base36
, 36, 16 );
1408 function getFileSrc() {
1409 return $this->fileSrc
;
1415 function isTempSrc() {
1416 return $this->isTemp
;
1422 function getFilename() {
1423 return $this->filename
;
1429 function getArchiveName() {
1430 return $this->archiveName
;
1436 function getSize() {
1443 function getType() {
1450 function getAction() {
1451 return $this->action
;
1457 function getParams() {
1458 return $this->params
;
1464 function importOldRevision() {
1465 $dbw = wfGetDB( DB_MASTER
);
1467 # Sneak a single revision into place
1468 $user = User
::newFromName( $this->getUser() );
1470 $userId = intval( $user->getId() );
1471 $userText = $user->getName();
1475 $userText = $this->getUser();
1476 $userObj = new User
;
1479 // avoid memory leak...?
1480 $linkCache = LinkCache
::singleton();
1481 $linkCache->clear();
1483 $page = WikiPage
::factory( $this->title
);
1484 if ( !$page->exists() ) {
1485 # must create the page...
1486 $pageId = $page->insertOn( $dbw );
1488 $oldcountable = null;
1490 $pageId = $page->getId();
1493 $prior = $dbw->selectField( 'revision', '1',
1494 array( 'rev_page' => $pageId,
1495 'rev_timestamp' => $dbw->timestamp( $this->timestamp
),
1496 'rev_user_text' => $userText,
1497 'rev_comment' => $this->getComment() ),
1501 // @todo FIXME: This could fail slightly for multiple matches :P
1502 wfDebug( __METHOD__
. ": skipping existing revision for [[" .
1503 $this->title
->getPrefixedText() . "]], timestamp " . $this->timestamp
. "\n" );
1506 $oldcountable = $page->isCountable();
1509 # @todo FIXME: Use original rev_id optionally (better for backups)
1511 $revision = new Revision( array(
1512 'title' => $this->title
,
1514 'content_model' => $this->getModel(),
1515 'content_format' => $this->getFormat(),
1516 //XXX: just set 'content' => $this->getContent()?
1517 'text' => $this->getContent()->serialize( $this->getFormat() ),
1518 'comment' => $this->getComment(),
1520 'user_text' => $userText,
1521 'timestamp' => $this->timestamp
,
1522 'minor_edit' => $this->minor
,
1524 $revision->insertOn( $dbw );
1525 $changed = $page->updateIfNewerOn( $dbw, $revision );
1527 if ( $changed !== false && !$this->mNoUpdates
) {
1528 wfDebug( __METHOD__
. ": running updates\n" );
1529 $page->doEditUpdates(
1532 array( 'created' => $created, 'oldcountable' => $oldcountable )
1542 function importLogItem() {
1543 $dbw = wfGetDB( DB_MASTER
);
1544 # @todo FIXME: This will not record autoblocks
1545 if ( !$this->getTitle() ) {
1546 wfDebug( __METHOD__
. ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1547 $this->timestamp
. "\n" );
1550 # Check if it exists already
1551 // @todo FIXME: Use original log ID (better for backups)
1552 $prior = $dbw->selectField( 'logging', '1',
1553 array( 'log_type' => $this->getType(),
1554 'log_action' => $this->getAction(),
1555 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1556 'log_namespace' => $this->getTitle()->getNamespace(),
1557 'log_title' => $this->getTitle()->getDBkey(),
1558 'log_comment' => $this->getComment(),
1559 #'log_user_text' => $this->user_text,
1560 'log_params' => $this->params
),
1563 // @todo FIXME: This could fail slightly for multiple matches :P
1566 . ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp "
1567 . $this->timestamp
. "\n" );
1570 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1572 'log_id' => $log_id,
1573 'log_type' => $this->type
,
1574 'log_action' => $this->action
,
1575 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1576 'log_user' => User
::idFromName( $this->user_text
),
1577 #'log_user_text' => $this->user_text,
1578 'log_namespace' => $this->getTitle()->getNamespace(),
1579 'log_title' => $this->getTitle()->getDBkey(),
1580 'log_comment' => $this->getComment(),
1581 'log_params' => $this->params
1583 $dbw->insert( 'logging', $data, __METHOD__
);
1589 function importUpload() {
1591 $archiveName = $this->getArchiveName();
1592 if ( $archiveName ) {
1593 wfDebug( __METHOD__
. "Importing archived file as $archiveName\n" );
1594 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1595 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1597 $file = wfLocalFile( $this->getTitle() );
1598 wfDebug( __METHOD__
. 'Importing new file as ' . $file->getName() . "\n" );
1599 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1600 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1601 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1602 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1603 wfDebug( __METHOD__
. "File already exists; importing as $archiveName\n" );
1607 wfDebug( __METHOD__
. ': Bad file for ' . $this->getTitle() . "\n" );
1611 # Get the file source or download if necessary
1612 $source = $this->getFileSrc();
1613 $flags = $this->isTempSrc() ? File
::DELETE_SOURCE
: 0;
1615 $source = $this->downloadSource();
1616 $flags |
= File
::DELETE_SOURCE
;
1619 wfDebug( __METHOD__
. ": Could not fetch remote file.\n" );
1622 $sha1 = $this->getSha1();
1623 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1624 if ( $flags & File
::DELETE_SOURCE
) {
1625 # Broken file; delete it if it is a temporary file
1628 wfDebug( __METHOD__
. ": Corrupt file $source.\n" );
1632 $user = User
::newFromName( $this->user_text
);
1634 # Do the actual upload
1635 if ( $archiveName ) {
1636 $status = $file->uploadOld( $source, $archiveName,
1637 $this->getTimestamp(), $this->getComment(), $user, $flags );
1639 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1640 $flags, false, $this->getTimestamp(), $user );
1643 if ( $status->isGood() ) {
1644 wfDebug( __METHOD__
. ": Successful\n" );
1647 wfDebug( __METHOD__
. ': failed: ' . $status->getXml() . "\n" );
1653 * @return bool|string
1655 function downloadSource() {
1656 global $wgEnableUploads;
1657 if ( !$wgEnableUploads ) {
1661 $tempo = tempnam( wfTempDir(), 'download' );
1662 $f = fopen( $tempo, 'wb' );
1664 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1669 $src = $this->getSrc();
1670 $data = Http
::get( $src );
1672 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1678 fwrite( $f, $data );
1687 * @todo document (e.g. one-sentence class description).
1688 * @ingroup SpecialPage
1690 class ImportStringSource
{
1691 function __construct( $string ) {
1692 $this->mString
= $string;
1693 $this->mRead
= false;
1700 return $this->mRead
;
1704 * @return bool|string
1706 function readChunk() {
1707 if ( $this->atEnd() ) {
1710 $this->mRead
= true;
1711 return $this->mString
;
1716 * @todo document (e.g. one-sentence class description).
1717 * @ingroup SpecialPage
1719 class ImportStreamSource
{
1720 function __construct( $handle ) {
1721 $this->mHandle
= $handle;
1728 return feof( $this->mHandle
);
1734 function readChunk() {
1735 return fread( $this->mHandle
, 32768 );
1739 * @param string $filename
1742 static function newFromFile( $filename ) {
1743 wfSuppressWarnings();
1744 $file = fopen( $filename, 'rt' );
1745 wfRestoreWarnings();
1747 return Status
::newFatal( "importcantopen" );
1749 return Status
::newGood( new ImportStreamSource( $file ) );
1753 * @param string $fieldname
1756 static function newFromUpload( $fieldname = "xmlimport" ) {
1757 $upload =& $_FILES[$fieldname];
1759 if ( $upload === null ||
!$upload['name'] ) {
1760 return Status
::newFatal( 'importnofile' );
1762 if ( !empty( $upload['error'] ) ) {
1763 switch ( $upload['error'] ) {
1765 # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1766 return Status
::newFatal( 'importuploaderrorsize' );
1768 # The uploaded file exceeds the MAX_FILE_SIZE directive that
1769 # was specified in the HTML form.
1770 return Status
::newFatal( 'importuploaderrorsize' );
1772 # The uploaded file was only partially uploaded
1773 return Status
::newFatal( 'importuploaderrorpartial' );
1775 # Missing a temporary folder.
1776 return Status
::newFatal( 'importuploaderrortemp' );
1777 # case else: # Currently impossible
1781 $fname = $upload['tmp_name'];
1782 if ( is_uploaded_file( $fname ) ) {
1783 return ImportStreamSource
::newFromFile( $fname );
1785 return Status
::newFatal( 'importnofile' );
1790 * @param string $url
1791 * @param string $method
1794 static function newFromURL( $url, $method = 'GET' ) {
1795 wfDebug( __METHOD__
. ": opening $url\n" );
1796 # Use the standard HTTP fetch function; it times out
1797 # quicker and sorts out user-agent problems which might
1798 # otherwise prevent importing from large sites, such
1799 # as the Wikimedia cluster, etc.
1800 $data = Http
::request( $method, $url, array( 'followRedirects' => true ) );
1801 if ( $data !== false ) {
1803 fwrite( $file, $data );
1806 return Status
::newGood( new ImportStreamSource( $file ) );
1808 return Status
::newFatal( 'importcantopen' );
1813 * @param string $interwiki
1814 * @param string $page
1815 * @param bool $history
1816 * @param bool $templates
1817 * @param int $pageLinkDepth
1820 public static function newFromInterwiki( $interwiki, $page, $history = false,
1821 $templates = false, $pageLinkDepth = 0
1823 if ( $page == '' ) {
1824 return Status
::newFatal( 'import-noarticle' );
1826 $link = Title
::newFromText( "$interwiki:Special:Export/$page" );
1827 if ( is_null( $link ) ||
!$link->isExternal() ) {
1828 return Status
::newFatal( 'importbadinterwiki' );
1832 $params['history'] = 1;
1835 $params['templates'] = 1;
1837 if ( $pageLinkDepth ) {
1838 $params['pagelink-depth'] = $pageLinkDepth;
1840 $url = $link->getFullURL( $params );
1841 # For interwikis, use POST to avoid redirects.
1842 return ImportStreamSource
::newFromURL( $url, "POST" );