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 if ( !in_array( 'uploadsource', stream_get_wrappers() ) ) {
49 stream_wrapper_register( 'uploadsource', 'UploadSourceAdapter' );
51 $id = UploadSourceAdapter
::registerSource( $source );
52 if ( defined( 'LIBXML_PARSEHUGE' ) ) {
53 $this->reader
->open( "uploadsource://$id", null, LIBXML_PARSEHUGE
);
55 $this->reader
->open( "uploadsource://$id" );
59 $this->setRevisionCallback( array( $this, "importRevision" ) );
60 $this->setUploadCallback( array( $this, 'importUpload' ) );
61 $this->setLogItemCallback( array( $this, 'importLogItem' ) );
62 $this->setPageOutCallback( array( $this, 'finishImportPage' ) );
66 * @return null|XMLReader
68 public function getReader() {
72 public function throwXmlError( $err ) {
73 $this->debug( "FAILURE: $err" );
74 wfDebug( "WikiImporter XML error: $err\n" );
77 public function debug( $data ) {
78 if ( $this->mDebug
) {
79 wfDebug( "IMPORT: $data\n" );
83 public function warn( $data ) {
84 wfDebug( "IMPORT: $data\n" );
87 public function notice( $msg /*, $param, ...*/ ) {
88 $params = func_get_args();
89 array_shift( $params );
91 if ( is_callable( $this->mNoticeCallback
) ) {
92 call_user_func( $this->mNoticeCallback
, $msg, $params );
93 } else { # No ImportReporter -> CLI
94 echo wfMessage( $msg, $params )->text() . "\n";
102 function setDebug( $debug ) {
103 $this->mDebug
= $debug;
107 * Set 'no updates' mode. In this mode, the link tables will not be updated by the importer
108 * @param bool $noupdates
110 function setNoUpdates( $noupdates ) {
111 $this->mNoUpdates
= $noupdates;
115 * Set a callback that displays notice messages
117 * @param callable $callback
120 public function setNoticeCallback( $callback ) {
121 return wfSetVar( $this->mNoticeCallback
, $callback );
125 * Sets the action to perform as each new page in the stream is reached.
126 * @param callable $callback
129 public function setPageCallback( $callback ) {
130 $previous = $this->mPageCallback
;
131 $this->mPageCallback
= $callback;
136 * Sets the action to perform as each page in the stream is completed.
137 * Callback accepts the page title (as a Title object), a second object
138 * with the original title form (in case it's been overridden into a
139 * local namespace), and a count of revisions.
141 * @param callable $callback
144 public function setPageOutCallback( $callback ) {
145 $previous = $this->mPageOutCallback
;
146 $this->mPageOutCallback
= $callback;
151 * Sets the action to perform as each page revision is reached.
152 * @param callable $callback
155 public function setRevisionCallback( $callback ) {
156 $previous = $this->mRevisionCallback
;
157 $this->mRevisionCallback
= $callback;
162 * Sets the action to perform as each file upload version is reached.
163 * @param callable $callback
166 public function setUploadCallback( $callback ) {
167 $previous = $this->mUploadCallback
;
168 $this->mUploadCallback
= $callback;
173 * Sets the action to perform as each log item reached.
174 * @param callable $callback
177 public function setLogItemCallback( $callback ) {
178 $previous = $this->mLogItemCallback
;
179 $this->mLogItemCallback
= $callback;
184 * Sets the action to perform when site info is encountered
185 * @param callable $callback
188 public function setSiteInfoCallback( $callback ) {
189 $previous = $this->mSiteInfoCallback
;
190 $this->mSiteInfoCallback
= $callback;
195 * Set a target namespace to override the defaults
196 * @param null|int $namespace
199 public function setTargetNamespace( $namespace ) {
200 if ( is_null( $namespace ) ) {
201 // Don't override namespaces
202 $this->mTargetNamespace
= null;
203 } elseif ( $namespace >= 0 ) {
204 // @todo FIXME: Check for validity
205 $this->mTargetNamespace
= intval( $namespace );
212 * Set a target root page under which all pages are imported
213 * @param null|string $rootpage
216 public function setTargetRootPage( $rootpage ) {
217 $status = Status
::newGood();
218 if ( is_null( $rootpage ) ) {
220 $this->mTargetRootPage
= null;
221 } elseif ( $rootpage !== '' ) {
222 $rootpage = rtrim( $rootpage, '/' ); //avoid double slashes
223 $title = Title
::newFromText( $rootpage, !is_null( $this->mTargetNamespace
)
224 ?
$this->mTargetNamespace
228 if ( !$title ||
$title->isExternal() ) {
229 $status->fatal( 'import-rootpage-invalid' );
231 if ( !MWNamespace
::hasSubpages( $title->getNamespace() ) ) {
234 $displayNSText = $title->getNamespace() == NS_MAIN
235 ?
wfMessage( 'blanknamespace' )->text()
236 : $wgContLang->getNsText( $title->getNamespace() );
237 $status->fatal( 'import-rootpage-nosubpage', $displayNSText );
239 // set namespace to 'all', so the namespace check in processTitle() can passed
240 $this->setTargetNamespace( null );
241 $this->mTargetRootPage
= $title->getPrefixedDBkey();
251 public function setImageBasePath( $dir ) {
252 $this->mImageBasePath
= $dir;
256 * @param bool $import
258 public function setImportUploads( $import ) {
259 $this->mImportUploads
= $import;
263 * Default per-revision callback, performs the import.
264 * @param WikiRevision $revision
267 public function importRevision( $revision ) {
268 if ( !$revision->getContent()->getContentHandler()->canBeUsedOn( $revision->getTitle() ) ) {
269 $this->notice( 'import-error-bad-location',
270 $revision->getTitle()->getPrefixedText(),
272 $revision->getModel(),
273 $revision->getFormat() );
279 $dbw = wfGetDB( DB_MASTER
);
280 return $dbw->deadlockLoop( array( $revision, 'importOldRevision' ) );
281 } catch ( MWContentSerializationException
$ex ) {
282 $this->notice( 'import-error-unserialize',
283 $revision->getTitle()->getPrefixedText(),
285 $revision->getModel(),
286 $revision->getFormat() );
293 * Default per-revision callback, performs the import.
294 * @param WikiRevision $revision
297 public function importLogItem( $revision ) {
298 $dbw = wfGetDB( DB_MASTER
);
299 return $dbw->deadlockLoop( array( $revision, 'importLogItem' ) );
304 * @param WikiRevision $revision
307 public function importUpload( $revision ) {
308 $dbw = wfGetDB( DB_MASTER
);
309 return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
313 * Mostly for hook use
314 * @param Title $title
315 * @param string $origTitle
316 * @param int $revCount
317 * @param int $sRevCount
318 * @param array $pageInfo
321 public function finishImportPage( $title, $origTitle, $revCount, $sRevCount, $pageInfo ) {
322 $args = func_get_args();
323 return wfRunHooks( 'AfterImportPage', $args );
327 * Alternate per-revision callback, for debugging.
328 * @param WikiRevision $revision
330 public function debugRevisionHandler( &$revision ) {
331 $this->debug( "Got revision:" );
332 if ( is_object( $revision->title
) ) {
333 $this->debug( "-- Title: " . $revision->title
->getPrefixedText() );
335 $this->debug( "-- Title: <invalid>" );
337 $this->debug( "-- User: " . $revision->user_text
);
338 $this->debug( "-- Timestamp: " . $revision->timestamp
);
339 $this->debug( "-- Comment: " . $revision->comment
);
340 $this->debug( "-- Text: " . $revision->text
);
344 * Notify the callback function when a new "<page>" is reached.
345 * @param Title $title
347 function pageCallback( $title ) {
348 if ( isset( $this->mPageCallback
) ) {
349 call_user_func( $this->mPageCallback
, $title );
354 * Notify the callback function when a "</page>" is closed.
355 * @param Title $title
356 * @param Title $origTitle
357 * @param int $revCount
358 * @param int $sucCount Number of revisions for which callback returned true
359 * @param array $pageInfo Associative array of page information
361 private function pageOutCallback( $title, $origTitle, $revCount, $sucCount, $pageInfo ) {
362 if ( isset( $this->mPageOutCallback
) ) {
363 $args = func_get_args();
364 call_user_func_array( $this->mPageOutCallback
, $args );
369 * Notify the callback function of a revision
370 * @param WikiRevision $revision
373 private function revisionCallback( $revision ) {
374 if ( isset( $this->mRevisionCallback
) ) {
375 return call_user_func_array( $this->mRevisionCallback
,
376 array( $revision, $this ) );
383 * Notify the callback function of a new log item
384 * @param WikiRevision $revision
387 private function logItemCallback( $revision ) {
388 if ( isset( $this->mLogItemCallback
) ) {
389 return call_user_func_array( $this->mLogItemCallback
,
390 array( $revision, $this ) );
397 * Shouldn't something like this be built-in to XMLReader?
398 * Fetches text contents of the current element, assuming
399 * no sub-elements or such scary things.
403 public function nodeContents() {
404 if ( $this->reader
->isEmptyElement
) {
408 while ( $this->reader
->read() ) {
409 switch ( $this->reader
->nodeType
) {
410 case XmlReader
::TEXT
:
411 case XmlReader
::SIGNIFICANT_WHITESPACE
:
412 $buffer .= $this->reader
->value
;
414 case XmlReader
::END_ELEMENT
:
419 $this->reader
->close();
425 /** Left in for debugging */
426 private function dumpElement() {
427 static $lookup = null;
429 $xmlReaderConstants = array(
444 "SIGNIFICANT_WHITESPACE",
451 foreach ( $xmlReaderConstants as $name ) {
452 $lookup[constant( "XmlReader::$name" )] = $name;
457 $lookup[$this->reader
->nodeType
],
464 * Primary entry point
465 * @throws MWException
468 public function doImport() {
470 // Calls to reader->read need to be wrapped in calls to
471 // libxml_disable_entity_loader() to avoid local file
472 // inclusion attacks (bug 46932).
473 $oldDisable = libxml_disable_entity_loader( true );
474 $this->reader
->read();
476 if ( $this->reader
->name
!= 'mediawiki' ) {
477 libxml_disable_entity_loader( $oldDisable );
478 throw new MWException( "Expected <mediawiki> tag, got " .
479 $this->reader
->name
);
481 $this->debug( "<mediawiki> tag is correct." );
483 $this->debug( "Starting primary dump processing loop." );
485 $keepReading = $this->reader
->read();
487 while ( $keepReading ) {
488 $tag = $this->reader
->name
;
489 $type = $this->reader
->nodeType
;
491 if ( !wfRunHooks( 'ImportHandleToplevelXMLTag', array( $this ) ) ) {
493 } elseif ( $tag == 'mediawiki' && $type == XmlReader
::END_ELEMENT
) {
495 } elseif ( $tag == 'siteinfo' ) {
496 $this->handleSiteInfo();
497 } elseif ( $tag == 'page' ) {
499 } elseif ( $tag == 'logitem' ) {
500 $this->handleLogItem();
501 } elseif ( $tag != '#text' ) {
502 $this->warn( "Unhandled top-level XML tag $tag" );
508 $keepReading = $this->reader
->next();
510 $this->debug( "Skip" );
512 $keepReading = $this->reader
->read();
516 libxml_disable_entity_loader( $oldDisable );
522 * @throws MWException
524 private function handleSiteInfo() {
525 // Site info is useful, but not actually used for dump imports.
526 // Includes a quick short-circuit to save performance.
527 if ( ! $this->mSiteInfoCallback
) {
528 $this->reader
->next();
531 throw new MWException( "SiteInfo tag is not yet handled, do not set mSiteInfoCallback" );
534 private function handleLogItem() {
535 $this->debug( "Enter log item handler." );
538 // Fields that can just be stuffed in the pageInfo object
539 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
540 'logtitle', 'params' );
542 while ( $this->reader
->read() ) {
543 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
544 $this->reader
->name
== 'logitem' ) {
548 $tag = $this->reader
->name
;
550 if ( !wfRunHooks( 'ImportHandleLogItemXMLTag', array(
554 } elseif ( in_array( $tag, $normalFields ) ) {
555 $logInfo[$tag] = $this->nodeContents();
556 } elseif ( $tag == 'contributor' ) {
557 $logInfo['contributor'] = $this->handleContributor();
558 } elseif ( $tag != '#text' ) {
559 $this->warn( "Unhandled log-item XML tag $tag" );
563 $this->processLogItem( $logInfo );
567 * @param array $logInfo
570 private function processLogItem( $logInfo ) {
571 $revision = new WikiRevision
;
573 $revision->setID( $logInfo['id'] );
574 $revision->setType( $logInfo['type'] );
575 $revision->setAction( $logInfo['action'] );
576 $revision->setTimestamp( $logInfo['timestamp'] );
577 $revision->setParams( $logInfo['params'] );
578 $revision->setTitle( Title
::newFromText( $logInfo['logtitle'] ) );
579 $revision->setNoUpdates( $this->mNoUpdates
);
581 if ( isset( $logInfo['comment'] ) ) {
582 $revision->setComment( $logInfo['comment'] );
585 if ( isset( $logInfo['contributor']['ip'] ) ) {
586 $revision->setUserIP( $logInfo['contributor']['ip'] );
588 if ( isset( $logInfo['contributor']['username'] ) ) {
589 $revision->setUserName( $logInfo['contributor']['username'] );
592 return $this->logItemCallback( $revision );
595 private function handlePage() {
597 $this->debug( "Enter page handler." );
598 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
600 // Fields that can just be stuffed in the pageInfo object
601 $normalFields = array( 'title', 'id', 'redirect', 'restrictions' );
606 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
607 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
608 $this->reader
->name
== 'page' ) {
612 $tag = $this->reader
->name
;
615 // The title is invalid, bail out of this page
617 } elseif ( !wfRunHooks( 'ImportHandlePageXMLTag', array( $this,
620 } elseif ( in_array( $tag, $normalFields ) ) {
621 $pageInfo[$tag] = $this->nodeContents();
622 if ( $tag == 'title' ) {
623 $title = $this->processTitle( $pageInfo['title'] );
630 $this->pageCallback( $title );
631 list( $pageInfo['_title'], $origTitle ) = $title;
633 } elseif ( $tag == 'revision' ) {
634 $this->handleRevision( $pageInfo );
635 } elseif ( $tag == 'upload' ) {
636 $this->handleUpload( $pageInfo );
637 } elseif ( $tag != '#text' ) {
638 $this->warn( "Unhandled page XML tag $tag" );
643 $this->pageOutCallback( $pageInfo['_title'], $origTitle,
644 $pageInfo['revisionCount'],
645 $pageInfo['successfulRevisionCount'],
650 * @param array $pageInfo
652 private function handleRevision( &$pageInfo ) {
653 $this->debug( "Enter revision handler" );
654 $revisionInfo = array();
656 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'model', 'format', 'text' );
660 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
661 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
662 $this->reader
->name
== 'revision' ) {
666 $tag = $this->reader
->name
;
668 if ( !wfRunHooks( 'ImportHandleRevisionXMLTag', array(
669 $this, $pageInfo, $revisionInfo
672 } elseif ( in_array( $tag, $normalFields ) ) {
673 $revisionInfo[$tag] = $this->nodeContents();
674 } elseif ( $tag == 'contributor' ) {
675 $revisionInfo['contributor'] = $this->handleContributor();
676 } elseif ( $tag != '#text' ) {
677 $this->warn( "Unhandled revision XML tag $tag" );
682 $pageInfo['revisionCount']++
;
683 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
684 $pageInfo['successfulRevisionCount']++
;
689 * @param array $pageInfo
690 * @param array $revisionInfo
693 private function processRevision( $pageInfo, $revisionInfo ) {
694 $revision = new WikiRevision
;
696 if ( isset( $revisionInfo['id'] ) ) {
697 $revision->setID( $revisionInfo['id'] );
699 if ( isset( $revisionInfo['text'] ) ) {
700 $revision->setText( $revisionInfo['text'] );
702 if ( isset( $revisionInfo['model'] ) ) {
703 $revision->setModel( $revisionInfo['model'] );
705 if ( isset( $revisionInfo['format'] ) ) {
706 $revision->setFormat( $revisionInfo['format'] );
708 $revision->setTitle( $pageInfo['_title'] );
710 if ( isset( $revisionInfo['timestamp'] ) ) {
711 $revision->setTimestamp( $revisionInfo['timestamp'] );
713 $revision->setTimestamp( wfTimestampNow() );
716 if ( isset( $revisionInfo['comment'] ) ) {
717 $revision->setComment( $revisionInfo['comment'] );
720 if ( isset( $revisionInfo['minor'] ) ) {
721 $revision->setMinor( true );
723 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
724 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
726 if ( isset( $revisionInfo['contributor']['username'] ) ) {
727 $revision->setUserName( $revisionInfo['contributor']['username'] );
729 $revision->setNoUpdates( $this->mNoUpdates
);
731 return $this->revisionCallback( $revision );
735 * @param array $pageInfo
738 private function handleUpload( &$pageInfo ) {
739 $this->debug( "Enter upload handler" );
740 $uploadInfo = array();
742 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
743 'src', 'size', 'sha1base36', 'archivename', 'rel' );
747 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
748 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
749 $this->reader
->name
== 'upload' ) {
753 $tag = $this->reader
->name
;
755 if ( !wfRunHooks( 'ImportHandleUploadXMLTag', array(
759 } elseif ( in_array( $tag, $normalFields ) ) {
760 $uploadInfo[$tag] = $this->nodeContents();
761 } elseif ( $tag == 'contributor' ) {
762 $uploadInfo['contributor'] = $this->handleContributor();
763 } elseif ( $tag == 'contents' ) {
764 $contents = $this->nodeContents();
765 $encoding = $this->reader
->getAttribute( 'encoding' );
766 if ( $encoding === 'base64' ) {
767 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
768 $uploadInfo['isTempSrc'] = true;
770 } elseif ( $tag != '#text' ) {
771 $this->warn( "Unhandled upload XML tag $tag" );
776 if ( $this->mImageBasePath
&& isset( $uploadInfo['rel'] ) ) {
777 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
778 if ( file_exists( $path ) ) {
779 $uploadInfo['fileSrc'] = $path;
780 $uploadInfo['isTempSrc'] = false;
784 if ( $this->mImportUploads
) {
785 return $this->processUpload( $pageInfo, $uploadInfo );
790 * @param string $contents
793 private function dumpTemp( $contents ) {
794 $filename = tempnam( wfTempDir(), 'importupload' );
795 file_put_contents( $filename, $contents );
800 * @param array $pageInfo
801 * @param array $uploadInfo
804 private function processUpload( $pageInfo, $uploadInfo ) {
805 $revision = new WikiRevision
;
806 $text = isset( $uploadInfo['text'] ) ?
$uploadInfo['text'] : '';
808 $revision->setTitle( $pageInfo['_title'] );
809 $revision->setID( $pageInfo['id'] );
810 $revision->setTimestamp( $uploadInfo['timestamp'] );
811 $revision->setText( $text );
812 $revision->setFilename( $uploadInfo['filename'] );
813 if ( isset( $uploadInfo['archivename'] ) ) {
814 $revision->setArchiveName( $uploadInfo['archivename'] );
816 $revision->setSrc( $uploadInfo['src'] );
817 if ( isset( $uploadInfo['fileSrc'] ) ) {
818 $revision->setFileSrc( $uploadInfo['fileSrc'],
819 !empty( $uploadInfo['isTempSrc'] ) );
821 if ( isset( $uploadInfo['sha1base36'] ) ) {
822 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
824 $revision->setSize( intval( $uploadInfo['size'] ) );
825 $revision->setComment( $uploadInfo['comment'] );
827 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
828 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
830 if ( isset( $uploadInfo['contributor']['username'] ) ) {
831 $revision->setUserName( $uploadInfo['contributor']['username'] );
833 $revision->setNoUpdates( $this->mNoUpdates
);
835 return call_user_func( $this->mUploadCallback
, $revision );
841 private function handleContributor() {
842 $fields = array( 'id', 'ip', 'username' );
845 while ( $this->reader
->read() ) {
846 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
847 $this->reader
->name
== 'contributor' ) {
851 $tag = $this->reader
->name
;
853 if ( in_array( $tag, $fields ) ) {
854 $info[$tag] = $this->nodeContents();
862 * @param string $text
865 private function processTitle( $text ) {
866 global $wgCommandLineMode;
869 $origTitle = Title
::newFromText( $workTitle );
871 if ( !is_null( $this->mTargetNamespace
) && !is_null( $origTitle ) ) {
872 # makeTitleSafe, because $origTitle can have a interwiki (different setting of interwiki map)
873 # and than dbKey can begin with a lowercase char
874 $title = Title
::makeTitleSafe( $this->mTargetNamespace
,
875 $origTitle->getDBkey() );
877 if ( !is_null( $this->mTargetRootPage
) ) {
878 $workTitle = $this->mTargetRootPage
. '/' . $workTitle;
880 $title = Title
::newFromText( $workTitle );
883 if ( is_null( $title ) ) {
884 # Invalid page title? Ignore the page
885 $this->notice( 'import-error-invalid', $workTitle );
887 } elseif ( $title->isExternal() ) {
888 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
890 } elseif ( !$title->canExist() ) {
891 $this->notice( 'import-error-special', $title->getPrefixedText() );
893 } elseif ( !$title->userCan( 'edit' ) && !$wgCommandLineMode ) {
894 # Do not import if the importing wiki user cannot edit this page
895 $this->notice( 'import-error-edit', $title->getPrefixedText() );
897 } elseif ( !$title->exists() && !$title->userCan( 'create' ) && !$wgCommandLineMode ) {
898 # Do not import if the importing wiki user cannot create this page
899 $this->notice( 'import-error-create', $title->getPrefixedText() );
903 return array( $title, $origTitle );
907 /** This is a horrible hack used to keep source compatibility */
908 class UploadSourceAdapter
{
910 private static $sourceRegistrations = array();
922 * @param string $source
925 static function registerSource( $source ) {
926 $id = wfRandomString();
928 self
::$sourceRegistrations[$id] = $source;
934 * @param string $path
935 * @param string $mode
936 * @param array $options
937 * @param string $opened_path
940 function stream_open( $path, $mode, $options, &$opened_path ) {
941 $url = parse_url( $path );
944 if ( !isset( self
::$sourceRegistrations[$id] ) ) {
948 $this->mSource
= self
::$sourceRegistrations[$id];
957 function stream_read( $count ) {
961 while ( !$leave && !$this->mSource
->atEnd() &&
962 strlen( $this->mBuffer
) < $count ) {
963 $read = $this->mSource
->readChunk();
965 if ( !strlen( $read ) ) {
969 $this->mBuffer
.= $read;
972 if ( strlen( $this->mBuffer
) ) {
973 $return = substr( $this->mBuffer
, 0, $count );
974 $this->mBuffer
= substr( $this->mBuffer
, $count );
977 $this->mPosition +
= strlen( $return );
983 * @param string $data
986 function stream_write( $data ) {
993 function stream_tell() {
994 return $this->mPosition
;
1000 function stream_eof() {
1001 return $this->mSource
->atEnd();
1007 function url_stat() {
1010 $result['dev'] = $result[0] = 0;
1011 $result['ino'] = $result[1] = 0;
1012 $result['mode'] = $result[2] = 0;
1013 $result['nlink'] = $result[3] = 0;
1014 $result['uid'] = $result[4] = 0;
1015 $result['gid'] = $result[5] = 0;
1016 $result['rdev'] = $result[6] = 0;
1017 $result['size'] = $result[7] = 0;
1018 $result['atime'] = $result[8] = 0;
1019 $result['mtime'] = $result[9] = 0;
1020 $result['ctime'] = $result[10] = 0;
1021 $result['blksize'] = $result[11] = 0;
1022 $result['blocks'] = $result[12] = 0;
1028 class XMLReader2
extends XMLReader
{
1031 * @return bool|string
1033 function nodeContents() {
1034 if ( $this->isEmptyElement
) {
1038 while ( $this->read() ) {
1039 switch ( $this->nodeType
) {
1040 case XmlReader
::TEXT
:
1041 case XmlReader
::SIGNIFICANT_WHITESPACE
:
1042 $buffer .= $this->value
;
1044 case XmlReader
::END_ELEMENT
:
1048 return $this->close();
1053 * @todo document (e.g. one-sentence class description).
1054 * @ingroup SpecialPage
1056 class WikiRevision
{
1057 /** @todo Unused? */
1058 private $importer = null;
1061 public $title = null;
1067 public $timestamp = "20010115000000";
1071 * @todo Can't find any uses. Public, because that's suspicious. Get clarity. */
1075 public $user_text = "";
1078 protected $model = null;
1081 protected $format = null;
1090 protected $content = null;
1093 public $comment = "";
1096 protected $minor = false;
1099 protected $type = "";
1102 protected $action = "";
1105 protected $params = "";
1108 protected $fileSrc = '';
1110 /** @var bool|string */
1111 protected $sha1base36 = false;
1117 private $isTemp = false;
1120 protected $archiveName = '';
1122 protected $filename;
1127 /** @todo Unused? */
1128 private $fileIsTemp;
1131 private $mNoUpdates = false;
1134 * @param Title $title
1135 * @throws MWException
1137 function setTitle( $title ) {
1138 if ( is_object( $title ) ) {
1139 $this->title
= $title;
1140 } elseif ( is_null( $title ) ) {
1141 throw new MWException( "WikiRevision given a null title in import. "
1142 . "You may need to adjust \$wgLegalTitleChars." );
1144 throw new MWException( "WikiRevision given non-object title in import." );
1151 function setID( $id ) {
1158 function setTimestamp( $ts ) {
1159 # 2003-08-05T18:30:02Z
1160 $this->timestamp
= wfTimestamp( TS_MW
, $ts );
1164 * @param string $user
1166 function setUsername( $user ) {
1167 $this->user_text
= $user;
1173 function setUserIP( $ip ) {
1174 $this->user_text
= $ip;
1178 * @param string $model
1180 function setModel( $model ) {
1181 $this->model
= $model;
1185 * @param string $format
1187 function setFormat( $format ) {
1188 $this->format
= $format;
1192 * @param string $text
1194 function setText( $text ) {
1195 $this->text
= $text;
1199 * @param string $text
1201 function setComment( $text ) {
1202 $this->comment
= $text;
1206 * @param bool $minor
1208 function setMinor( $minor ) {
1209 $this->minor
= (bool)$minor;
1215 function setSrc( $src ) {
1220 * @param string $src
1221 * @param bool $isTemp
1223 function setFileSrc( $src, $isTemp ) {
1224 $this->fileSrc
= $src;
1225 $this->fileIsTemp
= $isTemp;
1229 * @param string $sha1base36
1231 function setSha1Base36( $sha1base36 ) {
1232 $this->sha1base36
= $sha1base36;
1236 * @param string $filename
1238 function setFilename( $filename ) {
1239 $this->filename
= $filename;
1243 * @param string $archiveName
1245 function setArchiveName( $archiveName ) {
1246 $this->archiveName
= $archiveName;
1252 function setSize( $size ) {
1253 $this->size
= intval( $size );
1257 * @param string $type
1259 function setType( $type ) {
1260 $this->type
= $type;
1264 * @param string $action
1266 function setAction( $action ) {
1267 $this->action
= $action;
1271 * @param array $params
1273 function setParams( $params ) {
1274 $this->params
= $params;
1278 * @param bool $noupdates
1280 public function setNoUpdates( $noupdates ) {
1281 $this->mNoUpdates
= $noupdates;
1287 function getTitle() {
1288 return $this->title
;
1301 function getTimestamp() {
1302 return $this->timestamp
;
1308 function getUser() {
1309 return $this->user_text
;
1315 * @deprecated Since 1.21, use getContent() instead.
1317 function getText() {
1318 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1326 function getContent() {
1327 if ( is_null( $this->content
) ) {
1329 ContentHandler
::makeContent(
1337 return $this->content
;
1343 function getModel() {
1344 if ( is_null( $this->model
) ) {
1345 $this->model
= $this->getTitle()->getContentModel();
1348 return $this->model
;
1354 function getFormat() {
1355 if ( is_null( $this->model
) ) {
1356 $this->format
= ContentHandler
::getForTitle( $this->getTitle() )->getDefaultFormat();
1359 return $this->format
;
1365 function getComment() {
1366 return $this->comment
;
1372 function getMinor() {
1373 return $this->minor
;
1384 * @return bool|string
1386 function getSha1() {
1387 if ( $this->sha1base36
) {
1388 return wfBaseConvert( $this->sha1base36
, 36, 16 );
1396 function getFileSrc() {
1397 return $this->fileSrc
;
1403 function isTempSrc() {
1404 return $this->isTemp
;
1410 function getFilename() {
1411 return $this->filename
;
1417 function getArchiveName() {
1418 return $this->archiveName
;
1424 function getSize() {
1431 function getType() {
1438 function getAction() {
1439 return $this->action
;
1445 function getParams() {
1446 return $this->params
;
1452 function importOldRevision() {
1453 $dbw = wfGetDB( DB_MASTER
);
1455 # Sneak a single revision into place
1456 $user = User
::newFromName( $this->getUser() );
1458 $userId = intval( $user->getId() );
1459 $userText = $user->getName();
1463 $userText = $this->getUser();
1464 $userObj = new User
;
1467 // avoid memory leak...?
1468 $linkCache = LinkCache
::singleton();
1469 $linkCache->clear();
1471 $page = WikiPage
::factory( $this->title
);
1472 if ( !$page->exists() ) {
1473 # must create the page...
1474 $pageId = $page->insertOn( $dbw );
1476 $oldcountable = null;
1478 $pageId = $page->getId();
1481 $prior = $dbw->selectField( 'revision', '1',
1482 array( 'rev_page' => $pageId,
1483 'rev_timestamp' => $dbw->timestamp( $this->timestamp
),
1484 'rev_user_text' => $userText,
1485 'rev_comment' => $this->getComment() ),
1489 // @todo FIXME: This could fail slightly for multiple matches :P
1490 wfDebug( __METHOD__
. ": skipping existing revision for [[" .
1491 $this->title
->getPrefixedText() . "]], timestamp " . $this->timestamp
. "\n" );
1494 $oldcountable = $page->isCountable();
1497 # @todo FIXME: Use original rev_id optionally (better for backups)
1499 $revision = new Revision( array(
1500 'title' => $this->title
,
1502 'content_model' => $this->getModel(),
1503 'content_format' => $this->getFormat(),
1504 //XXX: just set 'content' => $this->getContent()?
1505 'text' => $this->getContent()->serialize( $this->getFormat() ),
1506 'comment' => $this->getComment(),
1508 'user_text' => $userText,
1509 'timestamp' => $this->timestamp
,
1510 'minor_edit' => $this->minor
,
1512 $revision->insertOn( $dbw );
1513 $changed = $page->updateIfNewerOn( $dbw, $revision );
1515 if ( $changed !== false && !$this->mNoUpdates
) {
1516 wfDebug( __METHOD__
. ": running updates\n" );
1517 $page->doEditUpdates(
1520 array( 'created' => $created, 'oldcountable' => $oldcountable )
1530 function importLogItem() {
1531 $dbw = wfGetDB( DB_MASTER
);
1532 # @todo FIXME: This will not record autoblocks
1533 if ( !$this->getTitle() ) {
1534 wfDebug( __METHOD__
. ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1535 $this->timestamp
. "\n" );
1538 # Check if it exists already
1539 // @todo FIXME: Use original log ID (better for backups)
1540 $prior = $dbw->selectField( 'logging', '1',
1541 array( 'log_type' => $this->getType(),
1542 'log_action' => $this->getAction(),
1543 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1544 'log_namespace' => $this->getTitle()->getNamespace(),
1545 'log_title' => $this->getTitle()->getDBkey(),
1546 'log_comment' => $this->getComment(),
1547 #'log_user_text' => $this->user_text,
1548 'log_params' => $this->params
),
1551 // @todo FIXME: This could fail slightly for multiple matches :P
1554 . ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp "
1555 . $this->timestamp
. "\n" );
1558 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1560 'log_id' => $log_id,
1561 'log_type' => $this->type
,
1562 'log_action' => $this->action
,
1563 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1564 'log_user' => User
::idFromName( $this->user_text
),
1565 #'log_user_text' => $this->user_text,
1566 'log_namespace' => $this->getTitle()->getNamespace(),
1567 'log_title' => $this->getTitle()->getDBkey(),
1568 'log_comment' => $this->getComment(),
1569 'log_params' => $this->params
1571 $dbw->insert( 'logging', $data, __METHOD__
);
1577 function importUpload() {
1579 $archiveName = $this->getArchiveName();
1580 if ( $archiveName ) {
1581 wfDebug( __METHOD__
. "Importing archived file as $archiveName\n" );
1582 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1583 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1585 $file = wfLocalFile( $this->getTitle() );
1586 wfDebug( __METHOD__
. 'Importing new file as ' . $file->getName() . "\n" );
1587 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1588 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1589 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1590 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1591 wfDebug( __METHOD__
. "File already exists; importing as $archiveName\n" );
1595 wfDebug( __METHOD__
. ': Bad file for ' . $this->getTitle() . "\n" );
1599 # Get the file source or download if necessary
1600 $source = $this->getFileSrc();
1601 $flags = $this->isTempSrc() ? File
::DELETE_SOURCE
: 0;
1603 $source = $this->downloadSource();
1604 $flags |
= File
::DELETE_SOURCE
;
1607 wfDebug( __METHOD__
. ": Could not fetch remote file.\n" );
1610 $sha1 = $this->getSha1();
1611 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1612 if ( $flags & File
::DELETE_SOURCE
) {
1613 # Broken file; delete it if it is a temporary file
1616 wfDebug( __METHOD__
. ": Corrupt file $source.\n" );
1620 $user = User
::newFromName( $this->user_text
);
1622 # Do the actual upload
1623 if ( $archiveName ) {
1624 $status = $file->uploadOld( $source, $archiveName,
1625 $this->getTimestamp(), $this->getComment(), $user, $flags );
1627 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1628 $flags, false, $this->getTimestamp(), $user );
1631 if ( $status->isGood() ) {
1632 wfDebug( __METHOD__
. ": Successful\n" );
1635 wfDebug( __METHOD__
. ': failed: ' . $status->getXml() . "\n" );
1641 * @return bool|string
1643 function downloadSource() {
1644 global $wgEnableUploads;
1645 if ( !$wgEnableUploads ) {
1649 $tempo = tempnam( wfTempDir(), 'download' );
1650 $f = fopen( $tempo, 'wb' );
1652 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1657 $src = $this->getSrc();
1658 $data = Http
::get( $src );
1660 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1666 fwrite( $f, $data );
1675 * @todo document (e.g. one-sentence class description).
1676 * @ingroup SpecialPage
1678 class ImportStringSource
{
1679 function __construct( $string ) {
1680 $this->mString
= $string;
1681 $this->mRead
= false;
1688 return $this->mRead
;
1692 * @return bool|string
1694 function readChunk() {
1695 if ( $this->atEnd() ) {
1698 $this->mRead
= true;
1699 return $this->mString
;
1704 * @todo document (e.g. one-sentence class description).
1705 * @ingroup SpecialPage
1707 class ImportStreamSource
{
1708 function __construct( $handle ) {
1709 $this->mHandle
= $handle;
1716 return feof( $this->mHandle
);
1722 function readChunk() {
1723 return fread( $this->mHandle
, 32768 );
1727 * @param string $filename
1730 static function newFromFile( $filename ) {
1731 wfSuppressWarnings();
1732 $file = fopen( $filename, 'rt' );
1733 wfRestoreWarnings();
1735 return Status
::newFatal( "importcantopen" );
1737 return Status
::newGood( new ImportStreamSource( $file ) );
1741 * @param string $fieldname
1744 static function newFromUpload( $fieldname = "xmlimport" ) {
1745 $upload =& $_FILES[$fieldname];
1747 if ( $upload === null ||
!$upload['name'] ) {
1748 return Status
::newFatal( 'importnofile' );
1750 if ( !empty( $upload['error'] ) ) {
1751 switch ( $upload['error'] ) {
1753 # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1754 return Status
::newFatal( 'importuploaderrorsize' );
1756 # The uploaded file exceeds the MAX_FILE_SIZE directive that
1757 # was specified in the HTML form.
1758 return Status
::newFatal( 'importuploaderrorsize' );
1760 # The uploaded file was only partially uploaded
1761 return Status
::newFatal( 'importuploaderrorpartial' );
1763 # Missing a temporary folder.
1764 return Status
::newFatal( 'importuploaderrortemp' );
1765 # case else: # Currently impossible
1769 $fname = $upload['tmp_name'];
1770 if ( is_uploaded_file( $fname ) ) {
1771 return ImportStreamSource
::newFromFile( $fname );
1773 return Status
::newFatal( 'importnofile' );
1778 * @param string $url
1779 * @param string $method
1782 static function newFromURL( $url, $method = 'GET' ) {
1783 wfDebug( __METHOD__
. ": opening $url\n" );
1784 # Use the standard HTTP fetch function; it times out
1785 # quicker and sorts out user-agent problems which might
1786 # otherwise prevent importing from large sites, such
1787 # as the Wikimedia cluster, etc.
1788 $data = Http
::request( $method, $url, array( 'followRedirects' => true ) );
1789 if ( $data !== false ) {
1791 fwrite( $file, $data );
1794 return Status
::newGood( new ImportStreamSource( $file ) );
1796 return Status
::newFatal( 'importcantopen' );
1801 * @param string $interwiki
1802 * @param string $page
1803 * @param bool $history
1804 * @param bool $templates
1805 * @param int $pageLinkDepth
1808 public static function newFromInterwiki( $interwiki, $page, $history = false,
1809 $templates = false, $pageLinkDepth = 0
1811 if ( $page == '' ) {
1812 return Status
::newFatal( 'import-noarticle' );
1814 $link = Title
::newFromText( "$interwiki:Special:Export/$page" );
1815 if ( is_null( $link ) ||
!$link->isExternal() ) {
1816 return Status
::newFatal( 'importbadinterwiki' );
1820 $params['history'] = 1;
1823 $params['templates'] = 1;
1825 if ( $pageLinkDepth ) {
1826 $params['pagelink-depth'] = $pageLinkDepth;
1828 $url = $link->getFullURL( $params );
1829 # For interwikis, use POST to avoid redirects.
1830 return ImportStreamSource
::newFromURL( $url, "POST" );