3 * MediaWiki page data importer.
5 * Copyright © 2003,2005 Brion Vibber <brion@pobox.com>
6 * https://www.mediawiki.org/
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
24 * @ingroup SpecialPage
28 * XML file reader for the page data importer
30 * implements Special:Import
31 * @ingroup SpecialPage
34 private $reader = null;
35 private $mLogItemCallback, $mUploadCallback, $mRevisionCallback, $mPageCallback;
36 private $mSiteInfoCallback, $mTargetNamespace, $mTargetRootPage, $mPageOutCallback;
37 private $mNoticeCallback, $mDebug;
38 private $mImportUploads, $mImageBasePath;
39 private $mNoUpdates = false;
42 * Creates an ImportXMLReader drawing from the source provided
43 * @param string $source
45 function __construct( $source ) {
46 $this->reader
= new XMLReader();
48 stream_wrapper_register( 'uploadsource', 'UploadSourceAdapter' );
49 $id = UploadSourceAdapter
::registerSource( $source );
50 if ( defined( 'LIBXML_PARSEHUGE' ) ) {
51 $this->reader
->open( "uploadsource://$id", null, LIBXML_PARSEHUGE
);
53 $this->reader
->open( "uploadsource://$id" );
57 $this->setRevisionCallback( array( $this, "importRevision" ) );
58 $this->setUploadCallback( array( $this, 'importUpload' ) );
59 $this->setLogItemCallback( array( $this, 'importLogItem' ) );
60 $this->setPageOutCallback( array( $this, 'finishImportPage' ) );
64 * @return null|XMLReader
66 public function getReader() {
70 public function throwXmlError( $err ) {
71 $this->debug( "FAILURE: $err" );
72 wfDebug( "WikiImporter XML error: $err\n" );
75 public function debug( $data ) {
76 if ( $this->mDebug
) {
77 wfDebug( "IMPORT: $data\n" );
81 public function warn( $data ) {
82 wfDebug( "IMPORT: $data\n" );
85 public function notice( $msg /*, $param, ...*/ ) {
86 $params = func_get_args();
87 array_shift( $params );
89 if ( is_callable( $this->mNoticeCallback
) ) {
90 call_user_func( $this->mNoticeCallback
, $msg, $params );
91 } else { # No ImportReporter -> CLI
92 echo wfMessage( $msg, $params )->text() . "\n";
100 function setDebug( $debug ) {
101 $this->mDebug
= $debug;
105 * Set 'no updates' mode. In this mode, the link tables will not be updated by the importer
106 * @param bool $noupdates
108 function setNoUpdates( $noupdates ) {
109 $this->mNoUpdates
= $noupdates;
113 * Set a callback that displays notice messages
115 * @param callable $callback
118 public function setNoticeCallback( $callback ) {
119 return wfSetVar( $this->mNoticeCallback
, $callback );
123 * Sets the action to perform as each new page in the stream is reached.
124 * @param callable $callback
127 public function setPageCallback( $callback ) {
128 $previous = $this->mPageCallback
;
129 $this->mPageCallback
= $callback;
134 * Sets the action to perform as each page in the stream is completed.
135 * Callback accepts the page title (as a Title object), a second object
136 * with the original title form (in case it's been overridden into a
137 * local namespace), and a count of revisions.
139 * @param callable $callback
142 public function setPageOutCallback( $callback ) {
143 $previous = $this->mPageOutCallback
;
144 $this->mPageOutCallback
= $callback;
149 * Sets the action to perform as each page revision is reached.
150 * @param callable $callback
153 public function setRevisionCallback( $callback ) {
154 $previous = $this->mRevisionCallback
;
155 $this->mRevisionCallback
= $callback;
160 * Sets the action to perform as each file upload version is reached.
161 * @param callable $callback
164 public function setUploadCallback( $callback ) {
165 $previous = $this->mUploadCallback
;
166 $this->mUploadCallback
= $callback;
171 * Sets the action to perform as each log item reached.
172 * @param callable $callback
175 public function setLogItemCallback( $callback ) {
176 $previous = $this->mLogItemCallback
;
177 $this->mLogItemCallback
= $callback;
182 * Sets the action to perform when site info is encountered
183 * @param callable $callback
186 public function setSiteInfoCallback( $callback ) {
187 $previous = $this->mSiteInfoCallback
;
188 $this->mSiteInfoCallback
= $callback;
193 * Set a target namespace to override the defaults
194 * @param null|int $namespace
197 public function setTargetNamespace( $namespace ) {
198 if ( is_null( $namespace ) ) {
199 // Don't override namespaces
200 $this->mTargetNamespace
= null;
201 } elseif ( $namespace >= 0 ) {
202 // @todo FIXME: Check for validity
203 $this->mTargetNamespace
= intval( $namespace );
210 * Set a target root page under which all pages are imported
211 * @param null|string $rootpage
214 public function setTargetRootPage( $rootpage ) {
215 $status = Status
::newGood();
216 if ( is_null( $rootpage ) ) {
218 $this->mTargetRootPage
= null;
219 } elseif ( $rootpage !== '' ) {
220 $rootpage = rtrim( $rootpage, '/' ); //avoid double slashes
221 $title = Title
::newFromText( $rootpage, !is_null( $this->mTargetNamespace
) ?
$this->mTargetNamespace
: NS_MAIN
);
222 if ( !$title ||
$title->isExternal() ) {
223 $status->fatal( 'import-rootpage-invalid' );
225 if ( !MWNamespace
::hasSubpages( $title->getNamespace() ) ) {
228 $displayNSText = $title->getNamespace() == NS_MAIN
229 ?
wfMessage( 'blanknamespace' )->text()
230 : $wgContLang->getNsText( $title->getNamespace() );
231 $status->fatal( 'import-rootpage-nosubpage', $displayNSText );
233 // set namespace to 'all', so the namespace check in processTitle() can passed
234 $this->setTargetNamespace( null );
235 $this->mTargetRootPage
= $title->getPrefixedDBkey();
245 public function setImageBasePath( $dir ) {
246 $this->mImageBasePath
= $dir;
250 * @param bool $import
252 public function setImportUploads( $import ) {
253 $this->mImportUploads
= $import;
257 * Default per-revision callback, performs the import.
258 * @param WikiRevision $revision
261 public function importRevision( $revision ) {
262 if ( !$revision->getContent()->getContentHandler()->canBeUsedOn( $revision->getTitle() ) ) {
263 $this->notice( 'import-error-bad-location',
264 $revision->getTitle()->getPrefixedText(),
266 $revision->getModel(),
267 $revision->getFormat() );
273 $dbw = wfGetDB( DB_MASTER
);
274 return $dbw->deadlockLoop( array( $revision, 'importOldRevision' ) );
275 } catch ( MWContentSerializationException
$ex ) {
276 $this->notice( 'import-error-unserialize',
277 $revision->getTitle()->getPrefixedText(),
279 $revision->getModel(),
280 $revision->getFormat() );
287 * Default per-revision callback, performs the import.
288 * @param WikiRevision $rev
291 public function importLogItem( $rev ) {
292 $dbw = wfGetDB( DB_MASTER
);
293 return $dbw->deadlockLoop( array( $rev, 'importLogItem' ) );
298 * @param WikiRevision $revision
301 public function importUpload( $revision ) {
302 $dbw = wfGetDB( DB_MASTER
);
303 return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
307 * Mostly for hook use
308 * @param Title $title
309 * @param string $origTitle
310 * @param int $revCount
311 * @param int $sRevCount
312 * @param array $pageInfo
315 public function finishImportPage( $title, $origTitle, $revCount, $sRevCount, $pageInfo ) {
316 $args = func_get_args();
317 return wfRunHooks( 'AfterImportPage', $args );
321 * Alternate per-revision callback, for debugging.
322 * @param WikiRevision $revision
324 public function debugRevisionHandler( &$revision ) {
325 $this->debug( "Got revision:" );
326 if ( is_object( $revision->title
) ) {
327 $this->debug( "-- Title: " . $revision->title
->getPrefixedText() );
329 $this->debug( "-- Title: <invalid>" );
331 $this->debug( "-- User: " . $revision->user_text
);
332 $this->debug( "-- Timestamp: " . $revision->timestamp
);
333 $this->debug( "-- Comment: " . $revision->comment
);
334 $this->debug( "-- Text: " . $revision->text
);
338 * Notify the callback function when a new "<page>" is reached.
339 * @param Title $title
341 function pageCallback( $title ) {
342 if ( isset( $this->mPageCallback
) ) {
343 call_user_func( $this->mPageCallback
, $title );
348 * Notify the callback function when a "</page>" is closed.
349 * @param Title $title
350 * @param Title $origTitle
351 * @param int $revCount
352 * @param int $sucCount Number of revisions for which callback returned true
353 * @param array $pageInfo Associative array of page information
355 private function pageOutCallback( $title, $origTitle, $revCount, $sucCount, $pageInfo ) {
356 if ( isset( $this->mPageOutCallback
) ) {
357 $args = func_get_args();
358 call_user_func_array( $this->mPageOutCallback
, $args );
363 * Notify the callback function of a revision
364 * @param WikiRevision $revision
367 private function revisionCallback( $revision ) {
368 if ( isset( $this->mRevisionCallback
) ) {
369 return call_user_func_array( $this->mRevisionCallback
,
370 array( $revision, $this ) );
377 * Notify the callback function of a new log item
378 * @param WikiRevision $revision
381 private function logItemCallback( $revision ) {
382 if ( isset( $this->mLogItemCallback
) ) {
383 return call_user_func_array( $this->mLogItemCallback
,
384 array( $revision, $this ) );
391 * Shouldn't something like this be built-in to XMLReader?
392 * Fetches text contents of the current element, assuming
393 * no sub-elements or such scary things.
397 public function nodeContents() {
398 if ( $this->reader
->isEmptyElement
) {
402 while ( $this->reader
->read() ) {
403 switch ( $this->reader
->nodeType
) {
404 case XmlReader
::TEXT
:
405 case XmlReader
::SIGNIFICANT_WHITESPACE
:
406 $buffer .= $this->reader
->value
;
408 case XmlReader
::END_ELEMENT
:
413 $this->reader
->close();
419 /** Left in for debugging */
420 private function dumpElement() {
421 static $lookup = null;
423 $xmlReaderConstants = array(
438 "SIGNIFICANT_WHITESPACE",
445 foreach ( $xmlReaderConstants as $name ) {
446 $lookup[constant( "XmlReader::$name" )] = $name;
451 $lookup[$this->reader
->nodeType
],
458 * Primary entry point
459 * @throws MWException
462 public function doImport() {
464 // Calls to reader->read need to be wrapped in calls to
465 // libxml_disable_entity_loader() to avoid local file
466 // inclusion attacks (bug 46932).
467 $oldDisable = libxml_disable_entity_loader( true );
468 $this->reader
->read();
470 if ( $this->reader
->name
!= 'mediawiki' ) {
471 libxml_disable_entity_loader( $oldDisable );
472 throw new MWException( "Expected <mediawiki> tag, got " .
473 $this->reader
->name
);
475 $this->debug( "<mediawiki> tag is correct." );
477 $this->debug( "Starting primary dump processing loop." );
479 $keepReading = $this->reader
->read();
481 while ( $keepReading ) {
482 $tag = $this->reader
->name
;
483 $type = $this->reader
->nodeType
;
485 if ( !wfRunHooks( 'ImportHandleToplevelXMLTag', array( $this ) ) ) {
487 } elseif ( $tag == 'mediawiki' && $type == XmlReader
::END_ELEMENT
) {
489 } elseif ( $tag == 'siteinfo' ) {
490 $this->handleSiteInfo();
491 } elseif ( $tag == 'page' ) {
493 } elseif ( $tag == 'logitem' ) {
494 $this->handleLogItem();
495 } elseif ( $tag != '#text' ) {
496 $this->warn( "Unhandled top-level XML tag $tag" );
502 $keepReading = $this->reader
->next();
504 $this->debug( "Skip" );
506 $keepReading = $this->reader
->read();
510 libxml_disable_entity_loader( $oldDisable );
516 * @throws MWException
518 private function handleSiteInfo() {
519 // Site info is useful, but not actually used for dump imports.
520 // Includes a quick short-circuit to save performance.
521 if ( ! $this->mSiteInfoCallback
) {
522 $this->reader
->next();
525 throw new MWException( "SiteInfo tag is not yet handled, do not set mSiteInfoCallback" );
528 private function handleLogItem() {
529 $this->debug( "Enter log item handler." );
532 // Fields that can just be stuffed in the pageInfo object
533 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
534 'logtitle', 'params' );
536 while ( $this->reader
->read() ) {
537 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
538 $this->reader
->name
== 'logitem' ) {
542 $tag = $this->reader
->name
;
544 if ( !wfRunHooks( 'ImportHandleLogItemXMLTag', array(
548 } elseif ( in_array( $tag, $normalFields ) ) {
549 $logInfo[$tag] = $this->nodeContents();
550 } elseif ( $tag == 'contributor' ) {
551 $logInfo['contributor'] = $this->handleContributor();
552 } elseif ( $tag != '#text' ) {
553 $this->warn( "Unhandled log-item XML tag $tag" );
557 $this->processLogItem( $logInfo );
561 * @param array $logInfo
564 private function processLogItem( $logInfo ) {
565 $revision = new WikiRevision
;
567 $revision->setID( $logInfo['id'] );
568 $revision->setType( $logInfo['type'] );
569 $revision->setAction( $logInfo['action'] );
570 $revision->setTimestamp( $logInfo['timestamp'] );
571 $revision->setParams( $logInfo['params'] );
572 $revision->setTitle( Title
::newFromText( $logInfo['logtitle'] ) );
573 $revision->setNoUpdates( $this->mNoUpdates
);
575 if ( isset( $logInfo['comment'] ) ) {
576 $revision->setComment( $logInfo['comment'] );
579 if ( isset( $logInfo['contributor']['ip'] ) ) {
580 $revision->setUserIP( $logInfo['contributor']['ip'] );
582 if ( isset( $logInfo['contributor']['username'] ) ) {
583 $revision->setUserName( $logInfo['contributor']['username'] );
586 return $this->logItemCallback( $revision );
589 private function handlePage() {
591 $this->debug( "Enter page handler." );
592 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
594 // Fields that can just be stuffed in the pageInfo object
595 $normalFields = array( 'title', 'id', 'redirect', 'restrictions' );
600 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
601 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
602 $this->reader
->name
== 'page' ) {
606 $tag = $this->reader
->name
;
609 // The title is invalid, bail out of this page
611 } elseif ( !wfRunHooks( 'ImportHandlePageXMLTag', array( $this,
614 } elseif ( in_array( $tag, $normalFields ) ) {
615 $pageInfo[$tag] = $this->nodeContents();
616 if ( $tag == 'title' ) {
617 $title = $this->processTitle( $pageInfo['title'] );
624 $this->pageCallback( $title );
625 list( $pageInfo['_title'], $origTitle ) = $title;
627 } elseif ( $tag == 'revision' ) {
628 $this->handleRevision( $pageInfo );
629 } elseif ( $tag == 'upload' ) {
630 $this->handleUpload( $pageInfo );
631 } elseif ( $tag != '#text' ) {
632 $this->warn( "Unhandled page XML tag $tag" );
637 $this->pageOutCallback( $pageInfo['_title'], $origTitle,
638 $pageInfo['revisionCount'],
639 $pageInfo['successfulRevisionCount'],
644 * @param array $pageInfo
646 private function handleRevision( &$pageInfo ) {
647 $this->debug( "Enter revision handler" );
648 $revisionInfo = array();
650 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'model', 'format', 'text' );
654 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
655 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
656 $this->reader
->name
== 'revision' ) {
660 $tag = $this->reader
->name
;
662 if ( !wfRunHooks( 'ImportHandleRevisionXMLTag', array(
663 $this, $pageInfo, $revisionInfo
666 } elseif ( in_array( $tag, $normalFields ) ) {
667 $revisionInfo[$tag] = $this->nodeContents();
668 } elseif ( $tag == 'contributor' ) {
669 $revisionInfo['contributor'] = $this->handleContributor();
670 } elseif ( $tag != '#text' ) {
671 $this->warn( "Unhandled revision XML tag $tag" );
676 $pageInfo['revisionCount']++
;
677 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
678 $pageInfo['successfulRevisionCount']++
;
683 * @param array $pageInfo
684 * @param array $revisionInfo
687 private function processRevision( $pageInfo, $revisionInfo ) {
688 $revision = new WikiRevision
;
690 if ( isset( $revisionInfo['id'] ) ) {
691 $revision->setID( $revisionInfo['id'] );
693 if ( isset( $revisionInfo['text'] ) ) {
694 $revision->setText( $revisionInfo['text'] );
696 if ( isset( $revisionInfo['model'] ) ) {
697 $revision->setModel( $revisionInfo['model'] );
699 if ( isset( $revisionInfo['format'] ) ) {
700 $revision->setFormat( $revisionInfo['format'] );
702 $revision->setTitle( $pageInfo['_title'] );
704 if ( isset( $revisionInfo['timestamp'] ) ) {
705 $revision->setTimestamp( $revisionInfo['timestamp'] );
707 $revision->setTimestamp( wfTimestampNow() );
710 if ( isset( $revisionInfo['comment'] ) ) {
711 $revision->setComment( $revisionInfo['comment'] );
714 if ( isset( $revisionInfo['minor'] ) ) {
715 $revision->setMinor( true );
717 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
718 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
720 if ( isset( $revisionInfo['contributor']['username'] ) ) {
721 $revision->setUserName( $revisionInfo['contributor']['username'] );
723 $revision->setNoUpdates( $this->mNoUpdates
);
725 return $this->revisionCallback( $revision );
729 * @param array $pageInfo
732 private function handleUpload( &$pageInfo ) {
733 $this->debug( "Enter upload handler" );
734 $uploadInfo = array();
736 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
737 'src', 'size', 'sha1base36', 'archivename', 'rel' );
741 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
742 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
743 $this->reader
->name
== 'upload' ) {
747 $tag = $this->reader
->name
;
749 if ( !wfRunHooks( 'ImportHandleUploadXMLTag', array(
753 } elseif ( in_array( $tag, $normalFields ) ) {
754 $uploadInfo[$tag] = $this->nodeContents();
755 } elseif ( $tag == 'contributor' ) {
756 $uploadInfo['contributor'] = $this->handleContributor();
757 } elseif ( $tag == 'contents' ) {
758 $contents = $this->nodeContents();
759 $encoding = $this->reader
->getAttribute( 'encoding' );
760 if ( $encoding === 'base64' ) {
761 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
762 $uploadInfo['isTempSrc'] = true;
764 } elseif ( $tag != '#text' ) {
765 $this->warn( "Unhandled upload XML tag $tag" );
770 if ( $this->mImageBasePath
&& isset( $uploadInfo['rel'] ) ) {
771 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
772 if ( file_exists( $path ) ) {
773 $uploadInfo['fileSrc'] = $path;
774 $uploadInfo['isTempSrc'] = false;
778 if ( $this->mImportUploads
) {
779 return $this->processUpload( $pageInfo, $uploadInfo );
784 * @param string $contents
787 private function dumpTemp( $contents ) {
788 $filename = tempnam( wfTempDir(), 'importupload' );
789 file_put_contents( $filename, $contents );
794 * @param array $pageInfo
795 * @param array $uploadInfo
798 private function processUpload( $pageInfo, $uploadInfo ) {
799 $revision = new WikiRevision
;
800 $text = isset( $uploadInfo['text'] ) ?
$uploadInfo['text'] : '';
802 $revision->setTitle( $pageInfo['_title'] );
803 $revision->setID( $pageInfo['id'] );
804 $revision->setTimestamp( $uploadInfo['timestamp'] );
805 $revision->setText( $text );
806 $revision->setFilename( $uploadInfo['filename'] );
807 if ( isset( $uploadInfo['archivename'] ) ) {
808 $revision->setArchiveName( $uploadInfo['archivename'] );
810 $revision->setSrc( $uploadInfo['src'] );
811 if ( isset( $uploadInfo['fileSrc'] ) ) {
812 $revision->setFileSrc( $uploadInfo['fileSrc'],
813 !empty( $uploadInfo['isTempSrc'] ) );
815 if ( isset( $uploadInfo['sha1base36'] ) ) {
816 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
818 $revision->setSize( intval( $uploadInfo['size'] ) );
819 $revision->setComment( $uploadInfo['comment'] );
821 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
822 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
824 if ( isset( $uploadInfo['contributor']['username'] ) ) {
825 $revision->setUserName( $uploadInfo['contributor']['username'] );
827 $revision->setNoUpdates( $this->mNoUpdates
);
829 return call_user_func( $this->mUploadCallback
, $revision );
835 private function handleContributor() {
836 $fields = array( 'id', 'ip', 'username' );
839 while ( $this->reader
->read() ) {
840 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
841 $this->reader
->name
== 'contributor' ) {
845 $tag = $this->reader
->name
;
847 if ( in_array( $tag, $fields ) ) {
848 $info[$tag] = $this->nodeContents();
856 * @param string $text
859 private function processTitle( $text ) {
860 global $wgCommandLineMode;
863 $origTitle = Title
::newFromText( $workTitle );
865 if ( !is_null( $this->mTargetNamespace
) && !is_null( $origTitle ) ) {
866 # makeTitleSafe, because $origTitle can have a interwiki (different setting of interwiki map)
867 # and than dbKey can begin with a lowercase char
868 $title = Title
::makeTitleSafe( $this->mTargetNamespace
,
869 $origTitle->getDBkey() );
871 if ( !is_null( $this->mTargetRootPage
) ) {
872 $workTitle = $this->mTargetRootPage
. '/' . $workTitle;
874 $title = Title
::newFromText( $workTitle );
877 if ( is_null( $title ) ) {
878 # Invalid page title? Ignore the page
879 $this->notice( 'import-error-invalid', $workTitle );
881 } elseif ( $title->isExternal() ) {
882 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
884 } elseif ( !$title->canExist() ) {
885 $this->notice( 'import-error-special', $title->getPrefixedText() );
887 } elseif ( !$title->userCan( 'edit' ) && !$wgCommandLineMode ) {
888 # Do not import if the importing wiki user cannot edit this page
889 $this->notice( 'import-error-edit', $title->getPrefixedText() );
891 } elseif ( !$title->exists() && !$title->userCan( 'create' ) && !$wgCommandLineMode ) {
892 # Do not import if the importing wiki user cannot create this page
893 $this->notice( 'import-error-create', $title->getPrefixedText() );
897 return array( $title, $origTitle );
901 /** This is a horrible hack used to keep source compatibility */
902 class UploadSourceAdapter
{
903 static $sourceRegistrations = array();
910 * @param string $source
913 static function registerSource( $source ) {
914 $id = wfRandomString();
916 self
::$sourceRegistrations[$id] = $source;
922 * @param string $path
923 * @param string $mode
924 * @param array $options
925 * @param string $opened_path
928 function stream_open( $path, $mode, $options, &$opened_path ) {
929 $url = parse_url( $path );
932 if ( !isset( self
::$sourceRegistrations[$id] ) ) {
936 $this->mSource
= self
::$sourceRegistrations[$id];
945 function stream_read( $count ) {
949 while ( !$leave && !$this->mSource
->atEnd() &&
950 strlen( $this->mBuffer
) < $count ) {
951 $read = $this->mSource
->readChunk();
953 if ( !strlen( $read ) ) {
957 $this->mBuffer
.= $read;
960 if ( strlen( $this->mBuffer
) ) {
961 $return = substr( $this->mBuffer
, 0, $count );
962 $this->mBuffer
= substr( $this->mBuffer
, $count );
965 $this->mPosition +
= strlen( $return );
971 * @param string $data
974 function stream_write( $data ) {
981 function stream_tell() {
982 return $this->mPosition
;
988 function stream_eof() {
989 return $this->mSource
->atEnd();
995 function url_stat() {
998 $result['dev'] = $result[0] = 0;
999 $result['ino'] = $result[1] = 0;
1000 $result['mode'] = $result[2] = 0;
1001 $result['nlink'] = $result[3] = 0;
1002 $result['uid'] = $result[4] = 0;
1003 $result['gid'] = $result[5] = 0;
1004 $result['rdev'] = $result[6] = 0;
1005 $result['size'] = $result[7] = 0;
1006 $result['atime'] = $result[8] = 0;
1007 $result['mtime'] = $result[9] = 0;
1008 $result['ctime'] = $result[10] = 0;
1009 $result['blksize'] = $result[11] = 0;
1010 $result['blocks'] = $result[12] = 0;
1016 class XMLReader2
extends XMLReader
{
1019 * @return bool|string
1021 function nodeContents() {
1022 if ( $this->isEmptyElement
) {
1026 while ( $this->read() ) {
1027 switch ( $this->nodeType
) {
1028 case XmlReader
::TEXT
:
1029 case XmlReader
::SIGNIFICANT_WHITESPACE
:
1030 $buffer .= $this->value
;
1032 case XmlReader
::END_ELEMENT
:
1036 return $this->close();
1041 * @todo document (e.g. one-sentence class description).
1042 * @ingroup SpecialPage
1044 class WikiRevision
{
1045 var $importer = null;
1052 var $timestamp = "20010115000000";
1054 var $user_text = "";
1058 var $content = null;
1065 var $sha1base36 = false;
1066 var $isTemp = false;
1067 var $archiveName = '';
1069 private $mNoUpdates = false;
1072 * @param Title $title
1073 * @throws MWException
1075 function setTitle( $title ) {
1076 if ( is_object( $title ) ) {
1077 $this->title
= $title;
1078 } elseif ( is_null( $title ) ) {
1079 throw new MWException( "WikiRevision given a null title in import. You may need to adjust \$wgLegalTitleChars." );
1081 throw new MWException( "WikiRevision given non-object title in import." );
1088 function setID( $id ) {
1095 function setTimestamp( $ts ) {
1096 # 2003-08-05T18:30:02Z
1097 $this->timestamp
= wfTimestamp( TS_MW
, $ts );
1101 * @param string $user
1103 function setUsername( $user ) {
1104 $this->user_text
= $user;
1110 function setUserIP( $ip ) {
1111 $this->user_text
= $ip;
1115 * @param string $model
1117 function setModel( $model ) {
1118 $this->model
= $model;
1122 * @param string $format
1124 function setFormat( $format ) {
1125 $this->format
= $format;
1129 * @param string $text
1131 function setText( $text ) {
1132 $this->text
= $text;
1136 * @param string $text
1138 function setComment( $text ) {
1139 $this->comment
= $text;
1143 * @param bool $minor
1145 function setMinor( $minor ) {
1146 $this->minor
= (bool)$minor;
1152 function setSrc( $src ) {
1157 * @param string $src
1158 * @param bool $isTemp
1160 function setFileSrc( $src, $isTemp ) {
1161 $this->fileSrc
= $src;
1162 $this->fileIsTemp
= $isTemp;
1166 * @param string $sha1base36
1168 function setSha1Base36( $sha1base36 ) {
1169 $this->sha1base36
= $sha1base36;
1173 * @param string $filename
1175 function setFilename( $filename ) {
1176 $this->filename
= $filename;
1180 * @param string $archiveName
1182 function setArchiveName( $archiveName ) {
1183 $this->archiveName
= $archiveName;
1189 function setSize( $size ) {
1190 $this->size
= intval( $size );
1194 * @param string $type
1196 function setType( $type ) {
1197 $this->type
= $type;
1201 * @param string $action
1203 function setAction( $action ) {
1204 $this->action
= $action;
1208 * @param array $params
1210 function setParams( $params ) {
1211 $this->params
= $params;
1215 * @param bool $noupdates
1217 public function setNoUpdates( $noupdates ) {
1218 $this->mNoUpdates
= $noupdates;
1224 function getTitle() {
1225 return $this->title
;
1238 function getTimestamp() {
1239 return $this->timestamp
;
1245 function getUser() {
1246 return $this->user_text
;
1252 * @deprecated Since 1.21, use getContent() instead.
1254 function getText() {
1255 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1263 function getContent() {
1264 if ( is_null( $this->content
) ) {
1266 ContentHandler
::makeContent(
1274 return $this->content
;
1280 function getModel() {
1281 if ( is_null( $this->model
) ) {
1282 $this->model
= $this->getTitle()->getContentModel();
1285 return $this->model
;
1291 function getFormat() {
1292 if ( is_null( $this->model
) ) {
1293 $this->format
= ContentHandler
::getForTitle( $this->getTitle() )->getDefaultFormat();
1296 return $this->format
;
1302 function getComment() {
1303 return $this->comment
;
1309 function getMinor() {
1310 return $this->minor
;
1321 * @return bool|string
1323 function getSha1() {
1324 if ( $this->sha1base36
) {
1325 return wfBaseConvert( $this->sha1base36
, 36, 16 );
1333 function getFileSrc() {
1334 return $this->fileSrc
;
1340 function isTempSrc() {
1341 return $this->isTemp
;
1347 function getFilename() {
1348 return $this->filename
;
1354 function getArchiveName() {
1355 return $this->archiveName
;
1361 function getSize() {
1368 function getType() {
1375 function getAction() {
1376 return $this->action
;
1382 function getParams() {
1383 return $this->params
;
1389 function importOldRevision() {
1390 $dbw = wfGetDB( DB_MASTER
);
1392 # Sneak a single revision into place
1393 $user = User
::newFromName( $this->getUser() );
1395 $userId = intval( $user->getId() );
1396 $userText = $user->getName();
1400 $userText = $this->getUser();
1401 $userObj = new User
;
1404 // avoid memory leak...?
1405 $linkCache = LinkCache
::singleton();
1406 $linkCache->clear();
1408 $page = WikiPage
::factory( $this->title
);
1409 if ( !$page->exists() ) {
1410 # must create the page...
1411 $pageId = $page->insertOn( $dbw );
1413 $oldcountable = null;
1415 $pageId = $page->getId();
1418 $prior = $dbw->selectField( 'revision', '1',
1419 array( 'rev_page' => $pageId,
1420 'rev_timestamp' => $dbw->timestamp( $this->timestamp
),
1421 'rev_user_text' => $userText,
1422 'rev_comment' => $this->getComment() ),
1426 // @todo FIXME: This could fail slightly for multiple matches :P
1427 wfDebug( __METHOD__
. ": skipping existing revision for [[" .
1428 $this->title
->getPrefixedText() . "]], timestamp " . $this->timestamp
. "\n" );
1431 $oldcountable = $page->isCountable();
1434 # @todo FIXME: Use original rev_id optionally (better for backups)
1436 $revision = new Revision( array(
1437 'title' => $this->title
,
1439 'content_model' => $this->getModel(),
1440 'content_format' => $this->getFormat(),
1441 'text' => $this->getContent()->serialize( $this->getFormat() ), //XXX: just set 'content' => $this->getContent()?
1442 'comment' => $this->getComment(),
1444 'user_text' => $userText,
1445 'timestamp' => $this->timestamp
,
1446 'minor_edit' => $this->minor
,
1448 $revision->insertOn( $dbw );
1449 $changed = $page->updateIfNewerOn( $dbw, $revision );
1451 if ( $changed !== false && !$this->mNoUpdates
) {
1452 wfDebug( __METHOD__
. ": running updates\n" );
1453 $page->doEditUpdates( $revision, $userObj, array( 'created' => $created, 'oldcountable' => $oldcountable ) );
1462 function importLogItem() {
1463 $dbw = wfGetDB( DB_MASTER
);
1464 # @todo FIXME: This will not record autoblocks
1465 if ( !$this->getTitle() ) {
1466 wfDebug( __METHOD__
. ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1467 $this->timestamp
. "\n" );
1470 # Check if it exists already
1471 // @todo FIXME: Use original log ID (better for backups)
1472 $prior = $dbw->selectField( 'logging', '1',
1473 array( 'log_type' => $this->getType(),
1474 'log_action' => $this->getAction(),
1475 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1476 'log_namespace' => $this->getTitle()->getNamespace(),
1477 'log_title' => $this->getTitle()->getDBkey(),
1478 'log_comment' => $this->getComment(),
1479 #'log_user_text' => $this->user_text,
1480 'log_params' => $this->params
),
1483 // @todo FIXME: This could fail slightly for multiple matches :P
1485 wfDebug( __METHOD__
. ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp " .
1486 $this->timestamp
. "\n" );
1489 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1491 'log_id' => $log_id,
1492 'log_type' => $this->type
,
1493 'log_action' => $this->action
,
1494 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1495 'log_user' => User
::idFromName( $this->user_text
),
1496 #'log_user_text' => $this->user_text,
1497 'log_namespace' => $this->getTitle()->getNamespace(),
1498 'log_title' => $this->getTitle()->getDBkey(),
1499 'log_comment' => $this->getComment(),
1500 'log_params' => $this->params
1502 $dbw->insert( 'logging', $data, __METHOD__
);
1508 function importUpload() {
1510 $archiveName = $this->getArchiveName();
1511 if ( $archiveName ) {
1512 wfDebug( __METHOD__
. "Importing archived file as $archiveName\n" );
1513 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1514 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1516 $file = wfLocalFile( $this->getTitle() );
1517 wfDebug( __METHOD__
. 'Importing new file as ' . $file->getName() . "\n" );
1518 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1519 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1520 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1521 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1522 wfDebug( __METHOD__
. "File already exists; importing as $archiveName\n" );
1526 wfDebug( __METHOD__
. ': Bad file for ' . $this->getTitle() . "\n" );
1530 # Get the file source or download if necessary
1531 $source = $this->getFileSrc();
1532 $flags = $this->isTempSrc() ? File
::DELETE_SOURCE
: 0;
1534 $source = $this->downloadSource();
1535 $flags |
= File
::DELETE_SOURCE
;
1538 wfDebug( __METHOD__
. ": Could not fetch remote file.\n" );
1541 $sha1 = $this->getSha1();
1542 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1543 if ( $flags & File
::DELETE_SOURCE
) {
1544 # Broken file; delete it if it is a temporary file
1547 wfDebug( __METHOD__
. ": Corrupt file $source.\n" );
1551 $user = User
::newFromName( $this->user_text
);
1553 # Do the actual upload
1554 if ( $archiveName ) {
1555 $status = $file->uploadOld( $source, $archiveName,
1556 $this->getTimestamp(), $this->getComment(), $user, $flags );
1558 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1559 $flags, false, $this->getTimestamp(), $user );
1562 if ( $status->isGood() ) {
1563 wfDebug( __METHOD__
. ": Successful\n" );
1566 wfDebug( __METHOD__
. ': failed: ' . $status->getXml() . "\n" );
1572 * @return bool|string
1574 function downloadSource() {
1575 global $wgEnableUploads;
1576 if ( !$wgEnableUploads ) {
1580 $tempo = tempnam( wfTempDir(), 'download' );
1581 $f = fopen( $tempo, 'wb' );
1583 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1588 $src = $this->getSrc();
1589 $data = Http
::get( $src );
1591 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1597 fwrite( $f, $data );
1606 * @todo document (e.g. one-sentence class description).
1607 * @ingroup SpecialPage
1609 class ImportStringSource
{
1610 function __construct( $string ) {
1611 $this->mString
= $string;
1612 $this->mRead
= false;
1619 return $this->mRead
;
1623 * @return bool|string
1625 function readChunk() {
1626 if ( $this->atEnd() ) {
1629 $this->mRead
= true;
1630 return $this->mString
;
1635 * @todo document (e.g. one-sentence class description).
1636 * @ingroup SpecialPage
1638 class ImportStreamSource
{
1639 function __construct( $handle ) {
1640 $this->mHandle
= $handle;
1647 return feof( $this->mHandle
);
1653 function readChunk() {
1654 return fread( $this->mHandle
, 32768 );
1658 * @param string $filename
1661 static function newFromFile( $filename ) {
1662 wfSuppressWarnings();
1663 $file = fopen( $filename, 'rt' );
1664 wfRestoreWarnings();
1666 return Status
::newFatal( "importcantopen" );
1668 return Status
::newGood( new ImportStreamSource( $file ) );
1672 * @param string $fieldname
1675 static function newFromUpload( $fieldname = "xmlimport" ) {
1676 $upload =& $_FILES[$fieldname];
1678 if ( $upload === null ||
!$upload['name'] ) {
1679 return Status
::newFatal( 'importnofile' );
1681 if ( !empty( $upload['error'] ) ) {
1682 switch ( $upload['error'] ) {
1683 case 1: # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1684 return Status
::newFatal( 'importuploaderrorsize' );
1685 case 2: # The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
1686 return Status
::newFatal( 'importuploaderrorsize' );
1687 case 3: # The uploaded file was only partially uploaded
1688 return Status
::newFatal( 'importuploaderrorpartial' );
1689 case 6: #Missing a temporary folder.
1690 return Status
::newFatal( 'importuploaderrortemp' );
1691 # case else: # Currently impossible
1695 $fname = $upload['tmp_name'];
1696 if ( is_uploaded_file( $fname ) ) {
1697 return ImportStreamSource
::newFromFile( $fname );
1699 return Status
::newFatal( 'importnofile' );
1704 * @param string $url
1705 * @param string $method
1708 static function newFromURL( $url, $method = 'GET' ) {
1709 wfDebug( __METHOD__
. ": opening $url\n" );
1710 # Use the standard HTTP fetch function; it times out
1711 # quicker and sorts out user-agent problems which might
1712 # otherwise prevent importing from large sites, such
1713 # as the Wikimedia cluster, etc.
1714 $data = Http
::request( $method, $url, array( 'followRedirects' => true ) );
1715 if ( $data !== false ) {
1717 fwrite( $file, $data );
1720 return Status
::newGood( new ImportStreamSource( $file ) );
1722 return Status
::newFatal( 'importcantopen' );
1727 * @param string $interwiki
1728 * @param string $page
1729 * @param bool $history
1730 * @param bool $templates
1731 * @param int $pageLinkDepth
1734 public static function newFromInterwiki( $interwiki, $page, $history = false, $templates = false, $pageLinkDepth = 0 ) {
1735 if ( $page == '' ) {
1736 return Status
::newFatal( 'import-noarticle' );
1738 $link = Title
::newFromText( "$interwiki:Special:Export/$page" );
1739 if ( is_null( $link ) ||
!$link->isExternal() ) {
1740 return Status
::newFatal( 'importbadinterwiki' );
1744 $params['history'] = 1;
1747 $params['templates'] = 1;
1749 if ( $pageLinkDepth ) {
1750 $params['pagelink-depth'] = $pageLinkDepth;
1752 $url = $link->getFullURL( $params );
1753 # For interwikis, use POST to avoid redirects.
1754 return ImportStreamSource
::newFromURL( $url, "POST" );