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' ) );
63 private function throwXmlError( $err ) {
64 $this->debug( "FAILURE: $err" );
65 wfDebug( "WikiImporter XML error: $err\n" );
68 private function debug( $data ) {
69 if ( $this->mDebug
) {
70 wfDebug( "IMPORT: $data\n" );
74 private function warn( $data ) {
75 wfDebug( "IMPORT: $data\n" );
78 private function notice( $msg /*, $param, ...*/ ) {
79 $params = func_get_args();
80 array_shift( $params );
82 if ( is_callable( $this->mNoticeCallback
) ) {
83 call_user_func( $this->mNoticeCallback
, $msg, $params );
84 } else { # No ImportReporter -> CLI
85 echo wfMessage( $msg, $params )->text() . "\n";
93 function setDebug( $debug ) {
94 $this->mDebug
= $debug;
98 * Set 'no updates' mode. In this mode, the link tables will not be updated by the importer
99 * @param bool $noupdates
101 function setNoUpdates( $noupdates ) {
102 $this->mNoUpdates
= $noupdates;
106 * Set a callback that displays notice messages
108 * @param callable $callback
111 public function setNoticeCallback( $callback ) {
112 return wfSetVar( $this->mNoticeCallback
, $callback );
116 * Sets the action to perform as each new page in the stream is reached.
117 * @param callable $callback
120 public function setPageCallback( $callback ) {
121 $previous = $this->mPageCallback
;
122 $this->mPageCallback
= $callback;
127 * Sets the action to perform as each page in the stream is completed.
128 * Callback accepts the page title (as a Title object), a second object
129 * with the original title form (in case it's been overridden into a
130 * local namespace), and a count of revisions.
132 * @param callable $callback
135 public function setPageOutCallback( $callback ) {
136 $previous = $this->mPageOutCallback
;
137 $this->mPageOutCallback
= $callback;
142 * Sets the action to perform as each page revision is reached.
143 * @param callable $callback
146 public function setRevisionCallback( $callback ) {
147 $previous = $this->mRevisionCallback
;
148 $this->mRevisionCallback
= $callback;
153 * Sets the action to perform as each file upload version is reached.
154 * @param callable $callback
157 public function setUploadCallback( $callback ) {
158 $previous = $this->mUploadCallback
;
159 $this->mUploadCallback
= $callback;
164 * Sets the action to perform as each log item reached.
165 * @param callable $callback
168 public function setLogItemCallback( $callback ) {
169 $previous = $this->mLogItemCallback
;
170 $this->mLogItemCallback
= $callback;
175 * Sets the action to perform when site info is encountered
176 * @param callable $callback
179 public function setSiteInfoCallback( $callback ) {
180 $previous = $this->mSiteInfoCallback
;
181 $this->mSiteInfoCallback
= $callback;
186 * Set a target namespace to override the defaults
187 * @param null|int $namespace
190 public function setTargetNamespace( $namespace ) {
191 if ( is_null( $namespace ) ) {
192 // Don't override namespaces
193 $this->mTargetNamespace
= null;
194 } elseif ( $namespace >= 0 ) {
195 // @todo FIXME: Check for validity
196 $this->mTargetNamespace
= intval( $namespace );
203 * Set a target root page under which all pages are imported
204 * @param null|string $rootpage
207 public function setTargetRootPage( $rootpage ) {
208 $status = Status
::newGood();
209 if ( is_null( $rootpage ) ) {
211 $this->mTargetRootPage
= null;
212 } elseif ( $rootpage !== '' ) {
213 $rootpage = rtrim( $rootpage, '/' ); //avoid double slashes
214 $title = Title
::newFromText( $rootpage, !is_null( $this->mTargetNamespace
) ?
$this->mTargetNamespace
: NS_MAIN
);
215 if ( !$title ||
$title->isExternal() ) {
216 $status->fatal( 'import-rootpage-invalid' );
218 if ( !MWNamespace
::hasSubpages( $title->getNamespace() ) ) {
221 $displayNSText = $title->getNamespace() == NS_MAIN
222 ?
wfMessage( 'blanknamespace' )->text()
223 : $wgContLang->getNsText( $title->getNamespace() );
224 $status->fatal( 'import-rootpage-nosubpage', $displayNSText );
226 // set namespace to 'all', so the namespace check in processTitle() can passed
227 $this->setTargetNamespace( null );
228 $this->mTargetRootPage
= $title->getPrefixedDBkey();
238 public function setImageBasePath( $dir ) {
239 $this->mImageBasePath
= $dir;
243 * @param bool $import
245 public function setImportUploads( $import ) {
246 $this->mImportUploads
= $import;
250 * Default per-revision callback, performs the import.
251 * @param WikiRevision $revision
254 public function importRevision( $revision ) {
255 if ( !$revision->getContent()->getContentHandler()->canBeUsedOn( $revision->getTitle() ) ) {
256 $this->notice( 'import-error-bad-location',
257 $revision->getTitle()->getPrefixedText(),
259 $revision->getModel(),
260 $revision->getFormat() );
266 $dbw = wfGetDB( DB_MASTER
);
267 return $dbw->deadlockLoop( array( $revision, 'importOldRevision' ) );
268 } catch ( MWContentSerializationException
$ex ) {
269 $this->notice( 'import-error-unserialize',
270 $revision->getTitle()->getPrefixedText(),
272 $revision->getModel(),
273 $revision->getFormat() );
280 * Default per-revision callback, performs the import.
281 * @param WikiRevision $rev
284 public function importLogItem( $rev ) {
285 $dbw = wfGetDB( DB_MASTER
);
286 return $dbw->deadlockLoop( array( $rev, 'importLogItem' ) );
291 * @param WikiRevision $revision
294 public function importUpload( $revision ) {
295 $dbw = wfGetDB( DB_MASTER
);
296 return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
300 * Mostly for hook use
301 * @param Title $title
302 * @param string $origTitle
303 * @param int $revCount
304 * @param int $sRevCount
305 * @param array $pageInfo
308 public function finishImportPage( $title, $origTitle, $revCount, $sRevCount, $pageInfo ) {
309 $args = func_get_args();
310 return wfRunHooks( 'AfterImportPage', $args );
314 * Alternate per-revision callback, for debugging.
315 * @param WikiRevision $revision
317 public function debugRevisionHandler( &$revision ) {
318 $this->debug( "Got revision:" );
319 if ( is_object( $revision->title
) ) {
320 $this->debug( "-- Title: " . $revision->title
->getPrefixedText() );
322 $this->debug( "-- Title: <invalid>" );
324 $this->debug( "-- User: " . $revision->user_text
);
325 $this->debug( "-- Timestamp: " . $revision->timestamp
);
326 $this->debug( "-- Comment: " . $revision->comment
);
327 $this->debug( "-- Text: " . $revision->text
);
331 * Notify the callback function when a new "<page>" is reached.
332 * @param Title $title
334 function pageCallback( $title ) {
335 if ( isset( $this->mPageCallback
) ) {
336 call_user_func( $this->mPageCallback
, $title );
341 * Notify the callback function when a "</page>" is closed.
342 * @param Title $title
343 * @param Title $origTitle
344 * @param int $revCount
345 * @param int $sucCount Number of revisions for which callback returned true
346 * @param array $pageInfo Associative array of page information
348 private function pageOutCallback( $title, $origTitle, $revCount, $sucCount, $pageInfo ) {
349 if ( isset( $this->mPageOutCallback
) ) {
350 $args = func_get_args();
351 call_user_func_array( $this->mPageOutCallback
, $args );
356 * Notify the callback function of a revision
357 * @param WikiRevision $revision
360 private function revisionCallback( $revision ) {
361 if ( isset( $this->mRevisionCallback
) ) {
362 return call_user_func_array( $this->mRevisionCallback
,
363 array( $revision, $this ) );
370 * Notify the callback function of a new log item
371 * @param WikiRevision $revision
374 private function logItemCallback( $revision ) {
375 if ( isset( $this->mLogItemCallback
) ) {
376 return call_user_func_array( $this->mLogItemCallback
,
377 array( $revision, $this ) );
384 * Shouldn't something like this be built-in to XMLReader?
385 * Fetches text contents of the current element, assuming
386 * no sub-elements or such scary things.
390 private function nodeContents() {
391 if ( $this->reader
->isEmptyElement
) {
395 while ( $this->reader
->read() ) {
396 switch ( $this->reader
->nodeType
) {
397 case XmlReader
::TEXT
:
398 case XmlReader
::SIGNIFICANT_WHITESPACE
:
399 $buffer .= $this->reader
->value
;
401 case XmlReader
::END_ELEMENT
:
406 $this->reader
->close();
412 /** Left in for debugging */
413 private function dumpElement() {
414 static $lookup = null;
416 $xmlReaderConstants = array(
431 "SIGNIFICANT_WHITESPACE",
438 foreach ( $xmlReaderConstants as $name ) {
439 $lookup[constant( "XmlReader::$name" )] = $name;
444 $lookup[$this->reader
->nodeType
],
451 * Primary entry point
452 * @throws MWException
455 public function doImport() {
457 // Calls to reader->read need to be wrapped in calls to
458 // libxml_disable_entity_loader() to avoid local file
459 // inclusion attacks (bug 46932).
460 $oldDisable = libxml_disable_entity_loader( true );
461 $this->reader
->read();
463 if ( $this->reader
->name
!= 'mediawiki' ) {
464 libxml_disable_entity_loader( $oldDisable );
465 throw new MWException( "Expected <mediawiki> tag, got " .
466 $this->reader
->name
);
468 $this->debug( "<mediawiki> tag is correct." );
470 $this->debug( "Starting primary dump processing loop." );
472 $keepReading = $this->reader
->read();
474 while ( $keepReading ) {
475 $tag = $this->reader
->name
;
476 $type = $this->reader
->nodeType
;
478 if ( !wfRunHooks( 'ImportHandleToplevelXMLTag', array( $this ) ) ) {
480 } elseif ( $tag == 'mediawiki' && $type == XmlReader
::END_ELEMENT
) {
482 } elseif ( $tag == 'siteinfo' ) {
483 $this->handleSiteInfo();
484 } elseif ( $tag == 'page' ) {
486 } elseif ( $tag == 'logitem' ) {
487 $this->handleLogItem();
488 } elseif ( $tag != '#text' ) {
489 $this->warn( "Unhandled top-level XML tag $tag" );
495 $keepReading = $this->reader
->next();
497 $this->debug( "Skip" );
499 $keepReading = $this->reader
->read();
503 libxml_disable_entity_loader( $oldDisable );
509 * @throws MWException
511 private function handleSiteInfo() {
512 // Site info is useful, but not actually used for dump imports.
513 // Includes a quick short-circuit to save performance.
514 if ( ! $this->mSiteInfoCallback
) {
515 $this->reader
->next();
518 throw new MWException( "SiteInfo tag is not yet handled, do not set mSiteInfoCallback" );
521 private function handleLogItem() {
522 $this->debug( "Enter log item handler." );
525 // Fields that can just be stuffed in the pageInfo object
526 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
527 'logtitle', 'params' );
529 while ( $this->reader
->read() ) {
530 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
531 $this->reader
->name
== 'logitem' ) {
535 $tag = $this->reader
->name
;
537 if ( !wfRunHooks( 'ImportHandleLogItemXMLTag', array(
541 } elseif ( in_array( $tag, $normalFields ) ) {
542 $logInfo[$tag] = $this->nodeContents();
543 } elseif ( $tag == 'contributor' ) {
544 $logInfo['contributor'] = $this->handleContributor();
545 } elseif ( $tag != '#text' ) {
546 $this->warn( "Unhandled log-item XML tag $tag" );
550 $this->processLogItem( $logInfo );
554 * @param array $logInfo
557 private function processLogItem( $logInfo ) {
558 $revision = new WikiRevision
;
560 $revision->setID( $logInfo['id'] );
561 $revision->setType( $logInfo['type'] );
562 $revision->setAction( $logInfo['action'] );
563 $revision->setTimestamp( $logInfo['timestamp'] );
564 $revision->setParams( $logInfo['params'] );
565 $revision->setTitle( Title
::newFromText( $logInfo['logtitle'] ) );
566 $revision->setNoUpdates( $this->mNoUpdates
);
568 if ( isset( $logInfo['comment'] ) ) {
569 $revision->setComment( $logInfo['comment'] );
572 if ( isset( $logInfo['contributor']['ip'] ) ) {
573 $revision->setUserIP( $logInfo['contributor']['ip'] );
575 if ( isset( $logInfo['contributor']['username'] ) ) {
576 $revision->setUserName( $logInfo['contributor']['username'] );
579 return $this->logItemCallback( $revision );
582 private function handlePage() {
584 $this->debug( "Enter page handler." );
585 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
587 // Fields that can just be stuffed in the pageInfo object
588 $normalFields = array( 'title', 'id', 'redirect', 'restrictions' );
593 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
594 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
595 $this->reader
->name
== 'page' ) {
599 $tag = $this->reader
->name
;
602 // The title is invalid, bail out of this page
604 } elseif ( !wfRunHooks( 'ImportHandlePageXMLTag', array( $this,
607 } elseif ( in_array( $tag, $normalFields ) ) {
608 $pageInfo[$tag] = $this->nodeContents();
609 if ( $tag == 'title' ) {
610 $title = $this->processTitle( $pageInfo['title'] );
617 $this->pageCallback( $title );
618 list( $pageInfo['_title'], $origTitle ) = $title;
620 } elseif ( $tag == 'revision' ) {
621 $this->handleRevision( $pageInfo );
622 } elseif ( $tag == 'upload' ) {
623 $this->handleUpload( $pageInfo );
624 } elseif ( $tag != '#text' ) {
625 $this->warn( "Unhandled page XML tag $tag" );
630 $this->pageOutCallback( $pageInfo['_title'], $origTitle,
631 $pageInfo['revisionCount'],
632 $pageInfo['successfulRevisionCount'],
637 * @param array $pageInfo
639 private function handleRevision( &$pageInfo ) {
640 $this->debug( "Enter revision handler" );
641 $revisionInfo = array();
643 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'model', 'format', 'text' );
647 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
648 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
649 $this->reader
->name
== 'revision' ) {
653 $tag = $this->reader
->name
;
655 if ( !wfRunHooks( 'ImportHandleRevisionXMLTag', array(
656 $this, $pageInfo, $revisionInfo
659 } elseif ( in_array( $tag, $normalFields ) ) {
660 $revisionInfo[$tag] = $this->nodeContents();
661 } elseif ( $tag == 'contributor' ) {
662 $revisionInfo['contributor'] = $this->handleContributor();
663 } elseif ( $tag != '#text' ) {
664 $this->warn( "Unhandled revision XML tag $tag" );
669 $pageInfo['revisionCount']++
;
670 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
671 $pageInfo['successfulRevisionCount']++
;
676 * @param array $pageInfo
677 * @param array $revisionInfo
680 private function processRevision( $pageInfo, $revisionInfo ) {
681 $revision = new WikiRevision
;
683 if ( isset( $revisionInfo['id'] ) ) {
684 $revision->setID( $revisionInfo['id'] );
686 if ( isset( $revisionInfo['text'] ) ) {
687 $revision->setText( $revisionInfo['text'] );
689 if ( isset( $revisionInfo['model'] ) ) {
690 $revision->setModel( $revisionInfo['model'] );
692 if ( isset( $revisionInfo['format'] ) ) {
693 $revision->setFormat( $revisionInfo['format'] );
695 $revision->setTitle( $pageInfo['_title'] );
697 if ( isset( $revisionInfo['timestamp'] ) ) {
698 $revision->setTimestamp( $revisionInfo['timestamp'] );
700 $revision->setTimestamp( wfTimestampNow() );
703 if ( isset( $revisionInfo['comment'] ) ) {
704 $revision->setComment( $revisionInfo['comment'] );
707 if ( isset( $revisionInfo['minor'] ) ) {
708 $revision->setMinor( true );
710 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
711 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
713 if ( isset( $revisionInfo['contributor']['username'] ) ) {
714 $revision->setUserName( $revisionInfo['contributor']['username'] );
716 $revision->setNoUpdates( $this->mNoUpdates
);
718 return $this->revisionCallback( $revision );
722 * @param array $pageInfo
725 private function handleUpload( &$pageInfo ) {
726 $this->debug( "Enter upload handler" );
727 $uploadInfo = array();
729 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
730 'src', 'size', 'sha1base36', 'archivename', 'rel' );
734 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
735 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
736 $this->reader
->name
== 'upload' ) {
740 $tag = $this->reader
->name
;
742 if ( !wfRunHooks( 'ImportHandleUploadXMLTag', array(
746 } elseif ( in_array( $tag, $normalFields ) ) {
747 $uploadInfo[$tag] = $this->nodeContents();
748 } elseif ( $tag == 'contributor' ) {
749 $uploadInfo['contributor'] = $this->handleContributor();
750 } elseif ( $tag == 'contents' ) {
751 $contents = $this->nodeContents();
752 $encoding = $this->reader
->getAttribute( 'encoding' );
753 if ( $encoding === 'base64' ) {
754 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
755 $uploadInfo['isTempSrc'] = true;
757 } elseif ( $tag != '#text' ) {
758 $this->warn( "Unhandled upload XML tag $tag" );
763 if ( $this->mImageBasePath
&& isset( $uploadInfo['rel'] ) ) {
764 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
765 if ( file_exists( $path ) ) {
766 $uploadInfo['fileSrc'] = $path;
767 $uploadInfo['isTempSrc'] = false;
771 if ( $this->mImportUploads
) {
772 return $this->processUpload( $pageInfo, $uploadInfo );
777 * @param string $contents
780 private function dumpTemp( $contents ) {
781 $filename = tempnam( wfTempDir(), 'importupload' );
782 file_put_contents( $filename, $contents );
787 * @param array $pageInfo
788 * @param array $uploadInfo
791 private function processUpload( $pageInfo, $uploadInfo ) {
792 $revision = new WikiRevision
;
793 $text = isset( $uploadInfo['text'] ) ?
$uploadInfo['text'] : '';
795 $revision->setTitle( $pageInfo['_title'] );
796 $revision->setID( $pageInfo['id'] );
797 $revision->setTimestamp( $uploadInfo['timestamp'] );
798 $revision->setText( $text );
799 $revision->setFilename( $uploadInfo['filename'] );
800 if ( isset( $uploadInfo['archivename'] ) ) {
801 $revision->setArchiveName( $uploadInfo['archivename'] );
803 $revision->setSrc( $uploadInfo['src'] );
804 if ( isset( $uploadInfo['fileSrc'] ) ) {
805 $revision->setFileSrc( $uploadInfo['fileSrc'],
806 !empty( $uploadInfo['isTempSrc'] ) );
808 if ( isset( $uploadInfo['sha1base36'] ) ) {
809 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
811 $revision->setSize( intval( $uploadInfo['size'] ) );
812 $revision->setComment( $uploadInfo['comment'] );
814 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
815 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
817 if ( isset( $uploadInfo['contributor']['username'] ) ) {
818 $revision->setUserName( $uploadInfo['contributor']['username'] );
820 $revision->setNoUpdates( $this->mNoUpdates
);
822 return call_user_func( $this->mUploadCallback
, $revision );
828 private function handleContributor() {
829 $fields = array( 'id', 'ip', 'username' );
832 while ( $this->reader
->read() ) {
833 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
834 $this->reader
->name
== 'contributor' ) {
838 $tag = $this->reader
->name
;
840 if ( in_array( $tag, $fields ) ) {
841 $info[$tag] = $this->nodeContents();
849 * @param string $text
852 private function processTitle( $text ) {
853 global $wgCommandLineMode;
856 $origTitle = Title
::newFromText( $workTitle );
858 if ( !is_null( $this->mTargetNamespace
) && !is_null( $origTitle ) ) {
859 # makeTitleSafe, because $origTitle can have a interwiki (different setting of interwiki map)
860 # and than dbKey can begin with a lowercase char
861 $title = Title
::makeTitleSafe( $this->mTargetNamespace
,
862 $origTitle->getDBkey() );
864 if ( !is_null( $this->mTargetRootPage
) ) {
865 $workTitle = $this->mTargetRootPage
. '/' . $workTitle;
867 $title = Title
::newFromText( $workTitle );
870 if ( is_null( $title ) ) {
871 # Invalid page title? Ignore the page
872 $this->notice( 'import-error-invalid', $workTitle );
874 } elseif ( $title->isExternal() ) {
875 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
877 } elseif ( !$title->canExist() ) {
878 $this->notice( 'import-error-special', $title->getPrefixedText() );
880 } elseif ( !$title->userCan( 'edit' ) && !$wgCommandLineMode ) {
881 # Do not import if the importing wiki user cannot edit this page
882 $this->notice( 'import-error-edit', $title->getPrefixedText() );
884 } elseif ( !$title->exists() && !$title->userCan( 'create' ) && !$wgCommandLineMode ) {
885 # Do not import if the importing wiki user cannot create this page
886 $this->notice( 'import-error-create', $title->getPrefixedText() );
890 return array( $title, $origTitle );
894 /** This is a horrible hack used to keep source compatibility */
895 class UploadSourceAdapter
{
896 static $sourceRegistrations = array();
903 * @param string $source
906 static function registerSource( $source ) {
907 $id = wfRandomString();
909 self
::$sourceRegistrations[$id] = $source;
915 * @param string $path
916 * @param string $mode
917 * @param array $options
918 * @param string $opened_path
921 function stream_open( $path, $mode, $options, &$opened_path ) {
922 $url = parse_url( $path );
925 if ( !isset( self
::$sourceRegistrations[$id] ) ) {
929 $this->mSource
= self
::$sourceRegistrations[$id];
938 function stream_read( $count ) {
942 while ( !$leave && !$this->mSource
->atEnd() &&
943 strlen( $this->mBuffer
) < $count ) {
944 $read = $this->mSource
->readChunk();
946 if ( !strlen( $read ) ) {
950 $this->mBuffer
.= $read;
953 if ( strlen( $this->mBuffer
) ) {
954 $return = substr( $this->mBuffer
, 0, $count );
955 $this->mBuffer
= substr( $this->mBuffer
, $count );
958 $this->mPosition +
= strlen( $return );
964 * @param string $data
967 function stream_write( $data ) {
974 function stream_tell() {
975 return $this->mPosition
;
981 function stream_eof() {
982 return $this->mSource
->atEnd();
988 function url_stat() {
991 $result['dev'] = $result[0] = 0;
992 $result['ino'] = $result[1] = 0;
993 $result['mode'] = $result[2] = 0;
994 $result['nlink'] = $result[3] = 0;
995 $result['uid'] = $result[4] = 0;
996 $result['gid'] = $result[5] = 0;
997 $result['rdev'] = $result[6] = 0;
998 $result['size'] = $result[7] = 0;
999 $result['atime'] = $result[8] = 0;
1000 $result['mtime'] = $result[9] = 0;
1001 $result['ctime'] = $result[10] = 0;
1002 $result['blksize'] = $result[11] = 0;
1003 $result['blocks'] = $result[12] = 0;
1009 class XMLReader2
extends XMLReader
{
1012 * @return bool|string
1014 function nodeContents() {
1015 if ( $this->isEmptyElement
) {
1019 while ( $this->read() ) {
1020 switch ( $this->nodeType
) {
1021 case XmlReader
::TEXT
:
1022 case XmlReader
::SIGNIFICANT_WHITESPACE
:
1023 $buffer .= $this->value
;
1025 case XmlReader
::END_ELEMENT
:
1029 return $this->close();
1034 * @todo document (e.g. one-sentence class description).
1035 * @ingroup SpecialPage
1037 class WikiRevision
{
1038 var $importer = null;
1045 var $timestamp = "20010115000000";
1047 var $user_text = "";
1051 var $content = null;
1058 var $sha1base36 = false;
1059 var $isTemp = false;
1060 var $archiveName = '';
1062 private $mNoUpdates = false;
1065 * @param Title $title
1066 * @throws MWException
1068 function setTitle( $title ) {
1069 if ( is_object( $title ) ) {
1070 $this->title
= $title;
1071 } elseif ( is_null( $title ) ) {
1072 throw new MWException( "WikiRevision given a null title in import. You may need to adjust \$wgLegalTitleChars." );
1074 throw new MWException( "WikiRevision given non-object title in import." );
1081 function setID( $id ) {
1088 function setTimestamp( $ts ) {
1089 # 2003-08-05T18:30:02Z
1090 $this->timestamp
= wfTimestamp( TS_MW
, $ts );
1094 * @param string $user
1096 function setUsername( $user ) {
1097 $this->user_text
= $user;
1103 function setUserIP( $ip ) {
1104 $this->user_text
= $ip;
1108 * @param string $model
1110 function setModel( $model ) {
1111 $this->model
= $model;
1115 * @param string $format
1117 function setFormat( $format ) {
1118 $this->format
= $format;
1122 * @param string $text
1124 function setText( $text ) {
1125 $this->text
= $text;
1129 * @param string $text
1131 function setComment( $text ) {
1132 $this->comment
= $text;
1136 * @param bool $minor
1138 function setMinor( $minor ) {
1139 $this->minor
= (bool)$minor;
1145 function setSrc( $src ) {
1150 * @param string $src
1151 * @param bool $isTemp
1153 function setFileSrc( $src, $isTemp ) {
1154 $this->fileSrc
= $src;
1155 $this->fileIsTemp
= $isTemp;
1159 * @param string $sha1base36
1161 function setSha1Base36( $sha1base36 ) {
1162 $this->sha1base36
= $sha1base36;
1166 * @param string $filename
1168 function setFilename( $filename ) {
1169 $this->filename
= $filename;
1173 * @param string $archiveName
1175 function setArchiveName( $archiveName ) {
1176 $this->archiveName
= $archiveName;
1182 function setSize( $size ) {
1183 $this->size
= intval( $size );
1187 * @param string $type
1189 function setType( $type ) {
1190 $this->type
= $type;
1194 * @param string $action
1196 function setAction( $action ) {
1197 $this->action
= $action;
1201 * @param array $params
1203 function setParams( $params ) {
1204 $this->params
= $params;
1208 * @param bool $noupdates
1210 public function setNoUpdates( $noupdates ) {
1211 $this->mNoUpdates
= $noupdates;
1217 function getTitle() {
1218 return $this->title
;
1231 function getTimestamp() {
1232 return $this->timestamp
;
1238 function getUser() {
1239 return $this->user_text
;
1245 * @deprecated Since 1.21, use getContent() instead.
1247 function getText() {
1248 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1256 function getContent() {
1257 if ( is_null( $this->content
) ) {
1259 ContentHandler
::makeContent(
1267 return $this->content
;
1273 function getModel() {
1274 if ( is_null( $this->model
) ) {
1275 $this->model
= $this->getTitle()->getContentModel();
1278 return $this->model
;
1284 function getFormat() {
1285 if ( is_null( $this->model
) ) {
1286 $this->format
= ContentHandler
::getForTitle( $this->getTitle() )->getDefaultFormat();
1289 return $this->format
;
1295 function getComment() {
1296 return $this->comment
;
1302 function getMinor() {
1303 return $this->minor
;
1314 * @return bool|string
1316 function getSha1() {
1317 if ( $this->sha1base36
) {
1318 return wfBaseConvert( $this->sha1base36
, 36, 16 );
1326 function getFileSrc() {
1327 return $this->fileSrc
;
1333 function isTempSrc() {
1334 return $this->isTemp
;
1340 function getFilename() {
1341 return $this->filename
;
1347 function getArchiveName() {
1348 return $this->archiveName
;
1354 function getSize() {
1361 function getType() {
1368 function getAction() {
1369 return $this->action
;
1375 function getParams() {
1376 return $this->params
;
1382 function importOldRevision() {
1383 $dbw = wfGetDB( DB_MASTER
);
1385 # Sneak a single revision into place
1386 $user = User
::newFromName( $this->getUser() );
1388 $userId = intval( $user->getId() );
1389 $userText = $user->getName();
1393 $userText = $this->getUser();
1394 $userObj = new User
;
1397 // avoid memory leak...?
1398 $linkCache = LinkCache
::singleton();
1399 $linkCache->clear();
1401 $page = WikiPage
::factory( $this->title
);
1402 if ( !$page->exists() ) {
1403 # must create the page...
1404 $pageId = $page->insertOn( $dbw );
1406 $oldcountable = null;
1408 $pageId = $page->getId();
1411 $prior = $dbw->selectField( 'revision', '1',
1412 array( 'rev_page' => $pageId,
1413 'rev_timestamp' => $dbw->timestamp( $this->timestamp
),
1414 'rev_user_text' => $userText,
1415 'rev_comment' => $this->getComment() ),
1419 // @todo FIXME: This could fail slightly for multiple matches :P
1420 wfDebug( __METHOD__
. ": skipping existing revision for [[" .
1421 $this->title
->getPrefixedText() . "]], timestamp " . $this->timestamp
. "\n" );
1424 $oldcountable = $page->isCountable();
1427 # @todo FIXME: Use original rev_id optionally (better for backups)
1429 $revision = new Revision( array(
1430 'title' => $this->title
,
1432 'content_model' => $this->getModel(),
1433 'content_format' => $this->getFormat(),
1434 'text' => $this->getContent()->serialize( $this->getFormat() ), //XXX: just set 'content' => $this->getContent()?
1435 'comment' => $this->getComment(),
1437 'user_text' => $userText,
1438 'timestamp' => $this->timestamp
,
1439 'minor_edit' => $this->minor
,
1441 $revision->insertOn( $dbw );
1442 $changed = $page->updateIfNewerOn( $dbw, $revision );
1444 if ( $changed !== false && !$this->mNoUpdates
) {
1445 wfDebug( __METHOD__
. ": running updates\n" );
1446 $page->doEditUpdates( $revision, $userObj, array( 'created' => $created, 'oldcountable' => $oldcountable ) );
1455 function importLogItem() {
1456 $dbw = wfGetDB( DB_MASTER
);
1457 # @todo FIXME: This will not record autoblocks
1458 if ( !$this->getTitle() ) {
1459 wfDebug( __METHOD__
. ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1460 $this->timestamp
. "\n" );
1463 # Check if it exists already
1464 // @todo FIXME: Use original log ID (better for backups)
1465 $prior = $dbw->selectField( 'logging', '1',
1466 array( 'log_type' => $this->getType(),
1467 'log_action' => $this->getAction(),
1468 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1469 'log_namespace' => $this->getTitle()->getNamespace(),
1470 'log_title' => $this->getTitle()->getDBkey(),
1471 'log_comment' => $this->getComment(),
1472 #'log_user_text' => $this->user_text,
1473 'log_params' => $this->params
),
1476 // @todo FIXME: This could fail slightly for multiple matches :P
1478 wfDebug( __METHOD__
. ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp " .
1479 $this->timestamp
. "\n" );
1482 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1484 'log_id' => $log_id,
1485 'log_type' => $this->type
,
1486 'log_action' => $this->action
,
1487 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1488 'log_user' => User
::idFromName( $this->user_text
),
1489 #'log_user_text' => $this->user_text,
1490 'log_namespace' => $this->getTitle()->getNamespace(),
1491 'log_title' => $this->getTitle()->getDBkey(),
1492 'log_comment' => $this->getComment(),
1493 'log_params' => $this->params
1495 $dbw->insert( 'logging', $data, __METHOD__
);
1501 function importUpload() {
1503 $archiveName = $this->getArchiveName();
1504 if ( $archiveName ) {
1505 wfDebug( __METHOD__
. "Importing archived file as $archiveName\n" );
1506 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1507 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1509 $file = wfLocalFile( $this->getTitle() );
1510 wfDebug( __METHOD__
. 'Importing new file as ' . $file->getName() . "\n" );
1511 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1512 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1513 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1514 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1515 wfDebug( __METHOD__
. "File already exists; importing as $archiveName\n" );
1519 wfDebug( __METHOD__
. ': Bad file for ' . $this->getTitle() . "\n" );
1523 # Get the file source or download if necessary
1524 $source = $this->getFileSrc();
1525 $flags = $this->isTempSrc() ? File
::DELETE_SOURCE
: 0;
1527 $source = $this->downloadSource();
1528 $flags |
= File
::DELETE_SOURCE
;
1531 wfDebug( __METHOD__
. ": Could not fetch remote file.\n" );
1534 $sha1 = $this->getSha1();
1535 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1536 if ( $flags & File
::DELETE_SOURCE
) {
1537 # Broken file; delete it if it is a temporary file
1540 wfDebug( __METHOD__
. ": Corrupt file $source.\n" );
1544 $user = User
::newFromName( $this->user_text
);
1546 # Do the actual upload
1547 if ( $archiveName ) {
1548 $status = $file->uploadOld( $source, $archiveName,
1549 $this->getTimestamp(), $this->getComment(), $user, $flags );
1551 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1552 $flags, false, $this->getTimestamp(), $user );
1555 if ( $status->isGood() ) {
1556 wfDebug( __METHOD__
. ": Successful\n" );
1559 wfDebug( __METHOD__
. ': failed: ' . $status->getXml() . "\n" );
1565 * @return bool|string
1567 function downloadSource() {
1568 global $wgEnableUploads;
1569 if ( !$wgEnableUploads ) {
1573 $tempo = tempnam( wfTempDir(), 'download' );
1574 $f = fopen( $tempo, 'wb' );
1576 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1581 $src = $this->getSrc();
1582 $data = Http
::get( $src );
1584 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1590 fwrite( $f, $data );
1599 * @todo document (e.g. one-sentence class description).
1600 * @ingroup SpecialPage
1602 class ImportStringSource
{
1603 function __construct( $string ) {
1604 $this->mString
= $string;
1605 $this->mRead
= false;
1612 return $this->mRead
;
1616 * @return bool|string
1618 function readChunk() {
1619 if ( $this->atEnd() ) {
1622 $this->mRead
= true;
1623 return $this->mString
;
1628 * @todo document (e.g. one-sentence class description).
1629 * @ingroup SpecialPage
1631 class ImportStreamSource
{
1632 function __construct( $handle ) {
1633 $this->mHandle
= $handle;
1640 return feof( $this->mHandle
);
1646 function readChunk() {
1647 return fread( $this->mHandle
, 32768 );
1651 * @param string $filename
1654 static function newFromFile( $filename ) {
1655 wfSuppressWarnings();
1656 $file = fopen( $filename, 'rt' );
1657 wfRestoreWarnings();
1659 return Status
::newFatal( "importcantopen" );
1661 return Status
::newGood( new ImportStreamSource( $file ) );
1665 * @param string $fieldname
1668 static function newFromUpload( $fieldname = "xmlimport" ) {
1669 $upload =& $_FILES[$fieldname];
1671 if ( $upload === null ||
!$upload['name'] ) {
1672 return Status
::newFatal( 'importnofile' );
1674 if ( !empty( $upload['error'] ) ) {
1675 switch ( $upload['error'] ) {
1676 case 1: # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1677 return Status
::newFatal( 'importuploaderrorsize' );
1678 case 2: # The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
1679 return Status
::newFatal( 'importuploaderrorsize' );
1680 case 3: # The uploaded file was only partially uploaded
1681 return Status
::newFatal( 'importuploaderrorpartial' );
1682 case 6: #Missing a temporary folder.
1683 return Status
::newFatal( 'importuploaderrortemp' );
1684 # case else: # Currently impossible
1688 $fname = $upload['tmp_name'];
1689 if ( is_uploaded_file( $fname ) ) {
1690 return ImportStreamSource
::newFromFile( $fname );
1692 return Status
::newFatal( 'importnofile' );
1697 * @param string $url
1698 * @param string $method
1701 static function newFromURL( $url, $method = 'GET' ) {
1702 wfDebug( __METHOD__
. ": opening $url\n" );
1703 # Use the standard HTTP fetch function; it times out
1704 # quicker and sorts out user-agent problems which might
1705 # otherwise prevent importing from large sites, such
1706 # as the Wikimedia cluster, etc.
1707 $data = Http
::request( $method, $url, array( 'followRedirects' => true ) );
1708 if ( $data !== false ) {
1710 fwrite( $file, $data );
1713 return Status
::newGood( new ImportStreamSource( $file ) );
1715 return Status
::newFatal( 'importcantopen' );
1720 * @param string $interwiki
1721 * @param string $page
1722 * @param bool $history
1723 * @param bool $templates
1724 * @param int $pageLinkDepth
1727 public static function newFromInterwiki( $interwiki, $page, $history = false, $templates = false, $pageLinkDepth = 0 ) {
1728 if ( $page == '' ) {
1729 return Status
::newFatal( 'import-noarticle' );
1731 $link = Title
::newFromText( "$interwiki:Special:Export/$page" );
1732 if ( is_null( $link ) ||
!$link->isExternal() ) {
1733 return Status
::newFatal( 'importbadinterwiki' );
1737 $params['history'] = 1;
1740 $params['templates'] = 1;
1742 if ( $pageLinkDepth ) {
1743 $params['pagelink-depth'] = $pageLinkDepth;
1745 $url = $link->getFullURL( $params );
1746 # For interwikis, use POST to avoid redirects.
1747 return ImportStreamSource
::newFromURL( $url, "POST" );