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()
71 public function throwXmlError( $err ) {
72 $this->debug( "FAILURE: $err" );
73 wfDebug( "WikiImporter XML error: $err\n" );
76 public function debug( $data ) {
77 if ( $this->mDebug
) {
78 wfDebug( "IMPORT: $data\n" );
82 public function warn( $data ) {
83 wfDebug( "IMPORT: $data\n" );
86 public function notice( $msg /*, $param, ...*/ ) {
87 $params = func_get_args();
88 array_shift( $params );
90 if ( is_callable( $this->mNoticeCallback
) ) {
91 call_user_func( $this->mNoticeCallback
, $msg, $params );
92 } else { # No ImportReporter -> CLI
93 echo wfMessage( $msg, $params )->text() . "\n";
101 function setDebug( $debug ) {
102 $this->mDebug
= $debug;
106 * Set 'no updates' mode. In this mode, the link tables will not be updated by the importer
107 * @param bool $noupdates
109 function setNoUpdates( $noupdates ) {
110 $this->mNoUpdates
= $noupdates;
114 * Set a callback that displays notice messages
116 * @param callable $callback
119 public function setNoticeCallback( $callback ) {
120 return wfSetVar( $this->mNoticeCallback
, $callback );
124 * Sets the action to perform as each new page in the stream is reached.
125 * @param callable $callback
128 public function setPageCallback( $callback ) {
129 $previous = $this->mPageCallback
;
130 $this->mPageCallback
= $callback;
135 * Sets the action to perform as each page in the stream is completed.
136 * Callback accepts the page title (as a Title object), a second object
137 * with the original title form (in case it's been overridden into a
138 * local namespace), and a count of revisions.
140 * @param callable $callback
143 public function setPageOutCallback( $callback ) {
144 $previous = $this->mPageOutCallback
;
145 $this->mPageOutCallback
= $callback;
150 * Sets the action to perform as each page revision is reached.
151 * @param callable $callback
154 public function setRevisionCallback( $callback ) {
155 $previous = $this->mRevisionCallback
;
156 $this->mRevisionCallback
= $callback;
161 * Sets the action to perform as each file upload version is reached.
162 * @param callable $callback
165 public function setUploadCallback( $callback ) {
166 $previous = $this->mUploadCallback
;
167 $this->mUploadCallback
= $callback;
172 * Sets the action to perform as each log item reached.
173 * @param callable $callback
176 public function setLogItemCallback( $callback ) {
177 $previous = $this->mLogItemCallback
;
178 $this->mLogItemCallback
= $callback;
183 * Sets the action to perform when site info is encountered
184 * @param callable $callback
187 public function setSiteInfoCallback( $callback ) {
188 $previous = $this->mSiteInfoCallback
;
189 $this->mSiteInfoCallback
= $callback;
194 * Set a target namespace to override the defaults
195 * @param null|int $namespace
198 public function setTargetNamespace( $namespace ) {
199 if ( is_null( $namespace ) ) {
200 // Don't override namespaces
201 $this->mTargetNamespace
= null;
202 } elseif ( $namespace >= 0 ) {
203 // @todo FIXME: Check for validity
204 $this->mTargetNamespace
= intval( $namespace );
211 * Set a target root page under which all pages are imported
212 * @param null|string $rootpage
215 public function setTargetRootPage( $rootpage ) {
216 $status = Status
::newGood();
217 if ( is_null( $rootpage ) ) {
219 $this->mTargetRootPage
= null;
220 } elseif ( $rootpage !== '' ) {
221 $rootpage = rtrim( $rootpage, '/' ); //avoid double slashes
222 $title = Title
::newFromText( $rootpage, !is_null( $this->mTargetNamespace
) ?
$this->mTargetNamespace
: NS_MAIN
);
223 if ( !$title ||
$title->isExternal() ) {
224 $status->fatal( 'import-rootpage-invalid' );
226 if ( !MWNamespace
::hasSubpages( $title->getNamespace() ) ) {
229 $displayNSText = $title->getNamespace() == NS_MAIN
230 ?
wfMessage( 'blanknamespace' )->text()
231 : $wgContLang->getNsText( $title->getNamespace() );
232 $status->fatal( 'import-rootpage-nosubpage', $displayNSText );
234 // set namespace to 'all', so the namespace check in processTitle() can passed
235 $this->setTargetNamespace( null );
236 $this->mTargetRootPage
= $title->getPrefixedDBkey();
246 public function setImageBasePath( $dir ) {
247 $this->mImageBasePath
= $dir;
251 * @param bool $import
253 public function setImportUploads( $import ) {
254 $this->mImportUploads
= $import;
258 * Default per-revision callback, performs the import.
259 * @param WikiRevision $revision
262 public function importRevision( $revision ) {
263 if ( !$revision->getContent()->getContentHandler()->canBeUsedOn( $revision->getTitle() ) ) {
264 $this->notice( 'import-error-bad-location',
265 $revision->getTitle()->getPrefixedText(),
267 $revision->getModel(),
268 $revision->getFormat() );
274 $dbw = wfGetDB( DB_MASTER
);
275 return $dbw->deadlockLoop( array( $revision, 'importOldRevision' ) );
276 } catch ( MWContentSerializationException
$ex ) {
277 $this->notice( 'import-error-unserialize',
278 $revision->getTitle()->getPrefixedText(),
280 $revision->getModel(),
281 $revision->getFormat() );
288 * Default per-revision callback, performs the import.
289 * @param WikiRevision $rev
292 public function importLogItem( $rev ) {
293 $dbw = wfGetDB( DB_MASTER
);
294 return $dbw->deadlockLoop( array( $rev, 'importLogItem' ) );
299 * @param WikiRevision $revision
302 public function importUpload( $revision ) {
303 $dbw = wfGetDB( DB_MASTER
);
304 return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
308 * Mostly for hook use
309 * @param Title $title
310 * @param string $origTitle
311 * @param int $revCount
312 * @param int $sRevCount
313 * @param array $pageInfo
316 public function finishImportPage( $title, $origTitle, $revCount, $sRevCount, $pageInfo ) {
317 $args = func_get_args();
318 return wfRunHooks( 'AfterImportPage', $args );
322 * Alternate per-revision callback, for debugging.
323 * @param WikiRevision $revision
325 public function debugRevisionHandler( &$revision ) {
326 $this->debug( "Got revision:" );
327 if ( is_object( $revision->title
) ) {
328 $this->debug( "-- Title: " . $revision->title
->getPrefixedText() );
330 $this->debug( "-- Title: <invalid>" );
332 $this->debug( "-- User: " . $revision->user_text
);
333 $this->debug( "-- Timestamp: " . $revision->timestamp
);
334 $this->debug( "-- Comment: " . $revision->comment
);
335 $this->debug( "-- Text: " . $revision->text
);
339 * Notify the callback function when a new "<page>" is reached.
340 * @param Title $title
342 function pageCallback( $title ) {
343 if ( isset( $this->mPageCallback
) ) {
344 call_user_func( $this->mPageCallback
, $title );
349 * Notify the callback function when a "</page>" is closed.
350 * @param Title $title
351 * @param Title $origTitle
352 * @param int $revCount
353 * @param int $sucCount Number of revisions for which callback returned true
354 * @param array $pageInfo Associative array of page information
356 private function pageOutCallback( $title, $origTitle, $revCount, $sucCount, $pageInfo ) {
357 if ( isset( $this->mPageOutCallback
) ) {
358 $args = func_get_args();
359 call_user_func_array( $this->mPageOutCallback
, $args );
364 * Notify the callback function of a revision
365 * @param WikiRevision $revision
368 private function revisionCallback( $revision ) {
369 if ( isset( $this->mRevisionCallback
) ) {
370 return call_user_func_array( $this->mRevisionCallback
,
371 array( $revision, $this ) );
378 * Notify the callback function of a new log item
379 * @param WikiRevision $revision
382 private function logItemCallback( $revision ) {
383 if ( isset( $this->mLogItemCallback
) ) {
384 return call_user_func_array( $this->mLogItemCallback
,
385 array( $revision, $this ) );
392 * Shouldn't something like this be built-in to XMLReader?
393 * Fetches text contents of the current element, assuming
394 * no sub-elements or such scary things.
398 public function nodeContents() {
399 if ( $this->reader
->isEmptyElement
) {
403 while ( $this->reader
->read() ) {
404 switch ( $this->reader
->nodeType
) {
405 case XmlReader
::TEXT
:
406 case XmlReader
::SIGNIFICANT_WHITESPACE
:
407 $buffer .= $this->reader
->value
;
409 case XmlReader
::END_ELEMENT
:
414 $this->reader
->close();
420 /** Left in for debugging */
421 private function dumpElement() {
422 static $lookup = null;
424 $xmlReaderConstants = array(
439 "SIGNIFICANT_WHITESPACE",
446 foreach ( $xmlReaderConstants as $name ) {
447 $lookup[constant( "XmlReader::$name" )] = $name;
452 $lookup[$this->reader
->nodeType
],
459 * Primary entry point
460 * @throws MWException
463 public function doImport() {
465 // Calls to reader->read need to be wrapped in calls to
466 // libxml_disable_entity_loader() to avoid local file
467 // inclusion attacks (bug 46932).
468 $oldDisable = libxml_disable_entity_loader( true );
469 $this->reader
->read();
471 if ( $this->reader
->name
!= 'mediawiki' ) {
472 libxml_disable_entity_loader( $oldDisable );
473 throw new MWException( "Expected <mediawiki> tag, got " .
474 $this->reader
->name
);
476 $this->debug( "<mediawiki> tag is correct." );
478 $this->debug( "Starting primary dump processing loop." );
480 $keepReading = $this->reader
->read();
482 while ( $keepReading ) {
483 $tag = $this->reader
->name
;
484 $type = $this->reader
->nodeType
;
486 if ( !wfRunHooks( 'ImportHandleToplevelXMLTag', array( $this ) ) ) {
488 } elseif ( $tag == 'mediawiki' && $type == XmlReader
::END_ELEMENT
) {
490 } elseif ( $tag == 'siteinfo' ) {
491 $this->handleSiteInfo();
492 } elseif ( $tag == 'page' ) {
494 } elseif ( $tag == 'logitem' ) {
495 $this->handleLogItem();
496 } elseif ( $tag != '#text' ) {
497 $this->warn( "Unhandled top-level XML tag $tag" );
503 $keepReading = $this->reader
->next();
505 $this->debug( "Skip" );
507 $keepReading = $this->reader
->read();
511 libxml_disable_entity_loader( $oldDisable );
517 * @throws MWException
519 private function handleSiteInfo() {
520 // Site info is useful, but not actually used for dump imports.
521 // Includes a quick short-circuit to save performance.
522 if ( ! $this->mSiteInfoCallback
) {
523 $this->reader
->next();
526 throw new MWException( "SiteInfo tag is not yet handled, do not set mSiteInfoCallback" );
529 private function handleLogItem() {
530 $this->debug( "Enter log item handler." );
533 // Fields that can just be stuffed in the pageInfo object
534 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
535 'logtitle', 'params' );
537 while ( $this->reader
->read() ) {
538 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
539 $this->reader
->name
== 'logitem' ) {
543 $tag = $this->reader
->name
;
545 if ( !wfRunHooks( 'ImportHandleLogItemXMLTag', array(
549 } elseif ( in_array( $tag, $normalFields ) ) {
550 $logInfo[$tag] = $this->nodeContents();
551 } elseif ( $tag == 'contributor' ) {
552 $logInfo['contributor'] = $this->handleContributor();
553 } elseif ( $tag != '#text' ) {
554 $this->warn( "Unhandled log-item XML tag $tag" );
558 $this->processLogItem( $logInfo );
562 * @param array $logInfo
565 private function processLogItem( $logInfo ) {
566 $revision = new WikiRevision
;
568 $revision->setID( $logInfo['id'] );
569 $revision->setType( $logInfo['type'] );
570 $revision->setAction( $logInfo['action'] );
571 $revision->setTimestamp( $logInfo['timestamp'] );
572 $revision->setParams( $logInfo['params'] );
573 $revision->setTitle( Title
::newFromText( $logInfo['logtitle'] ) );
574 $revision->setNoUpdates( $this->mNoUpdates
);
576 if ( isset( $logInfo['comment'] ) ) {
577 $revision->setComment( $logInfo['comment'] );
580 if ( isset( $logInfo['contributor']['ip'] ) ) {
581 $revision->setUserIP( $logInfo['contributor']['ip'] );
583 if ( isset( $logInfo['contributor']['username'] ) ) {
584 $revision->setUserName( $logInfo['contributor']['username'] );
587 return $this->logItemCallback( $revision );
590 private function handlePage() {
592 $this->debug( "Enter page handler." );
593 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
595 // Fields that can just be stuffed in the pageInfo object
596 $normalFields = array( 'title', 'id', 'redirect', 'restrictions' );
601 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
602 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
603 $this->reader
->name
== 'page' ) {
607 $tag = $this->reader
->name
;
610 // The title is invalid, bail out of this page
612 } elseif ( !wfRunHooks( 'ImportHandlePageXMLTag', array( $this,
615 } elseif ( in_array( $tag, $normalFields ) ) {
616 $pageInfo[$tag] = $this->nodeContents();
617 if ( $tag == 'title' ) {
618 $title = $this->processTitle( $pageInfo['title'] );
625 $this->pageCallback( $title );
626 list( $pageInfo['_title'], $origTitle ) = $title;
628 } elseif ( $tag == 'revision' ) {
629 $this->handleRevision( $pageInfo );
630 } elseif ( $tag == 'upload' ) {
631 $this->handleUpload( $pageInfo );
632 } elseif ( $tag != '#text' ) {
633 $this->warn( "Unhandled page XML tag $tag" );
638 $this->pageOutCallback( $pageInfo['_title'], $origTitle,
639 $pageInfo['revisionCount'],
640 $pageInfo['successfulRevisionCount'],
645 * @param array $pageInfo
647 private function handleRevision( &$pageInfo ) {
648 $this->debug( "Enter revision handler" );
649 $revisionInfo = array();
651 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'model', 'format', 'text' );
655 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
656 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
657 $this->reader
->name
== 'revision' ) {
661 $tag = $this->reader
->name
;
663 if ( !wfRunHooks( 'ImportHandleRevisionXMLTag', array(
664 $this, $pageInfo, $revisionInfo
667 } elseif ( in_array( $tag, $normalFields ) ) {
668 $revisionInfo[$tag] = $this->nodeContents();
669 } elseif ( $tag == 'contributor' ) {
670 $revisionInfo['contributor'] = $this->handleContributor();
671 } elseif ( $tag != '#text' ) {
672 $this->warn( "Unhandled revision XML tag $tag" );
677 $pageInfo['revisionCount']++
;
678 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
679 $pageInfo['successfulRevisionCount']++
;
684 * @param array $pageInfo
685 * @param array $revisionInfo
688 private function processRevision( $pageInfo, $revisionInfo ) {
689 $revision = new WikiRevision
;
691 if ( isset( $revisionInfo['id'] ) ) {
692 $revision->setID( $revisionInfo['id'] );
694 if ( isset( $revisionInfo['text'] ) ) {
695 $revision->setText( $revisionInfo['text'] );
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['timestamp'] ) ) {
706 $revision->setTimestamp( $revisionInfo['timestamp'] );
708 $revision->setTimestamp( wfTimestampNow() );
711 if ( isset( $revisionInfo['comment'] ) ) {
712 $revision->setComment( $revisionInfo['comment'] );
715 if ( isset( $revisionInfo['minor'] ) ) {
716 $revision->setMinor( true );
718 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
719 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
721 if ( isset( $revisionInfo['contributor']['username'] ) ) {
722 $revision->setUserName( $revisionInfo['contributor']['username'] );
724 $revision->setNoUpdates( $this->mNoUpdates
);
726 return $this->revisionCallback( $revision );
730 * @param array $pageInfo
733 private function handleUpload( &$pageInfo ) {
734 $this->debug( "Enter upload handler" );
735 $uploadInfo = array();
737 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
738 'src', 'size', 'sha1base36', 'archivename', 'rel' );
742 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
743 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
744 $this->reader
->name
== 'upload' ) {
748 $tag = $this->reader
->name
;
750 if ( !wfRunHooks( 'ImportHandleUploadXMLTag', array(
754 } elseif ( in_array( $tag, $normalFields ) ) {
755 $uploadInfo[$tag] = $this->nodeContents();
756 } elseif ( $tag == 'contributor' ) {
757 $uploadInfo['contributor'] = $this->handleContributor();
758 } elseif ( $tag == 'contents' ) {
759 $contents = $this->nodeContents();
760 $encoding = $this->reader
->getAttribute( 'encoding' );
761 if ( $encoding === 'base64' ) {
762 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
763 $uploadInfo['isTempSrc'] = true;
765 } elseif ( $tag != '#text' ) {
766 $this->warn( "Unhandled upload XML tag $tag" );
771 if ( $this->mImageBasePath
&& isset( $uploadInfo['rel'] ) ) {
772 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
773 if ( file_exists( $path ) ) {
774 $uploadInfo['fileSrc'] = $path;
775 $uploadInfo['isTempSrc'] = false;
779 if ( $this->mImportUploads
) {
780 return $this->processUpload( $pageInfo, $uploadInfo );
785 * @param string $contents
788 private function dumpTemp( $contents ) {
789 $filename = tempnam( wfTempDir(), 'importupload' );
790 file_put_contents( $filename, $contents );
795 * @param array $pageInfo
796 * @param array $uploadInfo
799 private function processUpload( $pageInfo, $uploadInfo ) {
800 $revision = new WikiRevision
;
801 $text = isset( $uploadInfo['text'] ) ?
$uploadInfo['text'] : '';
803 $revision->setTitle( $pageInfo['_title'] );
804 $revision->setID( $pageInfo['id'] );
805 $revision->setTimestamp( $uploadInfo['timestamp'] );
806 $revision->setText( $text );
807 $revision->setFilename( $uploadInfo['filename'] );
808 if ( isset( $uploadInfo['archivename'] ) ) {
809 $revision->setArchiveName( $uploadInfo['archivename'] );
811 $revision->setSrc( $uploadInfo['src'] );
812 if ( isset( $uploadInfo['fileSrc'] ) ) {
813 $revision->setFileSrc( $uploadInfo['fileSrc'],
814 !empty( $uploadInfo['isTempSrc'] ) );
816 if ( isset( $uploadInfo['sha1base36'] ) ) {
817 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
819 $revision->setSize( intval( $uploadInfo['size'] ) );
820 $revision->setComment( $uploadInfo['comment'] );
822 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
823 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
825 if ( isset( $uploadInfo['contributor']['username'] ) ) {
826 $revision->setUserName( $uploadInfo['contributor']['username'] );
828 $revision->setNoUpdates( $this->mNoUpdates
);
830 return call_user_func( $this->mUploadCallback
, $revision );
836 private function handleContributor() {
837 $fields = array( 'id', 'ip', 'username' );
840 while ( $this->reader
->read() ) {
841 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
842 $this->reader
->name
== 'contributor' ) {
846 $tag = $this->reader
->name
;
848 if ( in_array( $tag, $fields ) ) {
849 $info[$tag] = $this->nodeContents();
857 * @param string $text
860 private function processTitle( $text ) {
861 global $wgCommandLineMode;
864 $origTitle = Title
::newFromText( $workTitle );
866 if ( !is_null( $this->mTargetNamespace
) && !is_null( $origTitle ) ) {
867 # makeTitleSafe, because $origTitle can have a interwiki (different setting of interwiki map)
868 # and than dbKey can begin with a lowercase char
869 $title = Title
::makeTitleSafe( $this->mTargetNamespace
,
870 $origTitle->getDBkey() );
872 if ( !is_null( $this->mTargetRootPage
) ) {
873 $workTitle = $this->mTargetRootPage
. '/' . $workTitle;
875 $title = Title
::newFromText( $workTitle );
878 if ( is_null( $title ) ) {
879 # Invalid page title? Ignore the page
880 $this->notice( 'import-error-invalid', $workTitle );
882 } elseif ( $title->isExternal() ) {
883 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
885 } elseif ( !$title->canExist() ) {
886 $this->notice( 'import-error-special', $title->getPrefixedText() );
888 } elseif ( !$title->userCan( 'edit' ) && !$wgCommandLineMode ) {
889 # Do not import if the importing wiki user cannot edit this page
890 $this->notice( 'import-error-edit', $title->getPrefixedText() );
892 } elseif ( !$title->exists() && !$title->userCan( 'create' ) && !$wgCommandLineMode ) {
893 # Do not import if the importing wiki user cannot create this page
894 $this->notice( 'import-error-create', $title->getPrefixedText() );
898 return array( $title, $origTitle );
902 /** This is a horrible hack used to keep source compatibility */
903 class UploadSourceAdapter
{
904 static $sourceRegistrations = array();
911 * @param string $source
914 static function registerSource( $source ) {
915 $id = wfRandomString();
917 self
::$sourceRegistrations[$id] = $source;
923 * @param string $path
924 * @param string $mode
925 * @param array $options
926 * @param string $opened_path
929 function stream_open( $path, $mode, $options, &$opened_path ) {
930 $url = parse_url( $path );
933 if ( !isset( self
::$sourceRegistrations[$id] ) ) {
937 $this->mSource
= self
::$sourceRegistrations[$id];
946 function stream_read( $count ) {
950 while ( !$leave && !$this->mSource
->atEnd() &&
951 strlen( $this->mBuffer
) < $count ) {
952 $read = $this->mSource
->readChunk();
954 if ( !strlen( $read ) ) {
958 $this->mBuffer
.= $read;
961 if ( strlen( $this->mBuffer
) ) {
962 $return = substr( $this->mBuffer
, 0, $count );
963 $this->mBuffer
= substr( $this->mBuffer
, $count );
966 $this->mPosition +
= strlen( $return );
972 * @param string $data
975 function stream_write( $data ) {
982 function stream_tell() {
983 return $this->mPosition
;
989 function stream_eof() {
990 return $this->mSource
->atEnd();
996 function url_stat() {
999 $result['dev'] = $result[0] = 0;
1000 $result['ino'] = $result[1] = 0;
1001 $result['mode'] = $result[2] = 0;
1002 $result['nlink'] = $result[3] = 0;
1003 $result['uid'] = $result[4] = 0;
1004 $result['gid'] = $result[5] = 0;
1005 $result['rdev'] = $result[6] = 0;
1006 $result['size'] = $result[7] = 0;
1007 $result['atime'] = $result[8] = 0;
1008 $result['mtime'] = $result[9] = 0;
1009 $result['ctime'] = $result[10] = 0;
1010 $result['blksize'] = $result[11] = 0;
1011 $result['blocks'] = $result[12] = 0;
1017 class XMLReader2
extends XMLReader
{
1020 * @return bool|string
1022 function nodeContents() {
1023 if ( $this->isEmptyElement
) {
1027 while ( $this->read() ) {
1028 switch ( $this->nodeType
) {
1029 case XmlReader
::TEXT
:
1030 case XmlReader
::SIGNIFICANT_WHITESPACE
:
1031 $buffer .= $this->value
;
1033 case XmlReader
::END_ELEMENT
:
1037 return $this->close();
1042 * @todo document (e.g. one-sentence class description).
1043 * @ingroup SpecialPage
1045 class WikiRevision
{
1046 var $importer = null;
1053 var $timestamp = "20010115000000";
1055 var $user_text = "";
1059 var $content = null;
1066 var $sha1base36 = false;
1067 var $isTemp = false;
1068 var $archiveName = '';
1070 private $mNoUpdates = false;
1073 * @param Title $title
1074 * @throws MWException
1076 function setTitle( $title ) {
1077 if ( is_object( $title ) ) {
1078 $this->title
= $title;
1079 } elseif ( is_null( $title ) ) {
1080 throw new MWException( "WikiRevision given a null title in import. You may need to adjust \$wgLegalTitleChars." );
1082 throw new MWException( "WikiRevision given non-object title in import." );
1089 function setID( $id ) {
1096 function setTimestamp( $ts ) {
1097 # 2003-08-05T18:30:02Z
1098 $this->timestamp
= wfTimestamp( TS_MW
, $ts );
1102 * @param string $user
1104 function setUsername( $user ) {
1105 $this->user_text
= $user;
1111 function setUserIP( $ip ) {
1112 $this->user_text
= $ip;
1116 * @param string $model
1118 function setModel( $model ) {
1119 $this->model
= $model;
1123 * @param string $format
1125 function setFormat( $format ) {
1126 $this->format
= $format;
1130 * @param string $text
1132 function setText( $text ) {
1133 $this->text
= $text;
1137 * @param string $text
1139 function setComment( $text ) {
1140 $this->comment
= $text;
1144 * @param bool $minor
1146 function setMinor( $minor ) {
1147 $this->minor
= (bool)$minor;
1153 function setSrc( $src ) {
1158 * @param string $src
1159 * @param bool $isTemp
1161 function setFileSrc( $src, $isTemp ) {
1162 $this->fileSrc
= $src;
1163 $this->fileIsTemp
= $isTemp;
1167 * @param string $sha1base36
1169 function setSha1Base36( $sha1base36 ) {
1170 $this->sha1base36
= $sha1base36;
1174 * @param string $filename
1176 function setFilename( $filename ) {
1177 $this->filename
= $filename;
1181 * @param string $archiveName
1183 function setArchiveName( $archiveName ) {
1184 $this->archiveName
= $archiveName;
1190 function setSize( $size ) {
1191 $this->size
= intval( $size );
1195 * @param string $type
1197 function setType( $type ) {
1198 $this->type
= $type;
1202 * @param string $action
1204 function setAction( $action ) {
1205 $this->action
= $action;
1209 * @param array $params
1211 function setParams( $params ) {
1212 $this->params
= $params;
1216 * @param bool $noupdates
1218 public function setNoUpdates( $noupdates ) {
1219 $this->mNoUpdates
= $noupdates;
1225 function getTitle() {
1226 return $this->title
;
1239 function getTimestamp() {
1240 return $this->timestamp
;
1246 function getUser() {
1247 return $this->user_text
;
1253 * @deprecated Since 1.21, use getContent() instead.
1255 function getText() {
1256 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1264 function getContent() {
1265 if ( is_null( $this->content
) ) {
1267 ContentHandler
::makeContent(
1275 return $this->content
;
1281 function getModel() {
1282 if ( is_null( $this->model
) ) {
1283 $this->model
= $this->getTitle()->getContentModel();
1286 return $this->model
;
1292 function getFormat() {
1293 if ( is_null( $this->model
) ) {
1294 $this->format
= ContentHandler
::getForTitle( $this->getTitle() )->getDefaultFormat();
1297 return $this->format
;
1303 function getComment() {
1304 return $this->comment
;
1310 function getMinor() {
1311 return $this->minor
;
1322 * @return bool|string
1324 function getSha1() {
1325 if ( $this->sha1base36
) {
1326 return wfBaseConvert( $this->sha1base36
, 36, 16 );
1334 function getFileSrc() {
1335 return $this->fileSrc
;
1341 function isTempSrc() {
1342 return $this->isTemp
;
1348 function getFilename() {
1349 return $this->filename
;
1355 function getArchiveName() {
1356 return $this->archiveName
;
1362 function getSize() {
1369 function getType() {
1376 function getAction() {
1377 return $this->action
;
1383 function getParams() {
1384 return $this->params
;
1390 function importOldRevision() {
1391 $dbw = wfGetDB( DB_MASTER
);
1393 # Sneak a single revision into place
1394 $user = User
::newFromName( $this->getUser() );
1396 $userId = intval( $user->getId() );
1397 $userText = $user->getName();
1401 $userText = $this->getUser();
1402 $userObj = new User
;
1405 // avoid memory leak...?
1406 $linkCache = LinkCache
::singleton();
1407 $linkCache->clear();
1409 $page = WikiPage
::factory( $this->title
);
1410 if ( !$page->exists() ) {
1411 # must create the page...
1412 $pageId = $page->insertOn( $dbw );
1414 $oldcountable = null;
1416 $pageId = $page->getId();
1419 $prior = $dbw->selectField( 'revision', '1',
1420 array( 'rev_page' => $pageId,
1421 'rev_timestamp' => $dbw->timestamp( $this->timestamp
),
1422 'rev_user_text' => $userText,
1423 'rev_comment' => $this->getComment() ),
1427 // @todo FIXME: This could fail slightly for multiple matches :P
1428 wfDebug( __METHOD__
. ": skipping existing revision for [[" .
1429 $this->title
->getPrefixedText() . "]], timestamp " . $this->timestamp
. "\n" );
1432 $oldcountable = $page->isCountable();
1435 # @todo FIXME: Use original rev_id optionally (better for backups)
1437 $revision = new Revision( array(
1438 'title' => $this->title
,
1440 'content_model' => $this->getModel(),
1441 'content_format' => $this->getFormat(),
1442 'text' => $this->getContent()->serialize( $this->getFormat() ), //XXX: just set 'content' => $this->getContent()?
1443 'comment' => $this->getComment(),
1445 'user_text' => $userText,
1446 'timestamp' => $this->timestamp
,
1447 'minor_edit' => $this->minor
,
1449 $revision->insertOn( $dbw );
1450 $changed = $page->updateIfNewerOn( $dbw, $revision );
1452 if ( $changed !== false && !$this->mNoUpdates
) {
1453 wfDebug( __METHOD__
. ": running updates\n" );
1454 $page->doEditUpdates( $revision, $userObj, array( 'created' => $created, 'oldcountable' => $oldcountable ) );
1463 function importLogItem() {
1464 $dbw = wfGetDB( DB_MASTER
);
1465 # @todo FIXME: This will not record autoblocks
1466 if ( !$this->getTitle() ) {
1467 wfDebug( __METHOD__
. ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1468 $this->timestamp
. "\n" );
1471 # Check if it exists already
1472 // @todo FIXME: Use original log ID (better for backups)
1473 $prior = $dbw->selectField( 'logging', '1',
1474 array( 'log_type' => $this->getType(),
1475 'log_action' => $this->getAction(),
1476 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1477 'log_namespace' => $this->getTitle()->getNamespace(),
1478 'log_title' => $this->getTitle()->getDBkey(),
1479 'log_comment' => $this->getComment(),
1480 #'log_user_text' => $this->user_text,
1481 'log_params' => $this->params
),
1484 // @todo FIXME: This could fail slightly for multiple matches :P
1486 wfDebug( __METHOD__
. ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp " .
1487 $this->timestamp
. "\n" );
1490 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1492 'log_id' => $log_id,
1493 'log_type' => $this->type
,
1494 'log_action' => $this->action
,
1495 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1496 'log_user' => User
::idFromName( $this->user_text
),
1497 #'log_user_text' => $this->user_text,
1498 'log_namespace' => $this->getTitle()->getNamespace(),
1499 'log_title' => $this->getTitle()->getDBkey(),
1500 'log_comment' => $this->getComment(),
1501 'log_params' => $this->params
1503 $dbw->insert( 'logging', $data, __METHOD__
);
1509 function importUpload() {
1511 $archiveName = $this->getArchiveName();
1512 if ( $archiveName ) {
1513 wfDebug( __METHOD__
. "Importing archived file as $archiveName\n" );
1514 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1515 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1517 $file = wfLocalFile( $this->getTitle() );
1518 wfDebug( __METHOD__
. 'Importing new file as ' . $file->getName() . "\n" );
1519 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1520 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1521 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1522 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1523 wfDebug( __METHOD__
. "File already exists; importing as $archiveName\n" );
1527 wfDebug( __METHOD__
. ': Bad file for ' . $this->getTitle() . "\n" );
1531 # Get the file source or download if necessary
1532 $source = $this->getFileSrc();
1533 $flags = $this->isTempSrc() ? File
::DELETE_SOURCE
: 0;
1535 $source = $this->downloadSource();
1536 $flags |
= File
::DELETE_SOURCE
;
1539 wfDebug( __METHOD__
. ": Could not fetch remote file.\n" );
1542 $sha1 = $this->getSha1();
1543 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1544 if ( $flags & File
::DELETE_SOURCE
) {
1545 # Broken file; delete it if it is a temporary file
1548 wfDebug( __METHOD__
. ": Corrupt file $source.\n" );
1552 $user = User
::newFromName( $this->user_text
);
1554 # Do the actual upload
1555 if ( $archiveName ) {
1556 $status = $file->uploadOld( $source, $archiveName,
1557 $this->getTimestamp(), $this->getComment(), $user, $flags );
1559 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1560 $flags, false, $this->getTimestamp(), $user );
1563 if ( $status->isGood() ) {
1564 wfDebug( __METHOD__
. ": Successful\n" );
1567 wfDebug( __METHOD__
. ': failed: ' . $status->getXml() . "\n" );
1573 * @return bool|string
1575 function downloadSource() {
1576 global $wgEnableUploads;
1577 if ( !$wgEnableUploads ) {
1581 $tempo = tempnam( wfTempDir(), 'download' );
1582 $f = fopen( $tempo, 'wb' );
1584 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1589 $src = $this->getSrc();
1590 $data = Http
::get( $src );
1592 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1598 fwrite( $f, $data );
1607 * @todo document (e.g. one-sentence class description).
1608 * @ingroup SpecialPage
1610 class ImportStringSource
{
1611 function __construct( $string ) {
1612 $this->mString
= $string;
1613 $this->mRead
= false;
1620 return $this->mRead
;
1624 * @return bool|string
1626 function readChunk() {
1627 if ( $this->atEnd() ) {
1630 $this->mRead
= true;
1631 return $this->mString
;
1636 * @todo document (e.g. one-sentence class description).
1637 * @ingroup SpecialPage
1639 class ImportStreamSource
{
1640 function __construct( $handle ) {
1641 $this->mHandle
= $handle;
1648 return feof( $this->mHandle
);
1654 function readChunk() {
1655 return fread( $this->mHandle
, 32768 );
1659 * @param string $filename
1662 static function newFromFile( $filename ) {
1663 wfSuppressWarnings();
1664 $file = fopen( $filename, 'rt' );
1665 wfRestoreWarnings();
1667 return Status
::newFatal( "importcantopen" );
1669 return Status
::newGood( new ImportStreamSource( $file ) );
1673 * @param string $fieldname
1676 static function newFromUpload( $fieldname = "xmlimport" ) {
1677 $upload =& $_FILES[$fieldname];
1679 if ( $upload === null ||
!$upload['name'] ) {
1680 return Status
::newFatal( 'importnofile' );
1682 if ( !empty( $upload['error'] ) ) {
1683 switch ( $upload['error'] ) {
1684 case 1: # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1685 return Status
::newFatal( 'importuploaderrorsize' );
1686 case 2: # The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
1687 return Status
::newFatal( 'importuploaderrorsize' );
1688 case 3: # The uploaded file was only partially uploaded
1689 return Status
::newFatal( 'importuploaderrorpartial' );
1690 case 6: #Missing a temporary folder.
1691 return Status
::newFatal( 'importuploaderrortemp' );
1692 # case else: # Currently impossible
1696 $fname = $upload['tmp_name'];
1697 if ( is_uploaded_file( $fname ) ) {
1698 return ImportStreamSource
::newFromFile( $fname );
1700 return Status
::newFatal( 'importnofile' );
1705 * @param string $url
1706 * @param string $method
1709 static function newFromURL( $url, $method = 'GET' ) {
1710 wfDebug( __METHOD__
. ": opening $url\n" );
1711 # Use the standard HTTP fetch function; it times out
1712 # quicker and sorts out user-agent problems which might
1713 # otherwise prevent importing from large sites, such
1714 # as the Wikimedia cluster, etc.
1715 $data = Http
::request( $method, $url, array( 'followRedirects' => true ) );
1716 if ( $data !== false ) {
1718 fwrite( $file, $data );
1721 return Status
::newGood( new ImportStreamSource( $file ) );
1723 return Status
::newFatal( 'importcantopen' );
1728 * @param string $interwiki
1729 * @param string $page
1730 * @param bool $history
1731 * @param bool $templates
1732 * @param int $pageLinkDepth
1735 public static function newFromInterwiki( $interwiki, $page, $history = false, $templates = false, $pageLinkDepth = 0 ) {
1736 if ( $page == '' ) {
1737 return Status
::newFatal( 'import-noarticle' );
1739 $link = Title
::newFromText( "$interwiki:Special:Export/$page" );
1740 if ( is_null( $link ) ||
!$link->isExternal() ) {
1741 return Status
::newFatal( 'importbadinterwiki' );
1745 $params['history'] = 1;
1748 $params['templates'] = 1;
1750 if ( $pageLinkDepth ) {
1751 $params['pagelink-depth'] = $pageLinkDepth;
1753 $url = $link->getFullURL( $params );
1754 # For interwikis, use POST to avoid redirects.
1755 return ImportStreamSource
::newFromURL( $url, "POST" );