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;
44 * Creates an ImportXMLReader drawing from the source provided
45 * @param ImportStreamSource $source
46 * @param Config $config
48 function __construct( ImportStreamSource
$source, Config
$config = null ) {
49 $this->reader
= new XMLReader();
51 wfDeprecated( __METHOD__
. ' without a Config instance', '1.25' );
52 $config = ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
54 $this->config
= $config;
56 if ( !in_array( 'uploadsource', stream_get_wrappers() ) ) {
57 stream_wrapper_register( 'uploadsource', 'UploadSourceAdapter' );
59 $id = UploadSourceAdapter
::registerSource( $source );
60 if ( defined( 'LIBXML_PARSEHUGE' ) ) {
61 $this->reader
->open( "uploadsource://$id", null, LIBXML_PARSEHUGE
);
63 $this->reader
->open( "uploadsource://$id" );
67 $this->setRevisionCallback( array( $this, "importRevision" ) );
68 $this->setUploadCallback( array( $this, 'importUpload' ) );
69 $this->setLogItemCallback( array( $this, 'importLogItem' ) );
70 $this->setPageOutCallback( array( $this, 'finishImportPage' ) );
74 * @return null|XMLReader
76 public function getReader() {
80 public function throwXmlError( $err ) {
81 $this->debug( "FAILURE: $err" );
82 wfDebug( "WikiImporter XML error: $err\n" );
85 public function debug( $data ) {
86 if ( $this->mDebug
) {
87 wfDebug( "IMPORT: $data\n" );
91 public function warn( $data ) {
92 wfDebug( "IMPORT: $data\n" );
95 public function notice( $msg /*, $param, ...*/ ) {
96 $params = func_get_args();
97 array_shift( $params );
99 if ( is_callable( $this->mNoticeCallback
) ) {
100 call_user_func( $this->mNoticeCallback
, $msg, $params );
101 } else { # No ImportReporter -> CLI
102 echo wfMessage( $msg, $params )->text() . "\n";
110 function setDebug( $debug ) {
111 $this->mDebug
= $debug;
115 * Set 'no updates' mode. In this mode, the link tables will not be updated by the importer
116 * @param bool $noupdates
118 function setNoUpdates( $noupdates ) {
119 $this->mNoUpdates
= $noupdates;
123 * Set a callback that displays notice messages
125 * @param callable $callback
128 public function setNoticeCallback( $callback ) {
129 return wfSetVar( $this->mNoticeCallback
, $callback );
133 * Sets the action to perform as each new page in the stream is reached.
134 * @param callable $callback
137 public function setPageCallback( $callback ) {
138 $previous = $this->mPageCallback
;
139 $this->mPageCallback
= $callback;
144 * Sets the action to perform as each page in the stream is completed.
145 * Callback accepts the page title (as a Title object), a second object
146 * with the original title form (in case it's been overridden into a
147 * local namespace), and a count of revisions.
149 * @param callable $callback
152 public function setPageOutCallback( $callback ) {
153 $previous = $this->mPageOutCallback
;
154 $this->mPageOutCallback
= $callback;
159 * Sets the action to perform as each page revision is reached.
160 * @param callable $callback
163 public function setRevisionCallback( $callback ) {
164 $previous = $this->mRevisionCallback
;
165 $this->mRevisionCallback
= $callback;
170 * Sets the action to perform as each file upload version is reached.
171 * @param callable $callback
174 public function setUploadCallback( $callback ) {
175 $previous = $this->mUploadCallback
;
176 $this->mUploadCallback
= $callback;
181 * Sets the action to perform as each log item reached.
182 * @param callable $callback
185 public function setLogItemCallback( $callback ) {
186 $previous = $this->mLogItemCallback
;
187 $this->mLogItemCallback
= $callback;
192 * Sets the action to perform when site info is encountered
193 * @param callable $callback
196 public function setSiteInfoCallback( $callback ) {
197 $previous = $this->mSiteInfoCallback
;
198 $this->mSiteInfoCallback
= $callback;
203 * Set a target namespace to override the defaults
204 * @param null|int $namespace
207 public function setTargetNamespace( $namespace ) {
208 if ( is_null( $namespace ) ) {
209 // Don't override namespaces
210 $this->mTargetNamespace
= null;
211 } elseif ( $namespace >= 0 ) {
212 // @todo FIXME: Check for validity
213 $this->mTargetNamespace
= intval( $namespace );
220 * Set a target root page under which all pages are imported
221 * @param null|string $rootpage
224 public function setTargetRootPage( $rootpage ) {
225 $status = Status
::newGood();
226 if ( is_null( $rootpage ) ) {
228 $this->mTargetRootPage
= null;
229 } elseif ( $rootpage !== '' ) {
230 $rootpage = rtrim( $rootpage, '/' ); //avoid double slashes
231 $title = Title
::newFromText( $rootpage, !is_null( $this->mTargetNamespace
)
232 ?
$this->mTargetNamespace
236 if ( !$title ||
$title->isExternal() ) {
237 $status->fatal( 'import-rootpage-invalid' );
239 if ( !MWNamespace
::hasSubpages( $title->getNamespace() ) ) {
242 $displayNSText = $title->getNamespace() == NS_MAIN
243 ?
wfMessage( 'blanknamespace' )->text()
244 : $wgContLang->getNsText( $title->getNamespace() );
245 $status->fatal( 'import-rootpage-nosubpage', $displayNSText );
247 // set namespace to 'all', so the namespace check in processTitle() can passed
248 $this->setTargetNamespace( null );
249 $this->mTargetRootPage
= $title->getPrefixedDBkey();
259 public function setImageBasePath( $dir ) {
260 $this->mImageBasePath
= $dir;
264 * @param bool $import
266 public function setImportUploads( $import ) {
267 $this->mImportUploads
= $import;
271 * Default per-revision callback, performs the import.
272 * @param WikiRevision $revision
275 public function importRevision( $revision ) {
276 if ( !$revision->getContentHandler()->canBeUsedOn( $revision->getTitle() ) ) {
277 $this->notice( 'import-error-bad-location',
278 $revision->getTitle()->getPrefixedText(),
280 $revision->getModel(),
281 $revision->getFormat() );
287 $dbw = wfGetDB( DB_MASTER
);
288 return $dbw->deadlockLoop( array( $revision, 'importOldRevision' ) );
289 } catch ( MWContentSerializationException
$ex ) {
290 $this->notice( 'import-error-unserialize',
291 $revision->getTitle()->getPrefixedText(),
293 $revision->getModel(),
294 $revision->getFormat() );
301 * Default per-revision callback, performs the import.
302 * @param WikiRevision $revision
305 public function importLogItem( $revision ) {
306 $dbw = wfGetDB( DB_MASTER
);
307 return $dbw->deadlockLoop( array( $revision, 'importLogItem' ) );
312 * @param WikiRevision $revision
315 public function importUpload( $revision ) {
316 $dbw = wfGetDB( DB_MASTER
);
317 return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
321 * Mostly for hook use
322 * @param Title $title
323 * @param string $origTitle
324 * @param int $revCount
325 * @param int $sRevCount
326 * @param array $pageInfo
329 public function finishImportPage( $title, $origTitle, $revCount, $sRevCount, $pageInfo ) {
330 $args = func_get_args();
331 return wfRunHooks( 'AfterImportPage', $args );
335 * Alternate per-revision callback, for debugging.
336 * @param WikiRevision $revision
338 public function debugRevisionHandler( &$revision ) {
339 $this->debug( "Got revision:" );
340 if ( is_object( $revision->title
) ) {
341 $this->debug( "-- Title: " . $revision->title
->getPrefixedText() );
343 $this->debug( "-- Title: <invalid>" );
345 $this->debug( "-- User: " . $revision->user_text
);
346 $this->debug( "-- Timestamp: " . $revision->timestamp
);
347 $this->debug( "-- Comment: " . $revision->comment
);
348 $this->debug( "-- Text: " . $revision->text
);
352 * Notify the callback function when a new "<page>" is reached.
353 * @param Title $title
355 function pageCallback( $title ) {
356 if ( isset( $this->mPageCallback
) ) {
357 call_user_func( $this->mPageCallback
, $title );
362 * Notify the callback function when a "</page>" is closed.
363 * @param Title $title
364 * @param Title $origTitle
365 * @param int $revCount
366 * @param int $sucCount Number of revisions for which callback returned true
367 * @param array $pageInfo Associative array of page information
369 private function pageOutCallback( $title, $origTitle, $revCount, $sucCount, $pageInfo ) {
370 if ( isset( $this->mPageOutCallback
) ) {
371 $args = func_get_args();
372 call_user_func_array( $this->mPageOutCallback
, $args );
377 * Notify the callback function of a revision
378 * @param WikiRevision $revision
381 private function revisionCallback( $revision ) {
382 if ( isset( $this->mRevisionCallback
) ) {
383 return call_user_func_array( $this->mRevisionCallback
,
384 array( $revision, $this ) );
391 * Notify the callback function of a new log item
392 * @param WikiRevision $revision
395 private function logItemCallback( $revision ) {
396 if ( isset( $this->mLogItemCallback
) ) {
397 return call_user_func_array( $this->mLogItemCallback
,
398 array( $revision, $this ) );
405 * Retrieves the contents of the named attribute of the current element.
406 * @param string $attr The name of the attribute
407 * @return string The value of the attribute or an empty string if it is not set in the current element.
409 public function nodeAttribute( $attr ) {
410 return $this->reader
->getAttribute( $attr );
414 * Shouldn't something like this be built-in to XMLReader?
415 * Fetches text contents of the current element, assuming
416 * no sub-elements or such scary things.
420 public function nodeContents() {
421 if ( $this->reader
->isEmptyElement
) {
425 while ( $this->reader
->read() ) {
426 switch ( $this->reader
->nodeType
) {
427 case XmlReader
::TEXT
:
428 case XmlReader
::SIGNIFICANT_WHITESPACE
:
429 $buffer .= $this->reader
->value
;
431 case XmlReader
::END_ELEMENT
:
436 $this->reader
->close();
441 * Primary entry point
442 * @throws MWException
445 public function doImport() {
446 // Calls to reader->read need to be wrapped in calls to
447 // libxml_disable_entity_loader() to avoid local file
448 // inclusion attacks (bug 46932).
449 $oldDisable = libxml_disable_entity_loader( true );
450 $this->reader
->read();
452 if ( $this->reader
->name
!= 'mediawiki' ) {
453 libxml_disable_entity_loader( $oldDisable );
454 throw new MWException( "Expected <mediawiki> tag, got " .
455 $this->reader
->name
);
457 $this->debug( "<mediawiki> tag is correct." );
459 $this->debug( "Starting primary dump processing loop." );
461 $keepReading = $this->reader
->read();
463 while ( $keepReading ) {
464 $tag = $this->reader
->name
;
465 $type = $this->reader
->nodeType
;
467 if ( !wfRunHooks( 'ImportHandleToplevelXMLTag', array( $this ) ) ) {
469 } elseif ( $tag == 'mediawiki' && $type == XmlReader
::END_ELEMENT
) {
471 } elseif ( $tag == 'siteinfo' ) {
472 $this->handleSiteInfo();
473 } elseif ( $tag == 'page' ) {
475 } elseif ( $tag == 'logitem' ) {
476 $this->handleLogItem();
477 } elseif ( $tag != '#text' ) {
478 $this->warn( "Unhandled top-level XML tag $tag" );
484 $keepReading = $this->reader
->next();
486 $this->debug( "Skip" );
488 $keepReading = $this->reader
->read();
492 libxml_disable_entity_loader( $oldDisable );
498 * @throws MWException
500 private function handleSiteInfo() {
501 // Site info is useful, but not actually used for dump imports.
502 // Includes a quick short-circuit to save performance.
503 if ( !$this->mSiteInfoCallback
) {
504 $this->reader
->next();
507 throw new MWException( "SiteInfo tag is not yet handled, do not set mSiteInfoCallback" );
510 private function handleLogItem() {
511 $this->debug( "Enter log item handler." );
514 // Fields that can just be stuffed in the pageInfo object
515 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
516 'logtitle', 'params' );
518 while ( $this->reader
->read() ) {
519 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
520 $this->reader
->name
== 'logitem' ) {
524 $tag = $this->reader
->name
;
526 if ( !wfRunHooks( 'ImportHandleLogItemXMLTag', array(
530 } elseif ( in_array( $tag, $normalFields ) ) {
531 $logInfo[$tag] = $this->nodeContents();
532 } elseif ( $tag == 'contributor' ) {
533 $logInfo['contributor'] = $this->handleContributor();
534 } elseif ( $tag != '#text' ) {
535 $this->warn( "Unhandled log-item XML tag $tag" );
539 $this->processLogItem( $logInfo );
543 * @param array $logInfo
546 private function processLogItem( $logInfo ) {
547 $revision = new WikiRevision( $this->config
);
549 $revision->setID( $logInfo['id'] );
550 $revision->setType( $logInfo['type'] );
551 $revision->setAction( $logInfo['action'] );
552 $revision->setTimestamp( $logInfo['timestamp'] );
553 $revision->setParams( $logInfo['params'] );
554 $revision->setTitle( Title
::newFromText( $logInfo['logtitle'] ) );
555 $revision->setNoUpdates( $this->mNoUpdates
);
557 if ( isset( $logInfo['comment'] ) ) {
558 $revision->setComment( $logInfo['comment'] );
561 if ( isset( $logInfo['contributor']['ip'] ) ) {
562 $revision->setUserIP( $logInfo['contributor']['ip'] );
564 if ( isset( $logInfo['contributor']['username'] ) ) {
565 $revision->setUserName( $logInfo['contributor']['username'] );
568 return $this->logItemCallback( $revision );
571 private function handlePage() {
573 $this->debug( "Enter page handler." );
574 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
576 // Fields that can just be stuffed in the pageInfo object
577 $normalFields = array( 'title', 'id', 'redirect', 'restrictions' );
582 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
583 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
584 $this->reader
->name
== 'page' ) {
588 $tag = $this->reader
->name
;
591 // The title is invalid, bail out of this page
593 } elseif ( !wfRunHooks( 'ImportHandlePageXMLTag', array( $this,
596 } elseif ( in_array( $tag, $normalFields ) ) {
600 // <title>Page</title>
601 // <redirect title="NewTitle"/>
603 // Because the redirect tag is built differently, we need special handling for that case.
604 if ( $tag == 'redirect' ) {
605 $pageInfo[$tag] = $this->nodeAttribute( 'title' );
607 $pageInfo[$tag] = $this->nodeContents();
608 if ( $tag == 'title' ) {
609 $title = $this->processTitle( $pageInfo['title'] );
616 $this->pageCallback( $title );
617 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( $this->config
);
683 if ( isset( $revisionInfo['id'] ) ) {
684 $revision->setID( $revisionInfo['id'] );
686 if ( isset( $revisionInfo['model'] ) ) {
687 $revision->setModel( $revisionInfo['model'] );
689 if ( isset( $revisionInfo['format'] ) ) {
690 $revision->setFormat( $revisionInfo['format'] );
692 $revision->setTitle( $pageInfo['_title'] );
694 if ( isset( $revisionInfo['text'] ) ) {
695 $handler = $revision->getContentHandler();
696 $text = $handler->importTransform(
697 $revisionInfo['text'],
698 $revision->getFormat() );
700 $revision->setText( $text );
702 if ( isset( $revisionInfo['timestamp'] ) ) {
703 $revision->setTimestamp( $revisionInfo['timestamp'] );
705 $revision->setTimestamp( wfTimestampNow() );
708 if ( isset( $revisionInfo['comment'] ) ) {
709 $revision->setComment( $revisionInfo['comment'] );
712 if ( isset( $revisionInfo['minor'] ) ) {
713 $revision->setMinor( true );
715 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
716 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
718 if ( isset( $revisionInfo['contributor']['username'] ) ) {
719 $revision->setUserName( $revisionInfo['contributor']['username'] );
721 $revision->setNoUpdates( $this->mNoUpdates
);
723 return $this->revisionCallback( $revision );
727 * @param array $pageInfo
730 private function handleUpload( &$pageInfo ) {
731 $this->debug( "Enter upload handler" );
732 $uploadInfo = array();
734 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
735 'src', 'size', 'sha1base36', 'archivename', 'rel' );
739 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
740 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
741 $this->reader
->name
== 'upload' ) {
745 $tag = $this->reader
->name
;
747 if ( !wfRunHooks( 'ImportHandleUploadXMLTag', array(
751 } elseif ( in_array( $tag, $normalFields ) ) {
752 $uploadInfo[$tag] = $this->nodeContents();
753 } elseif ( $tag == 'contributor' ) {
754 $uploadInfo['contributor'] = $this->handleContributor();
755 } elseif ( $tag == 'contents' ) {
756 $contents = $this->nodeContents();
757 $encoding = $this->reader
->getAttribute( 'encoding' );
758 if ( $encoding === 'base64' ) {
759 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
760 $uploadInfo['isTempSrc'] = true;
762 } elseif ( $tag != '#text' ) {
763 $this->warn( "Unhandled upload XML tag $tag" );
768 if ( $this->mImageBasePath
&& isset( $uploadInfo['rel'] ) ) {
769 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
770 if ( file_exists( $path ) ) {
771 $uploadInfo['fileSrc'] = $path;
772 $uploadInfo['isTempSrc'] = false;
776 if ( $this->mImportUploads
) {
777 return $this->processUpload( $pageInfo, $uploadInfo );
782 * @param string $contents
785 private function dumpTemp( $contents ) {
786 $filename = tempnam( wfTempDir(), 'importupload' );
787 file_put_contents( $filename, $contents );
792 * @param array $pageInfo
793 * @param array $uploadInfo
796 private function processUpload( $pageInfo, $uploadInfo ) {
797 $revision = new WikiRevision( $this->config
);
798 $text = isset( $uploadInfo['text'] ) ?
$uploadInfo['text'] : '';
800 $revision->setTitle( $pageInfo['_title'] );
801 $revision->setID( $pageInfo['id'] );
802 $revision->setTimestamp( $uploadInfo['timestamp'] );
803 $revision->setText( $text );
804 $revision->setFilename( $uploadInfo['filename'] );
805 if ( isset( $uploadInfo['archivename'] ) ) {
806 $revision->setArchiveName( $uploadInfo['archivename'] );
808 $revision->setSrc( $uploadInfo['src'] );
809 if ( isset( $uploadInfo['fileSrc'] ) ) {
810 $revision->setFileSrc( $uploadInfo['fileSrc'],
811 !empty( $uploadInfo['isTempSrc'] ) );
813 if ( isset( $uploadInfo['sha1base36'] ) ) {
814 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
816 $revision->setSize( intval( $uploadInfo['size'] ) );
817 $revision->setComment( $uploadInfo['comment'] );
819 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
820 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
822 if ( isset( $uploadInfo['contributor']['username'] ) ) {
823 $revision->setUserName( $uploadInfo['contributor']['username'] );
825 $revision->setNoUpdates( $this->mNoUpdates
);
827 return call_user_func( $this->mUploadCallback
, $revision );
833 private function handleContributor() {
834 $fields = array( 'id', 'ip', 'username' );
837 while ( $this->reader
->read() ) {
838 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
839 $this->reader
->name
== 'contributor' ) {
843 $tag = $this->reader
->name
;
845 if ( in_array( $tag, $fields ) ) {
846 $info[$tag] = $this->nodeContents();
854 * @param string $text
857 private function processTitle( $text ) {
859 $origTitle = Title
::newFromText( $workTitle );
861 if ( !is_null( $this->mTargetNamespace
) && !is_null( $origTitle ) ) {
862 # makeTitleSafe, because $origTitle can have a interwiki (different setting of interwiki map)
863 # and than dbKey can begin with a lowercase char
864 $title = Title
::makeTitleSafe( $this->mTargetNamespace
,
865 $origTitle->getDBkey() );
867 if ( !is_null( $this->mTargetRootPage
) ) {
868 $workTitle = $this->mTargetRootPage
. '/' . $workTitle;
870 $title = Title
::newFromText( $workTitle );
873 $commandLineMode = $this->config
->get( 'CommandLineMode' );
874 if ( is_null( $title ) ) {
875 # Invalid page title? Ignore the page
876 $this->notice( 'import-error-invalid', $workTitle );
878 } elseif ( $title->isExternal() ) {
879 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
881 } elseif ( !$title->canExist() ) {
882 $this->notice( 'import-error-special', $title->getPrefixedText() );
884 } elseif ( !$title->userCan( 'edit' ) && !$commandLineMode ) {
885 # Do not import if the importing wiki user cannot edit this page
886 $this->notice( 'import-error-edit', $title->getPrefixedText() );
888 } elseif ( !$title->exists() && !$title->userCan( 'create' ) && !$commandLineMode ) {
889 # Do not import if the importing wiki user cannot create this page
890 $this->notice( 'import-error-create', $title->getPrefixedText() );
894 return array( $title, $origTitle );
898 /** This is a horrible hack used to keep source compatibility */
899 class UploadSourceAdapter
{
901 public static $sourceRegistrations = array();
913 * @param ImportStreamSource $source
916 static function registerSource( ImportStreamSource
$source ) {
917 $id = wfRandomString();
919 self
::$sourceRegistrations[$id] = $source;
925 * @param string $path
926 * @param string $mode
927 * @param array $options
928 * @param string $opened_path
931 function stream_open( $path, $mode, $options, &$opened_path ) {
932 $url = parse_url( $path );
935 if ( !isset( self
::$sourceRegistrations[$id] ) ) {
939 $this->mSource
= self
::$sourceRegistrations[$id];
948 function stream_read( $count ) {
952 while ( !$leave && !$this->mSource
->atEnd() &&
953 strlen( $this->mBuffer
) < $count ) {
954 $read = $this->mSource
->readChunk();
956 if ( !strlen( $read ) ) {
960 $this->mBuffer
.= $read;
963 if ( strlen( $this->mBuffer
) ) {
964 $return = substr( $this->mBuffer
, 0, $count );
965 $this->mBuffer
= substr( $this->mBuffer
, $count );
968 $this->mPosition +
= strlen( $return );
974 * @param string $data
977 function stream_write( $data ) {
984 function stream_tell() {
985 return $this->mPosition
;
991 function stream_eof() {
992 return $this->mSource
->atEnd();
998 function url_stat() {
1001 $result['dev'] = $result[0] = 0;
1002 $result['ino'] = $result[1] = 0;
1003 $result['mode'] = $result[2] = 0;
1004 $result['nlink'] = $result[3] = 0;
1005 $result['uid'] = $result[4] = 0;
1006 $result['gid'] = $result[5] = 0;
1007 $result['rdev'] = $result[6] = 0;
1008 $result['size'] = $result[7] = 0;
1009 $result['atime'] = $result[8] = 0;
1010 $result['mtime'] = $result[9] = 0;
1011 $result['ctime'] = $result[10] = 0;
1012 $result['blksize'] = $result[11] = 0;
1013 $result['blocks'] = $result[12] = 0;
1020 * @todo document (e.g. one-sentence class description).
1021 * @ingroup SpecialPage
1023 class WikiRevision
{
1024 /** @todo Unused? */
1025 public $importer = null;
1028 public $title = null;
1034 public $timestamp = "20010115000000";
1038 * @todo Can't find any uses. Public, because that's suspicious. Get clarity. */
1042 public $user_text = "";
1045 public $model = null;
1048 public $format = null;
1057 public $content = null;
1059 /** @var ContentHandler */
1060 protected $contentHandler = null;
1063 public $comment = "";
1066 public $minor = false;
1072 public $action = "";
1075 public $params = "";
1078 public $fileSrc = '';
1080 /** @var bool|string */
1081 public $sha1base36 = false;
1087 public $isTemp = false;
1090 public $archiveName = '';
1092 protected $filename;
1097 /** @todo Unused? */
1101 private $mNoUpdates = false;
1103 /** @var Config $config */
1106 public function __construct( Config
$config ) {
1107 $this->config
= $config;
1111 * @param Title $title
1112 * @throws MWException
1114 function setTitle( $title ) {
1115 if ( is_object( $title ) ) {
1116 $this->title
= $title;
1117 } elseif ( is_null( $title ) ) {
1118 throw new MWException( "WikiRevision given a null title in import. "
1119 . "You may need to adjust \$wgLegalTitleChars." );
1121 throw new MWException( "WikiRevision given non-object title in import." );
1128 function setID( $id ) {
1135 function setTimestamp( $ts ) {
1136 # 2003-08-05T18:30:02Z
1137 $this->timestamp
= wfTimestamp( TS_MW
, $ts );
1141 * @param string $user
1143 function setUsername( $user ) {
1144 $this->user_text
= $user;
1150 function setUserIP( $ip ) {
1151 $this->user_text
= $ip;
1155 * @param string $model
1157 function setModel( $model ) {
1158 $this->model
= $model;
1162 * @param string $format
1164 function setFormat( $format ) {
1165 $this->format
= $format;
1169 * @param string $text
1171 function setText( $text ) {
1172 $this->text
= $text;
1176 * @param string $text
1178 function setComment( $text ) {
1179 $this->comment
= $text;
1183 * @param bool $minor
1185 function setMinor( $minor ) {
1186 $this->minor
= (bool)$minor;
1192 function setSrc( $src ) {
1197 * @param string $src
1198 * @param bool $isTemp
1200 function setFileSrc( $src, $isTemp ) {
1201 $this->fileSrc
= $src;
1202 $this->fileIsTemp
= $isTemp;
1206 * @param string $sha1base36
1208 function setSha1Base36( $sha1base36 ) {
1209 $this->sha1base36
= $sha1base36;
1213 * @param string $filename
1215 function setFilename( $filename ) {
1216 $this->filename
= $filename;
1220 * @param string $archiveName
1222 function setArchiveName( $archiveName ) {
1223 $this->archiveName
= $archiveName;
1229 function setSize( $size ) {
1230 $this->size
= intval( $size );
1234 * @param string $type
1236 function setType( $type ) {
1237 $this->type
= $type;
1241 * @param string $action
1243 function setAction( $action ) {
1244 $this->action
= $action;
1248 * @param array $params
1250 function setParams( $params ) {
1251 $this->params
= $params;
1255 * @param bool $noupdates
1257 public function setNoUpdates( $noupdates ) {
1258 $this->mNoUpdates
= $noupdates;
1264 function getTitle() {
1265 return $this->title
;
1278 function getTimestamp() {
1279 return $this->timestamp
;
1285 function getUser() {
1286 return $this->user_text
;
1292 * @deprecated Since 1.21, use getContent() instead.
1294 function getText() {
1295 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1301 * @return ContentHandler
1303 function getContentHandler() {
1304 if ( is_null( $this->contentHandler
) ) {
1305 $this->contentHandler
= ContentHandler
::getForModelID( $this->getModel() );
1308 return $this->contentHandler
;
1314 function getContent() {
1315 if ( is_null( $this->content
) ) {
1316 $handler = $this->getContentHandler();
1317 $this->content
= $handler->unserializeContent( $this->text
, $this->getFormat() );
1320 return $this->content
;
1326 function getModel() {
1327 if ( is_null( $this->model
) ) {
1328 $this->model
= $this->getTitle()->getContentModel();
1331 return $this->model
;
1337 function getFormat() {
1338 if ( is_null( $this->format
) ) {
1339 $this->format
= $this->getContentHandler()->getDefaultFormat();
1342 return $this->format
;
1348 function getComment() {
1349 return $this->comment
;
1355 function getMinor() {
1356 return $this->minor
;
1367 * @return bool|string
1369 function getSha1() {
1370 if ( $this->sha1base36
) {
1371 return wfBaseConvert( $this->sha1base36
, 36, 16 );
1379 function getFileSrc() {
1380 return $this->fileSrc
;
1386 function isTempSrc() {
1387 return $this->isTemp
;
1393 function getFilename() {
1394 return $this->filename
;
1400 function getArchiveName() {
1401 return $this->archiveName
;
1407 function getSize() {
1414 function getType() {
1421 function getAction() {
1422 return $this->action
;
1428 function getParams() {
1429 return $this->params
;
1435 function importOldRevision() {
1436 $dbw = wfGetDB( DB_MASTER
);
1438 # Sneak a single revision into place
1439 $user = User
::newFromName( $this->getUser() );
1441 $userId = intval( $user->getId() );
1442 $userText = $user->getName();
1446 $userText = $this->getUser();
1447 $userObj = new User
;
1450 // avoid memory leak...?
1451 $linkCache = LinkCache
::singleton();
1452 $linkCache->clear();
1454 $page = WikiPage
::factory( $this->title
);
1455 $page->loadPageData( 'fromdbmaster' );
1456 if ( !$page->exists() ) {
1457 # must create the page...
1458 $pageId = $page->insertOn( $dbw );
1460 $oldcountable = null;
1462 $pageId = $page->getId();
1465 $prior = $dbw->selectField( 'revision', '1',
1466 array( 'rev_page' => $pageId,
1467 'rev_timestamp' => $dbw->timestamp( $this->timestamp
),
1468 'rev_user_text' => $userText,
1469 'rev_comment' => $this->getComment() ),
1473 // @todo FIXME: This could fail slightly for multiple matches :P
1474 wfDebug( __METHOD__
. ": skipping existing revision for [[" .
1475 $this->title
->getPrefixedText() . "]], timestamp " . $this->timestamp
. "\n" );
1478 $oldcountable = $page->isCountable();
1481 # @todo FIXME: Use original rev_id optionally (better for backups)
1483 $revision = new Revision( array(
1484 'title' => $this->title
,
1486 'content_model' => $this->getModel(),
1487 'content_format' => $this->getFormat(),
1488 //XXX: just set 'content' => $this->getContent()?
1489 'text' => $this->getContent()->serialize( $this->getFormat() ),
1490 'comment' => $this->getComment(),
1492 'user_text' => $userText,
1493 'timestamp' => $this->timestamp
,
1494 'minor_edit' => $this->minor
,
1496 $revision->insertOn( $dbw );
1497 $changed = $page->updateIfNewerOn( $dbw, $revision );
1499 if ( $changed !== false && !$this->mNoUpdates
) {
1500 wfDebug( __METHOD__
. ": running updates\n" );
1501 $page->doEditUpdates(
1504 array( 'created' => $created, 'oldcountable' => $oldcountable )
1511 function importLogItem() {
1512 $dbw = wfGetDB( DB_MASTER
);
1513 # @todo FIXME: This will not record autoblocks
1514 if ( !$this->getTitle() ) {
1515 wfDebug( __METHOD__
. ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1516 $this->timestamp
. "\n" );
1519 # Check if it exists already
1520 // @todo FIXME: Use original log ID (better for backups)
1521 $prior = $dbw->selectField( 'logging', '1',
1522 array( 'log_type' => $this->getType(),
1523 'log_action' => $this->getAction(),
1524 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1525 'log_namespace' => $this->getTitle()->getNamespace(),
1526 'log_title' => $this->getTitle()->getDBkey(),
1527 'log_comment' => $this->getComment(),
1528 #'log_user_text' => $this->user_text,
1529 'log_params' => $this->params
),
1532 // @todo FIXME: This could fail slightly for multiple matches :P
1535 . ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp "
1536 . $this->timestamp
. "\n" );
1539 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1541 'log_id' => $log_id,
1542 'log_type' => $this->type
,
1543 'log_action' => $this->action
,
1544 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1545 'log_user' => User
::idFromName( $this->user_text
),
1546 #'log_user_text' => $this->user_text,
1547 'log_namespace' => $this->getTitle()->getNamespace(),
1548 'log_title' => $this->getTitle()->getDBkey(),
1549 'log_comment' => $this->getComment(),
1550 'log_params' => $this->params
1552 $dbw->insert( 'logging', $data, __METHOD__
);
1558 function importUpload() {
1560 $archiveName = $this->getArchiveName();
1561 if ( $archiveName ) {
1562 wfDebug( __METHOD__
. "Importing archived file as $archiveName\n" );
1563 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1564 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1566 $file = wfLocalFile( $this->getTitle() );
1567 wfDebug( __METHOD__
. 'Importing new file as ' . $file->getName() . "\n" );
1568 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1569 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1570 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1571 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1572 wfDebug( __METHOD__
. "File already exists; importing as $archiveName\n" );
1576 wfDebug( __METHOD__
. ': Bad file for ' . $this->getTitle() . "\n" );
1580 # Get the file source or download if necessary
1581 $source = $this->getFileSrc();
1582 $flags = $this->isTempSrc() ? File
::DELETE_SOURCE
: 0;
1584 $source = $this->downloadSource();
1585 $flags |
= File
::DELETE_SOURCE
;
1588 wfDebug( __METHOD__
. ": Could not fetch remote file.\n" );
1591 $sha1 = $this->getSha1();
1592 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1593 if ( $flags & File
::DELETE_SOURCE
) {
1594 # Broken file; delete it if it is a temporary file
1597 wfDebug( __METHOD__
. ": Corrupt file $source.\n" );
1601 $user = User
::newFromName( $this->user_text
);
1603 # Do the actual upload
1604 if ( $archiveName ) {
1605 $status = $file->uploadOld( $source, $archiveName,
1606 $this->getTimestamp(), $this->getComment(), $user, $flags );
1608 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1609 $flags, false, $this->getTimestamp(), $user );
1612 if ( $status->isGood() ) {
1613 wfDebug( __METHOD__
. ": Successful\n" );
1616 wfDebug( __METHOD__
. ': failed: ' . $status->getXml() . "\n" );
1622 * @return bool|string
1624 function downloadSource() {
1625 if ( !$this->config
->get( 'EnableUploads' ) ) {
1629 $tempo = tempnam( wfTempDir(), 'download' );
1630 $f = fopen( $tempo, 'wb' );
1632 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1637 $src = $this->getSrc();
1638 $data = Http
::get( $src );
1640 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1646 fwrite( $f, $data );
1655 * @todo document (e.g. one-sentence class description).
1656 * @ingroup SpecialPage
1658 class ImportStringSource
{
1659 function __construct( $string ) {
1660 $this->mString
= $string;
1661 $this->mRead
= false;
1668 return $this->mRead
;
1672 * @return bool|string
1674 function readChunk() {
1675 if ( $this->atEnd() ) {
1678 $this->mRead
= true;
1679 return $this->mString
;
1684 * @todo document (e.g. one-sentence class description).
1685 * @ingroup SpecialPage
1687 class ImportStreamSource
{
1688 function __construct( $handle ) {
1689 $this->mHandle
= $handle;
1696 return feof( $this->mHandle
);
1702 function readChunk() {
1703 return fread( $this->mHandle
, 32768 );
1707 * @param string $filename
1710 static function newFromFile( $filename ) {
1711 wfSuppressWarnings();
1712 $file = fopen( $filename, 'rt' );
1713 wfRestoreWarnings();
1715 return Status
::newFatal( "importcantopen" );
1717 return Status
::newGood( new ImportStreamSource( $file ) );
1721 * @param string $fieldname
1724 static function newFromUpload( $fieldname = "xmlimport" ) {
1725 $upload =& $_FILES[$fieldname];
1727 if ( $upload === null ||
!$upload['name'] ) {
1728 return Status
::newFatal( 'importnofile' );
1730 if ( !empty( $upload['error'] ) ) {
1731 switch ( $upload['error'] ) {
1733 # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1734 return Status
::newFatal( 'importuploaderrorsize' );
1736 # The uploaded file exceeds the MAX_FILE_SIZE directive that
1737 # was specified in the HTML form.
1738 return Status
::newFatal( 'importuploaderrorsize' );
1740 # The uploaded file was only partially uploaded
1741 return Status
::newFatal( 'importuploaderrorpartial' );
1743 # Missing a temporary folder.
1744 return Status
::newFatal( 'importuploaderrortemp' );
1745 # case else: # Currently impossible
1749 $fname = $upload['tmp_name'];
1750 if ( is_uploaded_file( $fname ) ) {
1751 return ImportStreamSource
::newFromFile( $fname );
1753 return Status
::newFatal( 'importnofile' );
1758 * @param string $url
1759 * @param string $method
1762 static function newFromURL( $url, $method = 'GET' ) {
1763 wfDebug( __METHOD__
. ": opening $url\n" );
1764 # Use the standard HTTP fetch function; it times out
1765 # quicker and sorts out user-agent problems which might
1766 # otherwise prevent importing from large sites, such
1767 # as the Wikimedia cluster, etc.
1768 $data = Http
::request( $method, $url, array( 'followRedirects' => true ) );
1769 if ( $data !== false ) {
1771 fwrite( $file, $data );
1774 return Status
::newGood( new ImportStreamSource( $file ) );
1776 return Status
::newFatal( 'importcantopen' );
1781 * @param string $interwiki
1782 * @param string $page
1783 * @param bool $history
1784 * @param bool $templates
1785 * @param int $pageLinkDepth
1788 public static function newFromInterwiki( $interwiki, $page, $history = false,
1789 $templates = false, $pageLinkDepth = 0
1791 if ( $page == '' ) {
1792 return Status
::newFatal( 'import-noarticle' );
1794 $link = Title
::newFromText( "$interwiki:Special:Export/$page" );
1795 if ( is_null( $link ) ||
!$link->isExternal() ) {
1796 return Status
::newFatal( 'importbadinterwiki' );
1800 $params['history'] = 1;
1803 $params['templates'] = 1;
1805 if ( $pageLinkDepth ) {
1806 $params['pagelink-depth'] = $pageLinkDepth;
1808 $url = $link->getFullURL( $params );
1809 # For interwikis, use POST to avoid redirects.
1810 return ImportStreamSource
::newFromURL( $url, "POST" );