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 $foreignNamespaces = null;
36 private $mLogItemCallback, $mUploadCallback, $mRevisionCallback, $mPageCallback;
37 private $mSiteInfoCallback, $mTargetNamespace, $mPageOutCallback;
38 private $mNoticeCallback, $mDebug;
39 private $mImportUploads, $mImageBasePath;
40 private $mNoUpdates = false;
43 /** @var ImportTitleFactory */
44 private $importTitleFactory;
47 * Creates an ImportXMLReader drawing from the source provided
48 * @param ImportStreamSource $source
49 * @param Config $config
51 function __construct( ImportStreamSource
$source, Config
$config = null ) {
52 $this->reader
= new XMLReader();
54 wfDeprecated( __METHOD__
. ' without a Config instance', '1.25' );
55 $config = ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
57 $this->config
= $config;
59 if ( !in_array( 'uploadsource', stream_get_wrappers() ) ) {
60 stream_wrapper_register( 'uploadsource', 'UploadSourceAdapter' );
62 $id = UploadSourceAdapter
::registerSource( $source );
63 if ( defined( 'LIBXML_PARSEHUGE' ) ) {
64 $this->reader
->open( "uploadsource://$id", null, LIBXML_PARSEHUGE
);
66 $this->reader
->open( "uploadsource://$id" );
70 $this->setRevisionCallback( array( $this, "importRevision" ) );
71 $this->setUploadCallback( array( $this, 'importUpload' ) );
72 $this->setLogItemCallback( array( $this, 'importLogItem' ) );
73 $this->setPageOutCallback( array( $this, 'finishImportPage' ) );
75 $this->importTitleFactory
= new NaiveImportTitleFactory();
79 * @return null|XMLReader
81 public function getReader() {
85 public function throwXmlError( $err ) {
86 $this->debug( "FAILURE: $err" );
87 wfDebug( "WikiImporter XML error: $err\n" );
90 public function debug( $data ) {
91 if ( $this->mDebug
) {
92 wfDebug( "IMPORT: $data\n" );
96 public function warn( $data ) {
97 wfDebug( "IMPORT: $data\n" );
100 public function notice( $msg /*, $param, ...*/ ) {
101 $params = func_get_args();
102 array_shift( $params );
104 if ( is_callable( $this->mNoticeCallback
) ) {
105 call_user_func( $this->mNoticeCallback
, $msg, $params );
106 } else { # No ImportReporter -> CLI
107 echo wfMessage( $msg, $params )->text() . "\n";
115 function setDebug( $debug ) {
116 $this->mDebug
= $debug;
120 * Set 'no updates' mode. In this mode, the link tables will not be updated by the importer
121 * @param bool $noupdates
123 function setNoUpdates( $noupdates ) {
124 $this->mNoUpdates
= $noupdates;
128 * Set a callback that displays notice messages
130 * @param callable $callback
133 public function setNoticeCallback( $callback ) {
134 return wfSetVar( $this->mNoticeCallback
, $callback );
138 * Sets the action to perform as each new page in the stream is reached.
139 * @param callable $callback
142 public function setPageCallback( $callback ) {
143 $previous = $this->mPageCallback
;
144 $this->mPageCallback
= $callback;
149 * Sets the action to perform as each page in the stream is completed.
150 * Callback accepts the page title (as a Title object), a second object
151 * with the original title form (in case it's been overridden into a
152 * local namespace), and a count of revisions.
154 * @param callable $callback
157 public function setPageOutCallback( $callback ) {
158 $previous = $this->mPageOutCallback
;
159 $this->mPageOutCallback
= $callback;
164 * Sets the action to perform as each page revision is reached.
165 * @param callable $callback
168 public function setRevisionCallback( $callback ) {
169 $previous = $this->mRevisionCallback
;
170 $this->mRevisionCallback
= $callback;
175 * Sets the action to perform as each file upload version is reached.
176 * @param callable $callback
179 public function setUploadCallback( $callback ) {
180 $previous = $this->mUploadCallback
;
181 $this->mUploadCallback
= $callback;
186 * Sets the action to perform as each log item reached.
187 * @param callable $callback
190 public function setLogItemCallback( $callback ) {
191 $previous = $this->mLogItemCallback
;
192 $this->mLogItemCallback
= $callback;
197 * Sets the action to perform when site info is encountered
198 * @param callable $callback
201 public function setSiteInfoCallback( $callback ) {
202 $previous = $this->mSiteInfoCallback
;
203 $this->mSiteInfoCallback
= $callback;
208 * Sets the factory object to use to convert ForeignTitle objects into local
210 * @param ImportTitleFactory $factory
212 public function setImportTitleFactory( $factory ) {
213 $this->importTitleFactory
= $factory;
217 * Set a target namespace to override the defaults
218 * @param null|int $namespace
221 public function setTargetNamespace( $namespace ) {
222 if ( is_null( $namespace ) ) {
223 // Don't override namespaces
224 $this->mTargetNamespace
= null;
225 $this->setImportTitleFactory( new NaiveImportTitleFactory() );
229 MWNamespace
::exists( intval( $namespace ) )
231 $namespace = intval( $namespace );
232 $this->mTargetNamespace
= $namespace;
233 $this->setImportTitleFactory( new NamespaceImportTitleFactory( $namespace ) );
241 * Set a target root page under which all pages are imported
242 * @param null|string $rootpage
245 public function setTargetRootPage( $rootpage ) {
246 $status = Status
::newGood();
247 if ( is_null( $rootpage ) ) {
249 $this->setImportTitleFactory( new NaiveImportTitleFactory() );
250 } elseif ( $rootpage !== '' ) {
251 $rootpage = rtrim( $rootpage, '/' ); //avoid double slashes
252 $title = Title
::newFromText( $rootpage, !is_null( $this->mTargetNamespace
)
253 ?
$this->mTargetNamespace
257 if ( !$title ||
$title->isExternal() ) {
258 $status->fatal( 'import-rootpage-invalid' );
260 if ( !MWNamespace
::hasSubpages( $title->getNamespace() ) ) {
263 $displayNSText = $title->getNamespace() == NS_MAIN
264 ?
wfMessage( 'blanknamespace' )->text()
265 : $wgContLang->getNsText( $title->getNamespace() );
266 $status->fatal( 'import-rootpage-nosubpage', $displayNSText );
268 // set namespace to 'all', so the namespace check in processTitle() can pass
269 $this->setTargetNamespace( null );
270 $this->setImportTitleFactory( new SubpageImportTitleFactory( $title ) );
280 public function setImageBasePath( $dir ) {
281 $this->mImageBasePath
= $dir;
285 * @param bool $import
287 public function setImportUploads( $import ) {
288 $this->mImportUploads
= $import;
292 * Default per-revision callback, performs the import.
293 * @param WikiRevision $revision
296 public function importRevision( $revision ) {
297 if ( !$revision->getContentHandler()->canBeUsedOn( $revision->getTitle() ) ) {
298 $this->notice( 'import-error-bad-location',
299 $revision->getTitle()->getPrefixedText(),
301 $revision->getModel(),
302 $revision->getFormat() );
308 $dbw = wfGetDB( DB_MASTER
);
309 return $dbw->deadlockLoop( array( $revision, 'importOldRevision' ) );
310 } catch ( MWContentSerializationException
$ex ) {
311 $this->notice( 'import-error-unserialize',
312 $revision->getTitle()->getPrefixedText(),
314 $revision->getModel(),
315 $revision->getFormat() );
322 * Default per-revision callback, performs the import.
323 * @param WikiRevision $revision
326 public function importLogItem( $revision ) {
327 $dbw = wfGetDB( DB_MASTER
);
328 return $dbw->deadlockLoop( array( $revision, 'importLogItem' ) );
333 * @param WikiRevision $revision
336 public function importUpload( $revision ) {
337 $dbw = wfGetDB( DB_MASTER
);
338 return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
342 * Mostly for hook use
343 * @param Title $title
344 * @param ForeignTitle $foreignTitle
345 * @param int $revCount
346 * @param int $sRevCount
347 * @param array $pageInfo
350 public function finishImportPage( $title, $foreignTitle, $revCount,
351 $sRevCount, $pageInfo ) {
352 $args = func_get_args();
353 return Hooks
::run( 'AfterImportPage', $args );
357 * Alternate per-revision callback, for debugging.
358 * @param WikiRevision $revision
360 public function debugRevisionHandler( &$revision ) {
361 $this->debug( "Got revision:" );
362 if ( is_object( $revision->title
) ) {
363 $this->debug( "-- Title: " . $revision->title
->getPrefixedText() );
365 $this->debug( "-- Title: <invalid>" );
367 $this->debug( "-- User: " . $revision->user_text
);
368 $this->debug( "-- Timestamp: " . $revision->timestamp
);
369 $this->debug( "-- Comment: " . $revision->comment
);
370 $this->debug( "-- Text: " . $revision->text
);
374 * Notify the callback function of site info
375 * @param array $siteInfo
378 private function siteInfoCallback( $siteInfo ) {
379 if ( isset( $this->mSiteInfoCallback
) ) {
380 return call_user_func_array( $this->mSiteInfoCallback
,
381 array( $siteInfo, $this ) );
388 * Notify the callback function when a new "<page>" is reached.
389 * @param Title $title
391 function pageCallback( $title ) {
392 if ( isset( $this->mPageCallback
) ) {
393 call_user_func( $this->mPageCallback
, $title );
398 * Notify the callback function when a "</page>" is closed.
399 * @param Title $title
400 * @param ForeignTitle $foreignTitle
401 * @param int $revCount
402 * @param int $sucCount Number of revisions for which callback returned true
403 * @param array $pageInfo Associative array of page information
405 private function pageOutCallback( $title, $foreignTitle, $revCount,
406 $sucCount, $pageInfo ) {
407 if ( isset( $this->mPageOutCallback
) ) {
408 $args = func_get_args();
409 call_user_func_array( $this->mPageOutCallback
, $args );
414 * Notify the callback function of a revision
415 * @param WikiRevision $revision
418 private function revisionCallback( $revision ) {
419 if ( isset( $this->mRevisionCallback
) ) {
420 return call_user_func_array( $this->mRevisionCallback
,
421 array( $revision, $this ) );
428 * Notify the callback function of a new log item
429 * @param WikiRevision $revision
432 private function logItemCallback( $revision ) {
433 if ( isset( $this->mLogItemCallback
) ) {
434 return call_user_func_array( $this->mLogItemCallback
,
435 array( $revision, $this ) );
442 * Retrieves the contents of the named attribute of the current element.
443 * @param string $attr The name of the attribute
444 * @return string The value of the attribute or an empty string if it is not set in the current element.
446 public function nodeAttribute( $attr ) {
447 return $this->reader
->getAttribute( $attr );
451 * Shouldn't something like this be built-in to XMLReader?
452 * Fetches text contents of the current element, assuming
453 * no sub-elements or such scary things.
457 public function nodeContents() {
458 if ( $this->reader
->isEmptyElement
) {
462 while ( $this->reader
->read() ) {
463 switch ( $this->reader
->nodeType
) {
464 case XMLReader
::TEXT
:
465 case XMLReader
::SIGNIFICANT_WHITESPACE
:
466 $buffer .= $this->reader
->value
;
468 case XMLReader
::END_ELEMENT
:
473 $this->reader
->close();
478 * Primary entry point
479 * @throws MWException
482 public function doImport() {
483 // Calls to reader->read need to be wrapped in calls to
484 // libxml_disable_entity_loader() to avoid local file
485 // inclusion attacks (bug 46932).
486 $oldDisable = libxml_disable_entity_loader( true );
487 $this->reader
->read();
489 if ( $this->reader
->name
!= 'mediawiki' ) {
490 libxml_disable_entity_loader( $oldDisable );
491 throw new MWException( "Expected <mediawiki> tag, got " .
492 $this->reader
->name
);
494 $this->debug( "<mediawiki> tag is correct." );
496 $this->debug( "Starting primary dump processing loop." );
498 $keepReading = $this->reader
->read();
500 while ( $keepReading ) {
501 $tag = $this->reader
->name
;
502 $type = $this->reader
->nodeType
;
504 if ( !Hooks
::run( 'ImportHandleToplevelXMLTag', array( $this ) ) ) {
506 } elseif ( $tag == 'mediawiki' && $type == XMLReader
::END_ELEMENT
) {
508 } elseif ( $tag == 'siteinfo' ) {
509 $this->handleSiteInfo();
510 } elseif ( $tag == 'page' ) {
512 } elseif ( $tag == 'logitem' ) {
513 $this->handleLogItem();
514 } elseif ( $tag != '#text' ) {
515 $this->warn( "Unhandled top-level XML tag $tag" );
521 $keepReading = $this->reader
->next();
523 $this->debug( "Skip" );
525 $keepReading = $this->reader
->read();
529 libxml_disable_entity_loader( $oldDisable );
533 private function handleSiteInfo() {
534 $this->debug( "Enter site info handler." );
537 // Fields that can just be stuffed in the siteInfo object
538 $normalFields = array( 'sitename', 'base', 'generator', 'case' );
540 while ( $this->reader
->read() ) {
541 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
542 $this->reader
->name
== 'siteinfo' ) {
546 $tag = $this->reader
->name
;
548 if ( $tag == 'namespace' ) {
549 $this->foreignNamespaces
[ $this->nodeAttribute( 'key' ) ] =
550 $this->nodeContents();
551 } elseif ( in_array( $tag, $normalFields ) ) {
552 $siteInfo[$tag] = $this->nodeContents();
556 $siteInfo['_namespaces'] = $this->foreignNamespaces
;
557 $this->siteInfoCallback( $siteInfo );
560 private function handleLogItem() {
561 $this->debug( "Enter log item handler." );
564 // Fields that can just be stuffed in the pageInfo object
565 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
566 'logtitle', 'params' );
568 while ( $this->reader
->read() ) {
569 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
570 $this->reader
->name
== 'logitem' ) {
574 $tag = $this->reader
->name
;
576 if ( !Hooks
::run( 'ImportHandleLogItemXMLTag', array(
580 } elseif ( in_array( $tag, $normalFields ) ) {
581 $logInfo[$tag] = $this->nodeContents();
582 } elseif ( $tag == 'contributor' ) {
583 $logInfo['contributor'] = $this->handleContributor();
584 } elseif ( $tag != '#text' ) {
585 $this->warn( "Unhandled log-item XML tag $tag" );
589 $this->processLogItem( $logInfo );
593 * @param array $logInfo
596 private function processLogItem( $logInfo ) {
597 $revision = new WikiRevision( $this->config
);
599 $revision->setID( $logInfo['id'] );
600 $revision->setType( $logInfo['type'] );
601 $revision->setAction( $logInfo['action'] );
602 $revision->setTimestamp( $logInfo['timestamp'] );
603 $revision->setParams( $logInfo['params'] );
604 $revision->setTitle( Title
::newFromText( $logInfo['logtitle'] ) );
605 $revision->setNoUpdates( $this->mNoUpdates
);
607 if ( isset( $logInfo['comment'] ) ) {
608 $revision->setComment( $logInfo['comment'] );
611 if ( isset( $logInfo['contributor']['ip'] ) ) {
612 $revision->setUserIP( $logInfo['contributor']['ip'] );
614 if ( isset( $logInfo['contributor']['username'] ) ) {
615 $revision->setUserName( $logInfo['contributor']['username'] );
618 return $this->logItemCallback( $revision );
621 private function handlePage() {
623 $this->debug( "Enter page handler." );
624 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
626 // Fields that can just be stuffed in the pageInfo object
627 $normalFields = array( 'title', 'ns', 'id', 'redirect', 'restrictions' );
632 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
633 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
634 $this->reader
->name
== 'page' ) {
640 $tag = $this->reader
->name
;
643 // The title is invalid, bail out of this page
645 } elseif ( !Hooks
::run( 'ImportHandlePageXMLTag', array( $this,
648 } elseif ( in_array( $tag, $normalFields ) ) {
652 // <title>Page</title>
653 // <redirect title="NewTitle"/>
655 // Because the redirect tag is built differently, we need special handling for that case.
656 if ( $tag == 'redirect' ) {
657 $pageInfo[$tag] = $this->nodeAttribute( 'title' );
659 $pageInfo[$tag] = $this->nodeContents();
661 } elseif ( $tag == 'revision' ||
$tag == 'upload' ) {
662 if ( !isset( $title ) ) {
663 $title = $this->processTitle( $pageInfo['title'],
664 isset( $pageInfo['ns'] ) ?
$pageInfo['ns'] : null );
671 $this->pageCallback( $title );
672 list( $pageInfo['_title'], $foreignTitle ) = $title;
676 if ( $tag == 'revision' ) {
677 $this->handleRevision( $pageInfo );
679 $this->handleUpload( $pageInfo );
682 } elseif ( $tag != '#text' ) {
683 $this->warn( "Unhandled page XML tag $tag" );
688 $this->pageOutCallback( $pageInfo['_title'], $foreignTitle,
689 $pageInfo['revisionCount'],
690 $pageInfo['successfulRevisionCount'],
695 * @param array $pageInfo
697 private function handleRevision( &$pageInfo ) {
698 $this->debug( "Enter revision handler" );
699 $revisionInfo = array();
701 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'model', 'format', 'text' );
705 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
706 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
707 $this->reader
->name
== 'revision' ) {
711 $tag = $this->reader
->name
;
713 if ( !Hooks
::run( 'ImportHandleRevisionXMLTag', array(
714 $this, $pageInfo, $revisionInfo
717 } elseif ( in_array( $tag, $normalFields ) ) {
718 $revisionInfo[$tag] = $this->nodeContents();
719 } elseif ( $tag == 'contributor' ) {
720 $revisionInfo['contributor'] = $this->handleContributor();
721 } elseif ( $tag != '#text' ) {
722 $this->warn( "Unhandled revision XML tag $tag" );
727 $pageInfo['revisionCount']++
;
728 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
729 $pageInfo['successfulRevisionCount']++
;
734 * @param array $pageInfo
735 * @param array $revisionInfo
738 private function processRevision( $pageInfo, $revisionInfo ) {
739 $revision = new WikiRevision( $this->config
);
741 if ( isset( $revisionInfo['id'] ) ) {
742 $revision->setID( $revisionInfo['id'] );
744 if ( isset( $revisionInfo['model'] ) ) {
745 $revision->setModel( $revisionInfo['model'] );
747 if ( isset( $revisionInfo['format'] ) ) {
748 $revision->setFormat( $revisionInfo['format'] );
750 $revision->setTitle( $pageInfo['_title'] );
752 if ( isset( $revisionInfo['text'] ) ) {
753 $handler = $revision->getContentHandler();
754 $text = $handler->importTransform(
755 $revisionInfo['text'],
756 $revision->getFormat() );
758 $revision->setText( $text );
760 if ( isset( $revisionInfo['timestamp'] ) ) {
761 $revision->setTimestamp( $revisionInfo['timestamp'] );
763 $revision->setTimestamp( wfTimestampNow() );
766 if ( isset( $revisionInfo['comment'] ) ) {
767 $revision->setComment( $revisionInfo['comment'] );
770 if ( isset( $revisionInfo['minor'] ) ) {
771 $revision->setMinor( true );
773 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
774 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
776 if ( isset( $revisionInfo['contributor']['username'] ) ) {
777 $revision->setUserName( $revisionInfo['contributor']['username'] );
779 $revision->setNoUpdates( $this->mNoUpdates
);
781 return $this->revisionCallback( $revision );
785 * @param array $pageInfo
788 private function handleUpload( &$pageInfo ) {
789 $this->debug( "Enter upload handler" );
790 $uploadInfo = array();
792 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
793 'src', 'size', 'sha1base36', 'archivename', 'rel' );
797 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
798 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
799 $this->reader
->name
== 'upload' ) {
803 $tag = $this->reader
->name
;
805 if ( !Hooks
::run( 'ImportHandleUploadXMLTag', array(
809 } elseif ( in_array( $tag, $normalFields ) ) {
810 $uploadInfo[$tag] = $this->nodeContents();
811 } elseif ( $tag == 'contributor' ) {
812 $uploadInfo['contributor'] = $this->handleContributor();
813 } elseif ( $tag == 'contents' ) {
814 $contents = $this->nodeContents();
815 $encoding = $this->reader
->getAttribute( 'encoding' );
816 if ( $encoding === 'base64' ) {
817 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
818 $uploadInfo['isTempSrc'] = true;
820 } elseif ( $tag != '#text' ) {
821 $this->warn( "Unhandled upload XML tag $tag" );
826 if ( $this->mImageBasePath
&& isset( $uploadInfo['rel'] ) ) {
827 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
828 if ( file_exists( $path ) ) {
829 $uploadInfo['fileSrc'] = $path;
830 $uploadInfo['isTempSrc'] = false;
834 if ( $this->mImportUploads
) {
835 return $this->processUpload( $pageInfo, $uploadInfo );
840 * @param string $contents
843 private function dumpTemp( $contents ) {
844 $filename = tempnam( wfTempDir(), 'importupload' );
845 file_put_contents( $filename, $contents );
850 * @param array $pageInfo
851 * @param array $uploadInfo
854 private function processUpload( $pageInfo, $uploadInfo ) {
855 $revision = new WikiRevision( $this->config
);
856 $text = isset( $uploadInfo['text'] ) ?
$uploadInfo['text'] : '';
858 $revision->setTitle( $pageInfo['_title'] );
859 $revision->setID( $pageInfo['id'] );
860 $revision->setTimestamp( $uploadInfo['timestamp'] );
861 $revision->setText( $text );
862 $revision->setFilename( $uploadInfo['filename'] );
863 if ( isset( $uploadInfo['archivename'] ) ) {
864 $revision->setArchiveName( $uploadInfo['archivename'] );
866 $revision->setSrc( $uploadInfo['src'] );
867 if ( isset( $uploadInfo['fileSrc'] ) ) {
868 $revision->setFileSrc( $uploadInfo['fileSrc'],
869 !empty( $uploadInfo['isTempSrc'] ) );
871 if ( isset( $uploadInfo['sha1base36'] ) ) {
872 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
874 $revision->setSize( intval( $uploadInfo['size'] ) );
875 $revision->setComment( $uploadInfo['comment'] );
877 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
878 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
880 if ( isset( $uploadInfo['contributor']['username'] ) ) {
881 $revision->setUserName( $uploadInfo['contributor']['username'] );
883 $revision->setNoUpdates( $this->mNoUpdates
);
885 return call_user_func( $this->mUploadCallback
, $revision );
891 private function handleContributor() {
892 $fields = array( 'id', 'ip', 'username' );
895 while ( $this->reader
->read() ) {
896 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
897 $this->reader
->name
== 'contributor' ) {
901 $tag = $this->reader
->name
;
903 if ( in_array( $tag, $fields ) ) {
904 $info[$tag] = $this->nodeContents();
912 * @param string $text
913 * @param string|null $ns
916 private function processTitle( $text, $ns = null ) {
917 if ( is_null( $this->foreignNamespaces
) ) {
918 $foreignTitleFactory = new NaiveForeignTitleFactory();
920 $foreignTitleFactory = new NamespaceAwareForeignTitleFactory(
921 $this->foreignNamespaces
);
924 $foreignTitle = $foreignTitleFactory->createForeignTitle( $text,
927 $title = $this->importTitleFactory
->createTitleFromForeignTitle(
930 $commandLineMode = $this->config
->get( 'CommandLineMode' );
931 if ( is_null( $title ) ) {
932 # Invalid page title? Ignore the page
933 $this->notice( 'import-error-invalid', $foreignTitle->getFullText() );
935 } elseif ( $title->isExternal() ) {
936 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
938 } elseif ( !$title->canExist() ) {
939 $this->notice( 'import-error-special', $title->getPrefixedText() );
941 } elseif ( !$title->userCan( 'edit' ) && !$commandLineMode ) {
942 # Do not import if the importing wiki user cannot edit this page
943 $this->notice( 'import-error-edit', $title->getPrefixedText() );
945 } elseif ( !$title->exists() && !$title->userCan( 'create' ) && !$commandLineMode ) {
946 # Do not import if the importing wiki user cannot create this page
947 $this->notice( 'import-error-create', $title->getPrefixedText() );
951 return array( $title, $foreignTitle );
955 /** This is a horrible hack used to keep source compatibility */
956 class UploadSourceAdapter
{
958 public static $sourceRegistrations = array();
970 * @param ImportStreamSource $source
973 static function registerSource( ImportStreamSource
$source ) {
974 $id = wfRandomString();
976 self
::$sourceRegistrations[$id] = $source;
982 * @param string $path
983 * @param string $mode
984 * @param array $options
985 * @param string $opened_path
988 function stream_open( $path, $mode, $options, &$opened_path ) {
989 $url = parse_url( $path );
992 if ( !isset( self
::$sourceRegistrations[$id] ) ) {
996 $this->mSource
= self
::$sourceRegistrations[$id];
1005 function stream_read( $count ) {
1009 while ( !$leave && !$this->mSource
->atEnd() &&
1010 strlen( $this->mBuffer
) < $count ) {
1011 $read = $this->mSource
->readChunk();
1013 if ( !strlen( $read ) ) {
1017 $this->mBuffer
.= $read;
1020 if ( strlen( $this->mBuffer
) ) {
1021 $return = substr( $this->mBuffer
, 0, $count );
1022 $this->mBuffer
= substr( $this->mBuffer
, $count );
1025 $this->mPosition +
= strlen( $return );
1031 * @param string $data
1034 function stream_write( $data ) {
1041 function stream_tell() {
1042 return $this->mPosition
;
1048 function stream_eof() {
1049 return $this->mSource
->atEnd();
1055 function url_stat() {
1058 $result['dev'] = $result[0] = 0;
1059 $result['ino'] = $result[1] = 0;
1060 $result['mode'] = $result[2] = 0;
1061 $result['nlink'] = $result[3] = 0;
1062 $result['uid'] = $result[4] = 0;
1063 $result['gid'] = $result[5] = 0;
1064 $result['rdev'] = $result[6] = 0;
1065 $result['size'] = $result[7] = 0;
1066 $result['atime'] = $result[8] = 0;
1067 $result['mtime'] = $result[9] = 0;
1068 $result['ctime'] = $result[10] = 0;
1069 $result['blksize'] = $result[11] = 0;
1070 $result['blocks'] = $result[12] = 0;
1077 * @todo document (e.g. one-sentence class description).
1078 * @ingroup SpecialPage
1080 class WikiRevision
{
1081 /** @todo Unused? */
1082 public $importer = null;
1085 public $title = null;
1091 public $timestamp = "20010115000000";
1095 * @todo Can't find any uses. Public, because that's suspicious. Get clarity. */
1099 public $user_text = "";
1102 public $model = null;
1105 public $format = null;
1114 public $content = null;
1116 /** @var ContentHandler */
1117 protected $contentHandler = null;
1120 public $comment = "";
1123 public $minor = false;
1129 public $action = "";
1132 public $params = "";
1135 public $fileSrc = '';
1137 /** @var bool|string */
1138 public $sha1base36 = false;
1144 public $isTemp = false;
1147 public $archiveName = '';
1149 protected $filename;
1154 /** @todo Unused? */
1158 private $mNoUpdates = false;
1160 /** @var Config $config */
1163 public function __construct( Config
$config ) {
1164 $this->config
= $config;
1168 * @param Title $title
1169 * @throws MWException
1171 function setTitle( $title ) {
1172 if ( is_object( $title ) ) {
1173 $this->title
= $title;
1174 } elseif ( is_null( $title ) ) {
1175 throw new MWException( "WikiRevision given a null title in import. "
1176 . "You may need to adjust \$wgLegalTitleChars." );
1178 throw new MWException( "WikiRevision given non-object title in import." );
1185 function setID( $id ) {
1192 function setTimestamp( $ts ) {
1193 # 2003-08-05T18:30:02Z
1194 $this->timestamp
= wfTimestamp( TS_MW
, $ts );
1198 * @param string $user
1200 function setUsername( $user ) {
1201 $this->user_text
= $user;
1207 function setUserIP( $ip ) {
1208 $this->user_text
= $ip;
1212 * @param string $model
1214 function setModel( $model ) {
1215 $this->model
= $model;
1219 * @param string $format
1221 function setFormat( $format ) {
1222 $this->format
= $format;
1226 * @param string $text
1228 function setText( $text ) {
1229 $this->text
= $text;
1233 * @param string $text
1235 function setComment( $text ) {
1236 $this->comment
= $text;
1240 * @param bool $minor
1242 function setMinor( $minor ) {
1243 $this->minor
= (bool)$minor;
1249 function setSrc( $src ) {
1254 * @param string $src
1255 * @param bool $isTemp
1257 function setFileSrc( $src, $isTemp ) {
1258 $this->fileSrc
= $src;
1259 $this->fileIsTemp
= $isTemp;
1263 * @param string $sha1base36
1265 function setSha1Base36( $sha1base36 ) {
1266 $this->sha1base36
= $sha1base36;
1270 * @param string $filename
1272 function setFilename( $filename ) {
1273 $this->filename
= $filename;
1277 * @param string $archiveName
1279 function setArchiveName( $archiveName ) {
1280 $this->archiveName
= $archiveName;
1286 function setSize( $size ) {
1287 $this->size
= intval( $size );
1291 * @param string $type
1293 function setType( $type ) {
1294 $this->type
= $type;
1298 * @param string $action
1300 function setAction( $action ) {
1301 $this->action
= $action;
1305 * @param array $params
1307 function setParams( $params ) {
1308 $this->params
= $params;
1312 * @param bool $noupdates
1314 public function setNoUpdates( $noupdates ) {
1315 $this->mNoUpdates
= $noupdates;
1321 function getTitle() {
1322 return $this->title
;
1335 function getTimestamp() {
1336 return $this->timestamp
;
1342 function getUser() {
1343 return $this->user_text
;
1349 * @deprecated Since 1.21, use getContent() instead.
1351 function getText() {
1352 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1358 * @return ContentHandler
1360 function getContentHandler() {
1361 if ( is_null( $this->contentHandler
) ) {
1362 $this->contentHandler
= ContentHandler
::getForModelID( $this->getModel() );
1365 return $this->contentHandler
;
1371 function getContent() {
1372 if ( is_null( $this->content
) ) {
1373 $handler = $this->getContentHandler();
1374 $this->content
= $handler->unserializeContent( $this->text
, $this->getFormat() );
1377 return $this->content
;
1383 function getModel() {
1384 if ( is_null( $this->model
) ) {
1385 $this->model
= $this->getTitle()->getContentModel();
1388 return $this->model
;
1394 function getFormat() {
1395 if ( is_null( $this->format
) ) {
1396 $this->format
= $this->getContentHandler()->getDefaultFormat();
1399 return $this->format
;
1405 function getComment() {
1406 return $this->comment
;
1412 function getMinor() {
1413 return $this->minor
;
1424 * @return bool|string
1426 function getSha1() {
1427 if ( $this->sha1base36
) {
1428 return wfBaseConvert( $this->sha1base36
, 36, 16 );
1436 function getFileSrc() {
1437 return $this->fileSrc
;
1443 function isTempSrc() {
1444 return $this->isTemp
;
1450 function getFilename() {
1451 return $this->filename
;
1457 function getArchiveName() {
1458 return $this->archiveName
;
1464 function getSize() {
1471 function getType() {
1478 function getAction() {
1479 return $this->action
;
1485 function getParams() {
1486 return $this->params
;
1492 function importOldRevision() {
1493 $dbw = wfGetDB( DB_MASTER
);
1495 # Sneak a single revision into place
1496 $user = User
::newFromName( $this->getUser() );
1498 $userId = intval( $user->getId() );
1499 $userText = $user->getName();
1503 $userText = $this->getUser();
1504 $userObj = new User
;
1507 // avoid memory leak...?
1508 $linkCache = LinkCache
::singleton();
1509 $linkCache->clear();
1511 $page = WikiPage
::factory( $this->title
);
1512 $page->loadPageData( 'fromdbmaster' );
1513 if ( !$page->exists() ) {
1514 # must create the page...
1515 $pageId = $page->insertOn( $dbw );
1517 $oldcountable = null;
1519 $pageId = $page->getId();
1522 $prior = $dbw->selectField( 'revision', '1',
1523 array( 'rev_page' => $pageId,
1524 'rev_timestamp' => $dbw->timestamp( $this->timestamp
),
1525 'rev_user_text' => $userText,
1526 'rev_comment' => $this->getComment() ),
1530 // @todo FIXME: This could fail slightly for multiple matches :P
1531 wfDebug( __METHOD__
. ": skipping existing revision for [[" .
1532 $this->title
->getPrefixedText() . "]], timestamp " . $this->timestamp
. "\n" );
1535 $oldcountable = $page->isCountable();
1538 # @todo FIXME: Use original rev_id optionally (better for backups)
1540 $revision = new Revision( array(
1541 'title' => $this->title
,
1543 'content_model' => $this->getModel(),
1544 'content_format' => $this->getFormat(),
1545 //XXX: just set 'content' => $this->getContent()?
1546 'text' => $this->getContent()->serialize( $this->getFormat() ),
1547 'comment' => $this->getComment(),
1549 'user_text' => $userText,
1550 'timestamp' => $this->timestamp
,
1551 'minor_edit' => $this->minor
,
1553 $revision->insertOn( $dbw );
1554 $changed = $page->updateIfNewerOn( $dbw, $revision );
1556 if ( $changed !== false && !$this->mNoUpdates
) {
1557 wfDebug( __METHOD__
. ": running updates\n" );
1558 $page->doEditUpdates(
1561 array( 'created' => $created, 'oldcountable' => $oldcountable )
1568 function importLogItem() {
1569 $dbw = wfGetDB( DB_MASTER
);
1570 # @todo FIXME: This will not record autoblocks
1571 if ( !$this->getTitle() ) {
1572 wfDebug( __METHOD__
. ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1573 $this->timestamp
. "\n" );
1576 # Check if it exists already
1577 // @todo FIXME: Use original log ID (better for backups)
1578 $prior = $dbw->selectField( 'logging', '1',
1579 array( 'log_type' => $this->getType(),
1580 'log_action' => $this->getAction(),
1581 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1582 'log_namespace' => $this->getTitle()->getNamespace(),
1583 'log_title' => $this->getTitle()->getDBkey(),
1584 'log_comment' => $this->getComment(),
1585 #'log_user_text' => $this->user_text,
1586 'log_params' => $this->params
),
1589 // @todo FIXME: This could fail slightly for multiple matches :P
1592 . ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp "
1593 . $this->timestamp
. "\n" );
1596 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1598 'log_id' => $log_id,
1599 'log_type' => $this->type
,
1600 'log_action' => $this->action
,
1601 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1602 'log_user' => User
::idFromName( $this->user_text
),
1603 #'log_user_text' => $this->user_text,
1604 'log_namespace' => $this->getTitle()->getNamespace(),
1605 'log_title' => $this->getTitle()->getDBkey(),
1606 'log_comment' => $this->getComment(),
1607 'log_params' => $this->params
1609 $dbw->insert( 'logging', $data, __METHOD__
);
1615 function importUpload() {
1617 $archiveName = $this->getArchiveName();
1618 if ( $archiveName ) {
1619 wfDebug( __METHOD__
. "Importing archived file as $archiveName\n" );
1620 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1621 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1623 $file = wfLocalFile( $this->getTitle() );
1624 wfDebug( __METHOD__
. 'Importing new file as ' . $file->getName() . "\n" );
1625 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1626 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1627 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1628 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1629 wfDebug( __METHOD__
. "File already exists; importing as $archiveName\n" );
1633 wfDebug( __METHOD__
. ': Bad file for ' . $this->getTitle() . "\n" );
1637 # Get the file source or download if necessary
1638 $source = $this->getFileSrc();
1639 $flags = $this->isTempSrc() ? File
::DELETE_SOURCE
: 0;
1641 $source = $this->downloadSource();
1642 $flags |
= File
::DELETE_SOURCE
;
1645 wfDebug( __METHOD__
. ": Could not fetch remote file.\n" );
1648 $sha1 = $this->getSha1();
1649 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1650 if ( $flags & File
::DELETE_SOURCE
) {
1651 # Broken file; delete it if it is a temporary file
1654 wfDebug( __METHOD__
. ": Corrupt file $source.\n" );
1658 $user = User
::newFromName( $this->user_text
);
1660 # Do the actual upload
1661 if ( $archiveName ) {
1662 $status = $file->uploadOld( $source, $archiveName,
1663 $this->getTimestamp(), $this->getComment(), $user, $flags );
1665 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1666 $flags, false, $this->getTimestamp(), $user );
1669 if ( $status->isGood() ) {
1670 wfDebug( __METHOD__
. ": Successful\n" );
1673 wfDebug( __METHOD__
. ': failed: ' . $status->getXml() . "\n" );
1679 * @return bool|string
1681 function downloadSource() {
1682 if ( !$this->config
->get( 'EnableUploads' ) ) {
1686 $tempo = tempnam( wfTempDir(), 'download' );
1687 $f = fopen( $tempo, 'wb' );
1689 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1694 $src = $this->getSrc();
1695 $data = Http
::get( $src );
1697 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1703 fwrite( $f, $data );
1712 * Used for importing XML dumps where the content of the dump is in a string.
1713 * This class is ineffecient, and should only be used for small dumps.
1714 * For larger dumps, ImportStreamSource should be used instead.
1716 * @ingroup SpecialPage
1718 class ImportStringSource
{
1719 function __construct( $string ) {
1720 $this->mString
= $string;
1721 $this->mRead
= false;
1728 return $this->mRead
;
1732 * @return bool|string
1734 function readChunk() {
1735 if ( $this->atEnd() ) {
1738 $this->mRead
= true;
1739 return $this->mString
;
1744 * Imports a XML dump from a file (either from file upload, files on disk, or HTTP)
1745 * @ingroup SpecialPage
1747 class ImportStreamSource
{
1748 function __construct( $handle ) {
1749 $this->mHandle
= $handle;
1756 return feof( $this->mHandle
);
1762 function readChunk() {
1763 return fread( $this->mHandle
, 32768 );
1767 * @param string $filename
1770 static function newFromFile( $filename ) {
1771 wfSuppressWarnings();
1772 $file = fopen( $filename, 'rt' );
1773 wfRestoreWarnings();
1775 return Status
::newFatal( "importcantopen" );
1777 return Status
::newGood( new ImportStreamSource( $file ) );
1781 * @param string $fieldname
1784 static function newFromUpload( $fieldname = "xmlimport" ) {
1785 $upload =& $_FILES[$fieldname];
1787 if ( $upload === null ||
!$upload['name'] ) {
1788 return Status
::newFatal( 'importnofile' );
1790 if ( !empty( $upload['error'] ) ) {
1791 switch ( $upload['error'] ) {
1793 # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1794 return Status
::newFatal( 'importuploaderrorsize' );
1796 # The uploaded file exceeds the MAX_FILE_SIZE directive that
1797 # was specified in the HTML form.
1798 return Status
::newFatal( 'importuploaderrorsize' );
1800 # The uploaded file was only partially uploaded
1801 return Status
::newFatal( 'importuploaderrorpartial' );
1803 # Missing a temporary folder.
1804 return Status
::newFatal( 'importuploaderrortemp' );
1805 # case else: # Currently impossible
1809 $fname = $upload['tmp_name'];
1810 if ( is_uploaded_file( $fname ) ) {
1811 return ImportStreamSource
::newFromFile( $fname );
1813 return Status
::newFatal( 'importnofile' );
1818 * @param string $url
1819 * @param string $method
1822 static function newFromURL( $url, $method = 'GET' ) {
1823 wfDebug( __METHOD__
. ": opening $url\n" );
1824 # Use the standard HTTP fetch function; it times out
1825 # quicker and sorts out user-agent problems which might
1826 # otherwise prevent importing from large sites, such
1827 # as the Wikimedia cluster, etc.
1828 $data = Http
::request( $method, $url, array( 'followRedirects' => true ) );
1829 if ( $data !== false ) {
1831 fwrite( $file, $data );
1834 return Status
::newGood( new ImportStreamSource( $file ) );
1836 return Status
::newFatal( 'importcantopen' );
1841 * @param string $interwiki
1842 * @param string $page
1843 * @param bool $history
1844 * @param bool $templates
1845 * @param int $pageLinkDepth
1848 public static function newFromInterwiki( $interwiki, $page, $history = false,
1849 $templates = false, $pageLinkDepth = 0
1851 if ( $page == '' ) {
1852 return Status
::newFatal( 'import-noarticle' );
1854 $link = Title
::newFromText( "$interwiki:Special:Export/$page" );
1855 if ( is_null( $link ) ||
!$link->isExternal() ) {
1856 return Status
::newFatal( 'importbadinterwiki' );
1860 $params['history'] = 1;
1863 $params['templates'] = 1;
1865 if ( $pageLinkDepth ) {
1866 $params['pagelink-depth'] = $pageLinkDepth;
1868 $url = $link->getFullURL( $params );
1869 # For interwikis, use POST to avoid redirects.
1870 return ImportStreamSource
::newFromURL( $url, "POST" );