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;
46 private $countableCache = array();
49 * Creates an ImportXMLReader drawing from the source provided
50 * @param ImportStreamSource $source
51 * @param Config $config
53 function __construct( ImportStreamSource
$source, Config
$config = null ) {
54 $this->reader
= new XMLReader();
56 wfDeprecated( __METHOD__
. ' without a Config instance', '1.25' );
57 $config = ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
59 $this->config
= $config;
61 if ( !in_array( 'uploadsource', stream_get_wrappers() ) ) {
62 stream_wrapper_register( 'uploadsource', 'UploadSourceAdapter' );
64 $id = UploadSourceAdapter
::registerSource( $source );
65 if ( defined( 'LIBXML_PARSEHUGE' ) ) {
66 $this->reader
->open( "uploadsource://$id", null, LIBXML_PARSEHUGE
);
68 $this->reader
->open( "uploadsource://$id" );
72 $this->setPageCallback( array( $this, 'beforeImportPage' ) );
73 $this->setRevisionCallback( array( $this, "importRevision" ) );
74 $this->setUploadCallback( array( $this, 'importUpload' ) );
75 $this->setLogItemCallback( array( $this, 'importLogItem' ) );
76 $this->setPageOutCallback( array( $this, 'finishImportPage' ) );
78 $this->importTitleFactory
= new NaiveImportTitleFactory();
82 * @return null|XMLReader
84 public function getReader() {
88 public function throwXmlError( $err ) {
89 $this->debug( "FAILURE: $err" );
90 wfDebug( "WikiImporter XML error: $err\n" );
93 public function debug( $data ) {
94 if ( $this->mDebug
) {
95 wfDebug( "IMPORT: $data\n" );
99 public function warn( $data ) {
100 wfDebug( "IMPORT: $data\n" );
103 public function notice( $msg /*, $param, ...*/ ) {
104 $params = func_get_args();
105 array_shift( $params );
107 if ( is_callable( $this->mNoticeCallback
) ) {
108 call_user_func( $this->mNoticeCallback
, $msg, $params );
109 } else { # No ImportReporter -> CLI
110 echo wfMessage( $msg, $params )->text() . "\n";
118 function setDebug( $debug ) {
119 $this->mDebug
= $debug;
123 * Set 'no updates' mode. In this mode, the link tables will not be updated by the importer
124 * @param bool $noupdates
126 function setNoUpdates( $noupdates ) {
127 $this->mNoUpdates
= $noupdates;
131 * Set a callback that displays notice messages
133 * @param callable $callback
136 public function setNoticeCallback( $callback ) {
137 return wfSetVar( $this->mNoticeCallback
, $callback );
141 * Sets the action to perform as each new page in the stream is reached.
142 * @param callable $callback
145 public function setPageCallback( $callback ) {
146 $previous = $this->mPageCallback
;
147 $this->mPageCallback
= $callback;
152 * Sets the action to perform as each page in the stream is completed.
153 * Callback accepts the page title (as a Title object), a second object
154 * with the original title form (in case it's been overridden into a
155 * local namespace), and a count of revisions.
157 * @param callable $callback
160 public function setPageOutCallback( $callback ) {
161 $previous = $this->mPageOutCallback
;
162 $this->mPageOutCallback
= $callback;
167 * Sets the action to perform as each page revision is reached.
168 * @param callable $callback
171 public function setRevisionCallback( $callback ) {
172 $previous = $this->mRevisionCallback
;
173 $this->mRevisionCallback
= $callback;
178 * Sets the action to perform as each file upload version is reached.
179 * @param callable $callback
182 public function setUploadCallback( $callback ) {
183 $previous = $this->mUploadCallback
;
184 $this->mUploadCallback
= $callback;
189 * Sets the action to perform as each log item reached.
190 * @param callable $callback
193 public function setLogItemCallback( $callback ) {
194 $previous = $this->mLogItemCallback
;
195 $this->mLogItemCallback
= $callback;
200 * Sets the action to perform when site info is encountered
201 * @param callable $callback
204 public function setSiteInfoCallback( $callback ) {
205 $previous = $this->mSiteInfoCallback
;
206 $this->mSiteInfoCallback
= $callback;
211 * Sets the factory object to use to convert ForeignTitle objects into local
213 * @param ImportTitleFactory $factory
215 public function setImportTitleFactory( $factory ) {
216 $this->importTitleFactory
= $factory;
220 * Set a target namespace to override the defaults
221 * @param null|int $namespace
224 public function setTargetNamespace( $namespace ) {
225 if ( is_null( $namespace ) ) {
226 // Don't override namespaces
227 $this->mTargetNamespace
= null;
228 $this->setImportTitleFactory( new NaiveImportTitleFactory() );
232 MWNamespace
::exists( intval( $namespace ) )
234 $namespace = intval( $namespace );
235 $this->mTargetNamespace
= $namespace;
236 $this->setImportTitleFactory( new NamespaceImportTitleFactory( $namespace ) );
244 * Set a target root page under which all pages are imported
245 * @param null|string $rootpage
248 public function setTargetRootPage( $rootpage ) {
249 $status = Status
::newGood();
250 if ( is_null( $rootpage ) ) {
252 $this->setImportTitleFactory( new NaiveImportTitleFactory() );
253 } elseif ( $rootpage !== '' ) {
254 $rootpage = rtrim( $rootpage, '/' ); //avoid double slashes
255 $title = Title
::newFromText( $rootpage, !is_null( $this->mTargetNamespace
)
256 ?
$this->mTargetNamespace
260 if ( !$title ||
$title->isExternal() ) {
261 $status->fatal( 'import-rootpage-invalid' );
263 if ( !MWNamespace
::hasSubpages( $title->getNamespace() ) ) {
266 $displayNSText = $title->getNamespace() == NS_MAIN
267 ?
wfMessage( 'blanknamespace' )->text()
268 : $wgContLang->getNsText( $title->getNamespace() );
269 $status->fatal( 'import-rootpage-nosubpage', $displayNSText );
271 // set namespace to 'all', so the namespace check in processTitle() can pass
272 $this->setTargetNamespace( null );
273 $this->setImportTitleFactory( new SubpageImportTitleFactory( $title ) );
283 public function setImageBasePath( $dir ) {
284 $this->mImageBasePath
= $dir;
288 * @param bool $import
290 public function setImportUploads( $import ) {
291 $this->mImportUploads
= $import;
295 * Default per-page callback. Sets up some things related to site statistics
296 * @param array $titleAndForeignTitle Two-element array, with Title object at
297 * index 0 and ForeignTitle object at index 1
300 public function beforeImportPage( $titleAndForeignTitle ) {
301 $title = $titleAndForeignTitle[0];
302 $page = WikiPage
::factory( $title );
303 $this->countableCache
['title_' . $title->getPrefixedText()] = $page->isCountable();
308 * Default per-revision callback, performs the import.
309 * @param WikiRevision $revision
312 public function importRevision( $revision ) {
313 if ( !$revision->getContentHandler()->canBeUsedOn( $revision->getTitle() ) ) {
314 $this->notice( 'import-error-bad-location',
315 $revision->getTitle()->getPrefixedText(),
317 $revision->getModel(),
318 $revision->getFormat() );
324 $dbw = wfGetDB( DB_MASTER
);
325 return $dbw->deadlockLoop( array( $revision, 'importOldRevision' ) );
326 } catch ( MWContentSerializationException
$ex ) {
327 $this->notice( 'import-error-unserialize',
328 $revision->getTitle()->getPrefixedText(),
330 $revision->getModel(),
331 $revision->getFormat() );
338 * Default per-revision callback, performs the import.
339 * @param WikiRevision $revision
342 public function importLogItem( $revision ) {
343 $dbw = wfGetDB( DB_MASTER
);
344 return $dbw->deadlockLoop( array( $revision, 'importLogItem' ) );
349 * @param WikiRevision $revision
352 public function importUpload( $revision ) {
353 $dbw = wfGetDB( DB_MASTER
);
354 return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
358 * Mostly for hook use
359 * @param Title $title
360 * @param ForeignTitle $foreignTitle
361 * @param int $revCount
362 * @param int $sRevCount
363 * @param array $pageInfo
366 public function finishImportPage( $title, $foreignTitle, $revCount,
367 $sRevCount, $pageInfo ) {
369 // Update article count statistics (T42009)
370 // The normal counting logic in WikiPage->doEditUpdates() is designed for
371 // one-revision-at-a-time editing, not bulk imports. In this situation it
372 // suffers from issues of slave lag. We let WikiPage handle the total page
373 // and revision count, and we implement our own custom logic for the
374 // article (content page) count.
375 $page = WikiPage
::factory( $title );
376 $page->loadPageData( 'fromdbmaster' );
377 $content = $page->getContent();
378 $editInfo = $page->prepareContentForEdit( $content );
380 $countable = $page->isCountable( $editInfo );
381 $oldcountable = $this->countableCache
['title_' . $title->getPrefixedText()];
382 if ( isset( $oldcountable ) && $countable != $oldcountable ) {
383 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( array(
384 'articles' => ( (int)$countable - (int)$oldcountable )
388 $args = func_get_args();
389 return Hooks
::run( 'AfterImportPage', $args );
393 * Alternate per-revision callback, for debugging.
394 * @param WikiRevision $revision
396 public function debugRevisionHandler( &$revision ) {
397 $this->debug( "Got revision:" );
398 if ( is_object( $revision->title
) ) {
399 $this->debug( "-- Title: " . $revision->title
->getPrefixedText() );
401 $this->debug( "-- Title: <invalid>" );
403 $this->debug( "-- User: " . $revision->user_text
);
404 $this->debug( "-- Timestamp: " . $revision->timestamp
);
405 $this->debug( "-- Comment: " . $revision->comment
);
406 $this->debug( "-- Text: " . $revision->text
);
410 * Notify the callback function of site info
411 * @param array $siteInfo
414 private function siteInfoCallback( $siteInfo ) {
415 if ( isset( $this->mSiteInfoCallback
) ) {
416 return call_user_func_array( $this->mSiteInfoCallback
,
417 array( $siteInfo, $this ) );
424 * Notify the callback function when a new "<page>" is reached.
425 * @param Title $title
427 function pageCallback( $title ) {
428 if ( isset( $this->mPageCallback
) ) {
429 call_user_func( $this->mPageCallback
, $title );
434 * Notify the callback function when a "</page>" is closed.
435 * @param Title $title
436 * @param ForeignTitle $foreignTitle
437 * @param int $revCount
438 * @param int $sucCount Number of revisions for which callback returned true
439 * @param array $pageInfo Associative array of page information
441 private function pageOutCallback( $title, $foreignTitle, $revCount,
442 $sucCount, $pageInfo ) {
443 if ( isset( $this->mPageOutCallback
) ) {
444 $args = func_get_args();
445 call_user_func_array( $this->mPageOutCallback
, $args );
450 * Notify the callback function of a revision
451 * @param WikiRevision $revision
454 private function revisionCallback( $revision ) {
455 if ( isset( $this->mRevisionCallback
) ) {
456 return call_user_func_array( $this->mRevisionCallback
,
457 array( $revision, $this ) );
464 * Notify the callback function of a new log item
465 * @param WikiRevision $revision
468 private function logItemCallback( $revision ) {
469 if ( isset( $this->mLogItemCallback
) ) {
470 return call_user_func_array( $this->mLogItemCallback
,
471 array( $revision, $this ) );
478 * Retrieves the contents of the named attribute of the current element.
479 * @param string $attr The name of the attribute
480 * @return string The value of the attribute or an empty string if it is not set in the current element.
482 public function nodeAttribute( $attr ) {
483 return $this->reader
->getAttribute( $attr );
487 * Shouldn't something like this be built-in to XMLReader?
488 * Fetches text contents of the current element, assuming
489 * no sub-elements or such scary things.
493 public function nodeContents() {
494 if ( $this->reader
->isEmptyElement
) {
498 while ( $this->reader
->read() ) {
499 switch ( $this->reader
->nodeType
) {
500 case XMLReader
::TEXT
:
501 case XMLReader
::SIGNIFICANT_WHITESPACE
:
502 $buffer .= $this->reader
->value
;
504 case XMLReader
::END_ELEMENT
:
509 $this->reader
->close();
514 * Primary entry point
515 * @throws MWException
518 public function doImport() {
519 // Calls to reader->read need to be wrapped in calls to
520 // libxml_disable_entity_loader() to avoid local file
521 // inclusion attacks (bug 46932).
522 $oldDisable = libxml_disable_entity_loader( true );
523 $this->reader
->read();
525 if ( $this->reader
->name
!= 'mediawiki' ) {
526 libxml_disable_entity_loader( $oldDisable );
527 throw new MWException( "Expected <mediawiki> tag, got " .
528 $this->reader
->name
);
530 $this->debug( "<mediawiki> tag is correct." );
532 $this->debug( "Starting primary dump processing loop." );
534 $keepReading = $this->reader
->read();
536 while ( $keepReading ) {
537 $tag = $this->reader
->name
;
538 $type = $this->reader
->nodeType
;
540 if ( !Hooks
::run( 'ImportHandleToplevelXMLTag', array( $this ) ) ) {
542 } elseif ( $tag == 'mediawiki' && $type == XMLReader
::END_ELEMENT
) {
544 } elseif ( $tag == 'siteinfo' ) {
545 $this->handleSiteInfo();
546 } elseif ( $tag == 'page' ) {
548 } elseif ( $tag == 'logitem' ) {
549 $this->handleLogItem();
550 } elseif ( $tag != '#text' ) {
551 $this->warn( "Unhandled top-level XML tag $tag" );
557 $keepReading = $this->reader
->next();
559 $this->debug( "Skip" );
561 $keepReading = $this->reader
->read();
565 libxml_disable_entity_loader( $oldDisable );
569 private function handleSiteInfo() {
570 $this->debug( "Enter site info handler." );
573 // Fields that can just be stuffed in the siteInfo object
574 $normalFields = array( 'sitename', 'base', 'generator', 'case' );
576 while ( $this->reader
->read() ) {
577 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
578 $this->reader
->name
== 'siteinfo' ) {
582 $tag = $this->reader
->name
;
584 if ( $tag == 'namespace' ) {
585 $this->foreignNamespaces
[ $this->nodeAttribute( 'key' ) ] =
586 $this->nodeContents();
587 } elseif ( in_array( $tag, $normalFields ) ) {
588 $siteInfo[$tag] = $this->nodeContents();
592 $siteInfo['_namespaces'] = $this->foreignNamespaces
;
593 $this->siteInfoCallback( $siteInfo );
596 private function handleLogItem() {
597 $this->debug( "Enter log item handler." );
600 // Fields that can just be stuffed in the pageInfo object
601 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
602 'logtitle', 'params' );
604 while ( $this->reader
->read() ) {
605 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
606 $this->reader
->name
== 'logitem' ) {
610 $tag = $this->reader
->name
;
612 if ( !Hooks
::run( 'ImportHandleLogItemXMLTag', array(
616 } elseif ( in_array( $tag, $normalFields ) ) {
617 $logInfo[$tag] = $this->nodeContents();
618 } elseif ( $tag == 'contributor' ) {
619 $logInfo['contributor'] = $this->handleContributor();
620 } elseif ( $tag != '#text' ) {
621 $this->warn( "Unhandled log-item XML tag $tag" );
625 $this->processLogItem( $logInfo );
629 * @param array $logInfo
632 private function processLogItem( $logInfo ) {
633 $revision = new WikiRevision( $this->config
);
635 $revision->setID( $logInfo['id'] );
636 $revision->setType( $logInfo['type'] );
637 $revision->setAction( $logInfo['action'] );
638 $revision->setTimestamp( $logInfo['timestamp'] );
639 $revision->setParams( $logInfo['params'] );
640 $revision->setTitle( Title
::newFromText( $logInfo['logtitle'] ) );
641 $revision->setNoUpdates( $this->mNoUpdates
);
643 if ( isset( $logInfo['comment'] ) ) {
644 $revision->setComment( $logInfo['comment'] );
647 if ( isset( $logInfo['contributor']['ip'] ) ) {
648 $revision->setUserIP( $logInfo['contributor']['ip'] );
650 if ( isset( $logInfo['contributor']['username'] ) ) {
651 $revision->setUserName( $logInfo['contributor']['username'] );
654 return $this->logItemCallback( $revision );
657 private function handlePage() {
659 $this->debug( "Enter page handler." );
660 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
662 // Fields that can just be stuffed in the pageInfo object
663 $normalFields = array( 'title', 'ns', 'id', 'redirect', 'restrictions' );
668 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
669 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
670 $this->reader
->name
== 'page' ) {
676 $tag = $this->reader
->name
;
679 // The title is invalid, bail out of this page
681 } elseif ( !Hooks
::run( 'ImportHandlePageXMLTag', array( $this,
684 } elseif ( in_array( $tag, $normalFields ) ) {
688 // <title>Page</title>
689 // <redirect title="NewTitle"/>
691 // Because the redirect tag is built differently, we need special handling for that case.
692 if ( $tag == 'redirect' ) {
693 $pageInfo[$tag] = $this->nodeAttribute( 'title' );
695 $pageInfo[$tag] = $this->nodeContents();
697 } elseif ( $tag == 'revision' ||
$tag == 'upload' ) {
698 if ( !isset( $title ) ) {
699 $title = $this->processTitle( $pageInfo['title'],
700 isset( $pageInfo['ns'] ) ?
$pageInfo['ns'] : null );
707 $this->pageCallback( $title );
708 list( $pageInfo['_title'], $foreignTitle ) = $title;
712 if ( $tag == 'revision' ) {
713 $this->handleRevision( $pageInfo );
715 $this->handleUpload( $pageInfo );
718 } elseif ( $tag != '#text' ) {
719 $this->warn( "Unhandled page XML tag $tag" );
724 $this->pageOutCallback( $pageInfo['_title'], $foreignTitle,
725 $pageInfo['revisionCount'],
726 $pageInfo['successfulRevisionCount'],
731 * @param array $pageInfo
733 private function handleRevision( &$pageInfo ) {
734 $this->debug( "Enter revision handler" );
735 $revisionInfo = array();
737 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'model', 'format', 'text' );
741 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
742 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
743 $this->reader
->name
== 'revision' ) {
747 $tag = $this->reader
->name
;
749 if ( !Hooks
::run( 'ImportHandleRevisionXMLTag', array(
750 $this, $pageInfo, $revisionInfo
753 } elseif ( in_array( $tag, $normalFields ) ) {
754 $revisionInfo[$tag] = $this->nodeContents();
755 } elseif ( $tag == 'contributor' ) {
756 $revisionInfo['contributor'] = $this->handleContributor();
757 } elseif ( $tag != '#text' ) {
758 $this->warn( "Unhandled revision XML tag $tag" );
763 $pageInfo['revisionCount']++
;
764 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
765 $pageInfo['successfulRevisionCount']++
;
770 * @param array $pageInfo
771 * @param array $revisionInfo
774 private function processRevision( $pageInfo, $revisionInfo ) {
775 $revision = new WikiRevision( $this->config
);
777 if ( isset( $revisionInfo['id'] ) ) {
778 $revision->setID( $revisionInfo['id'] );
780 if ( isset( $revisionInfo['model'] ) ) {
781 $revision->setModel( $revisionInfo['model'] );
783 if ( isset( $revisionInfo['format'] ) ) {
784 $revision->setFormat( $revisionInfo['format'] );
786 $revision->setTitle( $pageInfo['_title'] );
788 if ( isset( $revisionInfo['text'] ) ) {
789 $handler = $revision->getContentHandler();
790 $text = $handler->importTransform(
791 $revisionInfo['text'],
792 $revision->getFormat() );
794 $revision->setText( $text );
796 if ( isset( $revisionInfo['timestamp'] ) ) {
797 $revision->setTimestamp( $revisionInfo['timestamp'] );
799 $revision->setTimestamp( wfTimestampNow() );
802 if ( isset( $revisionInfo['comment'] ) ) {
803 $revision->setComment( $revisionInfo['comment'] );
806 if ( isset( $revisionInfo['minor'] ) ) {
807 $revision->setMinor( true );
809 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
810 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
812 if ( isset( $revisionInfo['contributor']['username'] ) ) {
813 $revision->setUserName( $revisionInfo['contributor']['username'] );
815 $revision->setNoUpdates( $this->mNoUpdates
);
817 return $this->revisionCallback( $revision );
821 * @param array $pageInfo
824 private function handleUpload( &$pageInfo ) {
825 $this->debug( "Enter upload handler" );
826 $uploadInfo = array();
828 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
829 'src', 'size', 'sha1base36', 'archivename', 'rel' );
833 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
834 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
835 $this->reader
->name
== 'upload' ) {
839 $tag = $this->reader
->name
;
841 if ( !Hooks
::run( 'ImportHandleUploadXMLTag', array(
845 } elseif ( in_array( $tag, $normalFields ) ) {
846 $uploadInfo[$tag] = $this->nodeContents();
847 } elseif ( $tag == 'contributor' ) {
848 $uploadInfo['contributor'] = $this->handleContributor();
849 } elseif ( $tag == 'contents' ) {
850 $contents = $this->nodeContents();
851 $encoding = $this->reader
->getAttribute( 'encoding' );
852 if ( $encoding === 'base64' ) {
853 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
854 $uploadInfo['isTempSrc'] = true;
856 } elseif ( $tag != '#text' ) {
857 $this->warn( "Unhandled upload XML tag $tag" );
862 if ( $this->mImageBasePath
&& isset( $uploadInfo['rel'] ) ) {
863 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
864 if ( file_exists( $path ) ) {
865 $uploadInfo['fileSrc'] = $path;
866 $uploadInfo['isTempSrc'] = false;
870 if ( $this->mImportUploads
) {
871 return $this->processUpload( $pageInfo, $uploadInfo );
876 * @param string $contents
879 private function dumpTemp( $contents ) {
880 $filename = tempnam( wfTempDir(), 'importupload' );
881 file_put_contents( $filename, $contents );
886 * @param array $pageInfo
887 * @param array $uploadInfo
890 private function processUpload( $pageInfo, $uploadInfo ) {
891 $revision = new WikiRevision( $this->config
);
892 $text = isset( $uploadInfo['text'] ) ?
$uploadInfo['text'] : '';
894 $revision->setTitle( $pageInfo['_title'] );
895 $revision->setID( $pageInfo['id'] );
896 $revision->setTimestamp( $uploadInfo['timestamp'] );
897 $revision->setText( $text );
898 $revision->setFilename( $uploadInfo['filename'] );
899 if ( isset( $uploadInfo['archivename'] ) ) {
900 $revision->setArchiveName( $uploadInfo['archivename'] );
902 $revision->setSrc( $uploadInfo['src'] );
903 if ( isset( $uploadInfo['fileSrc'] ) ) {
904 $revision->setFileSrc( $uploadInfo['fileSrc'],
905 !empty( $uploadInfo['isTempSrc'] ) );
907 if ( isset( $uploadInfo['sha1base36'] ) ) {
908 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
910 $revision->setSize( intval( $uploadInfo['size'] ) );
911 $revision->setComment( $uploadInfo['comment'] );
913 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
914 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
916 if ( isset( $uploadInfo['contributor']['username'] ) ) {
917 $revision->setUserName( $uploadInfo['contributor']['username'] );
919 $revision->setNoUpdates( $this->mNoUpdates
);
921 return call_user_func( $this->mUploadCallback
, $revision );
927 private function handleContributor() {
928 $fields = array( 'id', 'ip', 'username' );
931 while ( $this->reader
->read() ) {
932 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
933 $this->reader
->name
== 'contributor' ) {
937 $tag = $this->reader
->name
;
939 if ( in_array( $tag, $fields ) ) {
940 $info[$tag] = $this->nodeContents();
948 * @param string $text
949 * @param string|null $ns
952 private function processTitle( $text, $ns = null ) {
953 if ( is_null( $this->foreignNamespaces
) ) {
954 $foreignTitleFactory = new NaiveForeignTitleFactory();
956 $foreignTitleFactory = new NamespaceAwareForeignTitleFactory(
957 $this->foreignNamespaces
);
960 $foreignTitle = $foreignTitleFactory->createForeignTitle( $text,
963 $title = $this->importTitleFactory
->createTitleFromForeignTitle(
966 $commandLineMode = $this->config
->get( 'CommandLineMode' );
967 if ( is_null( $title ) ) {
968 # Invalid page title? Ignore the page
969 $this->notice( 'import-error-invalid', $foreignTitle->getFullText() );
971 } elseif ( $title->isExternal() ) {
972 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
974 } elseif ( !$title->canExist() ) {
975 $this->notice( 'import-error-special', $title->getPrefixedText() );
977 } elseif ( !$title->userCan( 'edit' ) && !$commandLineMode ) {
978 # Do not import if the importing wiki user cannot edit this page
979 $this->notice( 'import-error-edit', $title->getPrefixedText() );
981 } elseif ( !$title->exists() && !$title->userCan( 'create' ) && !$commandLineMode ) {
982 # Do not import if the importing wiki user cannot create this page
983 $this->notice( 'import-error-create', $title->getPrefixedText() );
987 return array( $title, $foreignTitle );
991 /** This is a horrible hack used to keep source compatibility */
992 class UploadSourceAdapter
{
994 public static $sourceRegistrations = array();
1006 * @param ImportStreamSource $source
1009 static function registerSource( ImportStreamSource
$source ) {
1010 $id = wfRandomString();
1012 self
::$sourceRegistrations[$id] = $source;
1018 * @param string $path
1019 * @param string $mode
1020 * @param array $options
1021 * @param string $opened_path
1024 function stream_open( $path, $mode, $options, &$opened_path ) {
1025 $url = parse_url( $path );
1028 if ( !isset( self
::$sourceRegistrations[$id] ) ) {
1032 $this->mSource
= self
::$sourceRegistrations[$id];
1041 function stream_read( $count ) {
1045 while ( !$leave && !$this->mSource
->atEnd() &&
1046 strlen( $this->mBuffer
) < $count ) {
1047 $read = $this->mSource
->readChunk();
1049 if ( !strlen( $read ) ) {
1053 $this->mBuffer
.= $read;
1056 if ( strlen( $this->mBuffer
) ) {
1057 $return = substr( $this->mBuffer
, 0, $count );
1058 $this->mBuffer
= substr( $this->mBuffer
, $count );
1061 $this->mPosition +
= strlen( $return );
1067 * @param string $data
1070 function stream_write( $data ) {
1077 function stream_tell() {
1078 return $this->mPosition
;
1084 function stream_eof() {
1085 return $this->mSource
->atEnd();
1091 function url_stat() {
1094 $result['dev'] = $result[0] = 0;
1095 $result['ino'] = $result[1] = 0;
1096 $result['mode'] = $result[2] = 0;
1097 $result['nlink'] = $result[3] = 0;
1098 $result['uid'] = $result[4] = 0;
1099 $result['gid'] = $result[5] = 0;
1100 $result['rdev'] = $result[6] = 0;
1101 $result['size'] = $result[7] = 0;
1102 $result['atime'] = $result[8] = 0;
1103 $result['mtime'] = $result[9] = 0;
1104 $result['ctime'] = $result[10] = 0;
1105 $result['blksize'] = $result[11] = 0;
1106 $result['blocks'] = $result[12] = 0;
1113 * @todo document (e.g. one-sentence class description).
1114 * @ingroup SpecialPage
1116 class WikiRevision
{
1117 /** @todo Unused? */
1118 public $importer = null;
1121 public $title = null;
1127 public $timestamp = "20010115000000";
1131 * @todo Can't find any uses. Public, because that's suspicious. Get clarity. */
1135 public $user_text = "";
1138 public $model = null;
1141 public $format = null;
1150 public $content = null;
1152 /** @var ContentHandler */
1153 protected $contentHandler = null;
1156 public $comment = "";
1159 public $minor = false;
1165 public $action = "";
1168 public $params = "";
1171 public $fileSrc = '';
1173 /** @var bool|string */
1174 public $sha1base36 = false;
1180 public $isTemp = false;
1183 public $archiveName = '';
1185 protected $filename;
1190 /** @todo Unused? */
1194 private $mNoUpdates = false;
1196 /** @var Config $config */
1199 public function __construct( Config
$config ) {
1200 $this->config
= $config;
1204 * @param Title $title
1205 * @throws MWException
1207 function setTitle( $title ) {
1208 if ( is_object( $title ) ) {
1209 $this->title
= $title;
1210 } elseif ( is_null( $title ) ) {
1211 throw new MWException( "WikiRevision given a null title in import. "
1212 . "You may need to adjust \$wgLegalTitleChars." );
1214 throw new MWException( "WikiRevision given non-object title in import." );
1221 function setID( $id ) {
1228 function setTimestamp( $ts ) {
1229 # 2003-08-05T18:30:02Z
1230 $this->timestamp
= wfTimestamp( TS_MW
, $ts );
1234 * @param string $user
1236 function setUsername( $user ) {
1237 $this->user_text
= $user;
1243 function setUserIP( $ip ) {
1244 $this->user_text
= $ip;
1248 * @param string $model
1250 function setModel( $model ) {
1251 $this->model
= $model;
1255 * @param string $format
1257 function setFormat( $format ) {
1258 $this->format
= $format;
1262 * @param string $text
1264 function setText( $text ) {
1265 $this->text
= $text;
1269 * @param string $text
1271 function setComment( $text ) {
1272 $this->comment
= $text;
1276 * @param bool $minor
1278 function setMinor( $minor ) {
1279 $this->minor
= (bool)$minor;
1285 function setSrc( $src ) {
1290 * @param string $src
1291 * @param bool $isTemp
1293 function setFileSrc( $src, $isTemp ) {
1294 $this->fileSrc
= $src;
1295 $this->fileIsTemp
= $isTemp;
1299 * @param string $sha1base36
1301 function setSha1Base36( $sha1base36 ) {
1302 $this->sha1base36
= $sha1base36;
1306 * @param string $filename
1308 function setFilename( $filename ) {
1309 $this->filename
= $filename;
1313 * @param string $archiveName
1315 function setArchiveName( $archiveName ) {
1316 $this->archiveName
= $archiveName;
1322 function setSize( $size ) {
1323 $this->size
= intval( $size );
1327 * @param string $type
1329 function setType( $type ) {
1330 $this->type
= $type;
1334 * @param string $action
1336 function setAction( $action ) {
1337 $this->action
= $action;
1341 * @param array $params
1343 function setParams( $params ) {
1344 $this->params
= $params;
1348 * @param bool $noupdates
1350 public function setNoUpdates( $noupdates ) {
1351 $this->mNoUpdates
= $noupdates;
1357 function getTitle() {
1358 return $this->title
;
1371 function getTimestamp() {
1372 return $this->timestamp
;
1378 function getUser() {
1379 return $this->user_text
;
1385 * @deprecated Since 1.21, use getContent() instead.
1387 function getText() {
1388 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1394 * @return ContentHandler
1396 function getContentHandler() {
1397 if ( is_null( $this->contentHandler
) ) {
1398 $this->contentHandler
= ContentHandler
::getForModelID( $this->getModel() );
1401 return $this->contentHandler
;
1407 function getContent() {
1408 if ( is_null( $this->content
) ) {
1409 $handler = $this->getContentHandler();
1410 $this->content
= $handler->unserializeContent( $this->text
, $this->getFormat() );
1413 return $this->content
;
1419 function getModel() {
1420 if ( is_null( $this->model
) ) {
1421 $this->model
= $this->getTitle()->getContentModel();
1424 return $this->model
;
1430 function getFormat() {
1431 if ( is_null( $this->format
) ) {
1432 $this->format
= $this->getContentHandler()->getDefaultFormat();
1435 return $this->format
;
1441 function getComment() {
1442 return $this->comment
;
1448 function getMinor() {
1449 return $this->minor
;
1460 * @return bool|string
1462 function getSha1() {
1463 if ( $this->sha1base36
) {
1464 return wfBaseConvert( $this->sha1base36
, 36, 16 );
1472 function getFileSrc() {
1473 return $this->fileSrc
;
1479 function isTempSrc() {
1480 return $this->isTemp
;
1486 function getFilename() {
1487 return $this->filename
;
1493 function getArchiveName() {
1494 return $this->archiveName
;
1500 function getSize() {
1507 function getType() {
1514 function getAction() {
1515 return $this->action
;
1521 function getParams() {
1522 return $this->params
;
1528 function importOldRevision() {
1529 $dbw = wfGetDB( DB_MASTER
);
1531 # Sneak a single revision into place
1532 $user = User
::newFromName( $this->getUser() );
1534 $userId = intval( $user->getId() );
1535 $userText = $user->getName();
1539 $userText = $this->getUser();
1540 $userObj = new User
;
1543 // avoid memory leak...?
1544 $linkCache = LinkCache
::singleton();
1545 $linkCache->clear();
1547 $page = WikiPage
::factory( $this->title
);
1548 $page->loadPageData( 'fromdbmaster' );
1549 if ( !$page->exists() ) {
1550 # must create the page...
1551 $pageId = $page->insertOn( $dbw );
1553 $oldcountable = null;
1555 $pageId = $page->getId();
1558 $prior = $dbw->selectField( 'revision', '1',
1559 array( 'rev_page' => $pageId,
1560 'rev_timestamp' => $dbw->timestamp( $this->timestamp
),
1561 'rev_user_text' => $userText,
1562 'rev_comment' => $this->getComment() ),
1566 // @todo FIXME: This could fail slightly for multiple matches :P
1567 wfDebug( __METHOD__
. ": skipping existing revision for [[" .
1568 $this->title
->getPrefixedText() . "]], timestamp " . $this->timestamp
. "\n" );
1573 # @todo FIXME: Use original rev_id optionally (better for backups)
1575 $revision = new Revision( array(
1576 'title' => $this->title
,
1578 'content_model' => $this->getModel(),
1579 'content_format' => $this->getFormat(),
1580 //XXX: just set 'content' => $this->getContent()?
1581 'text' => $this->getContent()->serialize( $this->getFormat() ),
1582 'comment' => $this->getComment(),
1584 'user_text' => $userText,
1585 'timestamp' => $this->timestamp
,
1586 'minor_edit' => $this->minor
,
1588 $revision->insertOn( $dbw );
1589 $changed = $page->updateIfNewerOn( $dbw, $revision );
1591 if ( $changed !== false && !$this->mNoUpdates
) {
1592 wfDebug( __METHOD__
. ": running updates\n" );
1593 // countable/oldcountable stuff is handled in WikiImporter::finishImportPage
1594 $page->doEditUpdates(
1597 array( 'created' => $created, 'oldcountable' => 'no-change' )
1604 function importLogItem() {
1605 $dbw = wfGetDB( DB_MASTER
);
1606 # @todo FIXME: This will not record autoblocks
1607 if ( !$this->getTitle() ) {
1608 wfDebug( __METHOD__
. ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1609 $this->timestamp
. "\n" );
1612 # Check if it exists already
1613 // @todo FIXME: Use original log ID (better for backups)
1614 $prior = $dbw->selectField( 'logging', '1',
1615 array( 'log_type' => $this->getType(),
1616 'log_action' => $this->getAction(),
1617 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1618 'log_namespace' => $this->getTitle()->getNamespace(),
1619 'log_title' => $this->getTitle()->getDBkey(),
1620 'log_comment' => $this->getComment(),
1621 #'log_user_text' => $this->user_text,
1622 'log_params' => $this->params
),
1625 // @todo FIXME: This could fail slightly for multiple matches :P
1628 . ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp "
1629 . $this->timestamp
. "\n" );
1632 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1634 'log_id' => $log_id,
1635 'log_type' => $this->type
,
1636 'log_action' => $this->action
,
1637 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1638 'log_user' => User
::idFromName( $this->user_text
),
1639 #'log_user_text' => $this->user_text,
1640 'log_namespace' => $this->getTitle()->getNamespace(),
1641 'log_title' => $this->getTitle()->getDBkey(),
1642 'log_comment' => $this->getComment(),
1643 'log_params' => $this->params
1645 $dbw->insert( 'logging', $data, __METHOD__
);
1651 function importUpload() {
1653 $archiveName = $this->getArchiveName();
1654 if ( $archiveName ) {
1655 wfDebug( __METHOD__
. "Importing archived file as $archiveName\n" );
1656 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1657 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1659 $file = wfLocalFile( $this->getTitle() );
1660 wfDebug( __METHOD__
. 'Importing new file as ' . $file->getName() . "\n" );
1661 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1662 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1663 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1664 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1665 wfDebug( __METHOD__
. "File already exists; importing as $archiveName\n" );
1669 wfDebug( __METHOD__
. ': Bad file for ' . $this->getTitle() . "\n" );
1673 # Get the file source or download if necessary
1674 $source = $this->getFileSrc();
1675 $flags = $this->isTempSrc() ? File
::DELETE_SOURCE
: 0;
1677 $source = $this->downloadSource();
1678 $flags |
= File
::DELETE_SOURCE
;
1681 wfDebug( __METHOD__
. ": Could not fetch remote file.\n" );
1684 $sha1 = $this->getSha1();
1685 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1686 if ( $flags & File
::DELETE_SOURCE
) {
1687 # Broken file; delete it if it is a temporary file
1690 wfDebug( __METHOD__
. ": Corrupt file $source.\n" );
1694 $user = User
::newFromName( $this->user_text
);
1696 # Do the actual upload
1697 if ( $archiveName ) {
1698 $status = $file->uploadOld( $source, $archiveName,
1699 $this->getTimestamp(), $this->getComment(), $user, $flags );
1701 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1702 $flags, false, $this->getTimestamp(), $user );
1705 if ( $status->isGood() ) {
1706 wfDebug( __METHOD__
. ": Successful\n" );
1709 wfDebug( __METHOD__
. ': failed: ' . $status->getXml() . "\n" );
1715 * @return bool|string
1717 function downloadSource() {
1718 if ( !$this->config
->get( 'EnableUploads' ) ) {
1722 $tempo = tempnam( wfTempDir(), 'download' );
1723 $f = fopen( $tempo, 'wb' );
1725 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1730 $src = $this->getSrc();
1731 $data = Http
::get( $src );
1733 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1739 fwrite( $f, $data );
1748 * Used for importing XML dumps where the content of the dump is in a string.
1749 * This class is ineffecient, and should only be used for small dumps.
1750 * For larger dumps, ImportStreamSource should be used instead.
1752 * @ingroup SpecialPage
1754 class ImportStringSource
{
1755 function __construct( $string ) {
1756 $this->mString
= $string;
1757 $this->mRead
= false;
1764 return $this->mRead
;
1768 * @return bool|string
1770 function readChunk() {
1771 if ( $this->atEnd() ) {
1774 $this->mRead
= true;
1775 return $this->mString
;
1780 * Imports a XML dump from a file (either from file upload, files on disk, or HTTP)
1781 * @ingroup SpecialPage
1783 class ImportStreamSource
{
1784 function __construct( $handle ) {
1785 $this->mHandle
= $handle;
1792 return feof( $this->mHandle
);
1798 function readChunk() {
1799 return fread( $this->mHandle
, 32768 );
1803 * @param string $filename
1806 static function newFromFile( $filename ) {
1807 wfSuppressWarnings();
1808 $file = fopen( $filename, 'rt' );
1809 wfRestoreWarnings();
1811 return Status
::newFatal( "importcantopen" );
1813 return Status
::newGood( new ImportStreamSource( $file ) );
1817 * @param string $fieldname
1820 static function newFromUpload( $fieldname = "xmlimport" ) {
1821 $upload =& $_FILES[$fieldname];
1823 if ( $upload === null ||
!$upload['name'] ) {
1824 return Status
::newFatal( 'importnofile' );
1826 if ( !empty( $upload['error'] ) ) {
1827 switch ( $upload['error'] ) {
1829 # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1830 return Status
::newFatal( 'importuploaderrorsize' );
1832 # The uploaded file exceeds the MAX_FILE_SIZE directive that
1833 # was specified in the HTML form.
1834 return Status
::newFatal( 'importuploaderrorsize' );
1836 # The uploaded file was only partially uploaded
1837 return Status
::newFatal( 'importuploaderrorpartial' );
1839 # Missing a temporary folder.
1840 return Status
::newFatal( 'importuploaderrortemp' );
1841 # case else: # Currently impossible
1845 $fname = $upload['tmp_name'];
1846 if ( is_uploaded_file( $fname ) ) {
1847 return ImportStreamSource
::newFromFile( $fname );
1849 return Status
::newFatal( 'importnofile' );
1854 * @param string $url
1855 * @param string $method
1858 static function newFromURL( $url, $method = 'GET' ) {
1859 wfDebug( __METHOD__
. ": opening $url\n" );
1860 # Use the standard HTTP fetch function; it times out
1861 # quicker and sorts out user-agent problems which might
1862 # otherwise prevent importing from large sites, such
1863 # as the Wikimedia cluster, etc.
1864 $data = Http
::request( $method, $url, array( 'followRedirects' => true ) );
1865 if ( $data !== false ) {
1867 fwrite( $file, $data );
1870 return Status
::newGood( new ImportStreamSource( $file ) );
1872 return Status
::newFatal( 'importcantopen' );
1877 * @param string $interwiki
1878 * @param string $page
1879 * @param bool $history
1880 * @param bool $templates
1881 * @param int $pageLinkDepth
1884 public static function newFromInterwiki( $interwiki, $page, $history = false,
1885 $templates = false, $pageLinkDepth = 0
1887 if ( $page == '' ) {
1888 return Status
::newFatal( 'import-noarticle' );
1890 $link = Title
::newFromText( "$interwiki:Special:Export/$page" );
1891 if ( is_null( $link ) ||
!$link->isExternal() ) {
1892 return Status
::newFatal( 'importbadinterwiki' );
1896 $params['history'] = 1;
1899 $params['templates'] = 1;
1901 if ( $pageLinkDepth ) {
1902 $params['pagelink-depth'] = $pageLinkDepth;
1904 $url = $link->getFullURL( $params );
1905 # For interwikis, use POST to avoid redirects.
1906 return ImportStreamSource
::newFromURL( $url, "POST" );