3 * MediaWiki page data importer.
5 * Copyright © 2003,2005 Brion Vibber <brion@pobox.com>
6 * https://www.mediawiki.org/
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
24 * @ingroup SpecialPage
28 * XML file reader for the page data importer
30 * implements Special:Import
31 * @ingroup SpecialPage
34 private $reader = null;
35 private $mLogItemCallback, $mUploadCallback, $mRevisionCallback, $mPageCallback;
36 private $mSiteInfoCallback, $mTargetNamespace, $mTargetRootPage, $mPageOutCallback;
37 private $mNoticeCallback, $mDebug;
38 private $mImportUploads, $mImageBasePath;
39 private $mNoUpdates = false;
42 * Creates an ImportXMLReader drawing from the source provided
43 * @param string $source
45 function __construct( $source ) {
46 $this->reader
= new XMLReader();
48 if ( !in_array( 'uploadsource', stream_get_wrappers() ) ) {
49 stream_wrapper_register( 'uploadsource', 'UploadSourceAdapter' );
51 $id = UploadSourceAdapter
::registerSource( $source );
52 if ( defined( 'LIBXML_PARSEHUGE' ) ) {
53 $this->reader
->open( "uploadsource://$id", null, LIBXML_PARSEHUGE
);
55 $this->reader
->open( "uploadsource://$id" );
59 $this->setRevisionCallback( array( $this, "importRevision" ) );
60 $this->setUploadCallback( array( $this, 'importUpload' ) );
61 $this->setLogItemCallback( array( $this, 'importLogItem' ) );
62 $this->setPageOutCallback( array( $this, 'finishImportPage' ) );
66 * @return null|XMLReader
68 public function getReader() {
72 public function throwXmlError( $err ) {
73 $this->debug( "FAILURE: $err" );
74 wfDebug( "WikiImporter XML error: $err\n" );
77 public function debug( $data ) {
78 if ( $this->mDebug
) {
79 wfDebug( "IMPORT: $data\n" );
83 public function warn( $data ) {
84 wfDebug( "IMPORT: $data\n" );
87 public function notice( $msg /*, $param, ...*/ ) {
88 $params = func_get_args();
89 array_shift( $params );
91 if ( is_callable( $this->mNoticeCallback
) ) {
92 call_user_func( $this->mNoticeCallback
, $msg, $params );
93 } else { # No ImportReporter -> CLI
94 echo wfMessage( $msg, $params )->text() . "\n";
102 function setDebug( $debug ) {
103 $this->mDebug
= $debug;
107 * Set 'no updates' mode. In this mode, the link tables will not be updated by the importer
108 * @param bool $noupdates
110 function setNoUpdates( $noupdates ) {
111 $this->mNoUpdates
= $noupdates;
115 * Set a callback that displays notice messages
117 * @param callable $callback
120 public function setNoticeCallback( $callback ) {
121 return wfSetVar( $this->mNoticeCallback
, $callback );
125 * Sets the action to perform as each new page in the stream is reached.
126 * @param callable $callback
129 public function setPageCallback( $callback ) {
130 $previous = $this->mPageCallback
;
131 $this->mPageCallback
= $callback;
136 * Sets the action to perform as each page in the stream is completed.
137 * Callback accepts the page title (as a Title object), a second object
138 * with the original title form (in case it's been overridden into a
139 * local namespace), and a count of revisions.
141 * @param callable $callback
144 public function setPageOutCallback( $callback ) {
145 $previous = $this->mPageOutCallback
;
146 $this->mPageOutCallback
= $callback;
151 * Sets the action to perform as each page revision is reached.
152 * @param callable $callback
155 public function setRevisionCallback( $callback ) {
156 $previous = $this->mRevisionCallback
;
157 $this->mRevisionCallback
= $callback;
162 * Sets the action to perform as each file upload version is reached.
163 * @param callable $callback
166 public function setUploadCallback( $callback ) {
167 $previous = $this->mUploadCallback
;
168 $this->mUploadCallback
= $callback;
173 * Sets the action to perform as each log item reached.
174 * @param callable $callback
177 public function setLogItemCallback( $callback ) {
178 $previous = $this->mLogItemCallback
;
179 $this->mLogItemCallback
= $callback;
184 * Sets the action to perform when site info is encountered
185 * @param callable $callback
188 public function setSiteInfoCallback( $callback ) {
189 $previous = $this->mSiteInfoCallback
;
190 $this->mSiteInfoCallback
= $callback;
195 * Set a target namespace to override the defaults
196 * @param null|int $namespace
199 public function setTargetNamespace( $namespace ) {
200 if ( is_null( $namespace ) ) {
201 // Don't override namespaces
202 $this->mTargetNamespace
= null;
203 } elseif ( $namespace >= 0 ) {
204 // @todo FIXME: Check for validity
205 $this->mTargetNamespace
= intval( $namespace );
212 * Set a target root page under which all pages are imported
213 * @param null|string $rootpage
216 public function setTargetRootPage( $rootpage ) {
217 $status = Status
::newGood();
218 if ( is_null( $rootpage ) ) {
220 $this->mTargetRootPage
= null;
221 } elseif ( $rootpage !== '' ) {
222 $rootpage = rtrim( $rootpage, '/' ); //avoid double slashes
223 $title = Title
::newFromText( $rootpage, !is_null( $this->mTargetNamespace
)
224 ?
$this->mTargetNamespace
228 if ( !$title ||
$title->isExternal() ) {
229 $status->fatal( 'import-rootpage-invalid' );
231 if ( !MWNamespace
::hasSubpages( $title->getNamespace() ) ) {
234 $displayNSText = $title->getNamespace() == NS_MAIN
235 ?
wfMessage( 'blanknamespace' )->text()
236 : $wgContLang->getNsText( $title->getNamespace() );
237 $status->fatal( 'import-rootpage-nosubpage', $displayNSText );
239 // set namespace to 'all', so the namespace check in processTitle() can passed
240 $this->setTargetNamespace( null );
241 $this->mTargetRootPage
= $title->getPrefixedDBkey();
251 public function setImageBasePath( $dir ) {
252 $this->mImageBasePath
= $dir;
256 * @param bool $import
258 public function setImportUploads( $import ) {
259 $this->mImportUploads
= $import;
263 * Default per-revision callback, performs the import.
264 * @param WikiRevision $revision
267 public function importRevision( $revision ) {
268 if ( !$revision->getContentHandler()->canBeUsedOn( $revision->getTitle() ) ) {
269 $this->notice( 'import-error-bad-location',
270 $revision->getTitle()->getPrefixedText(),
272 $revision->getModel(),
273 $revision->getFormat() );
279 $dbw = wfGetDB( DB_MASTER
);
280 return $dbw->deadlockLoop( array( $revision, 'importOldRevision' ) );
281 } catch ( MWContentSerializationException
$ex ) {
282 $this->notice( 'import-error-unserialize',
283 $revision->getTitle()->getPrefixedText(),
285 $revision->getModel(),
286 $revision->getFormat() );
293 * Default per-revision callback, performs the import.
294 * @param WikiRevision $revision
297 public function importLogItem( $revision ) {
298 $dbw = wfGetDB( DB_MASTER
);
299 return $dbw->deadlockLoop( array( $revision, 'importLogItem' ) );
304 * @param WikiRevision $revision
307 public function importUpload( $revision ) {
308 $dbw = wfGetDB( DB_MASTER
);
309 return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
313 * Mostly for hook use
314 * @param Title $title
315 * @param string $origTitle
316 * @param int $revCount
317 * @param int $sRevCount
318 * @param array $pageInfo
321 public function finishImportPage( $title, $origTitle, $revCount, $sRevCount, $pageInfo ) {
322 $args = func_get_args();
323 return wfRunHooks( 'AfterImportPage', $args );
327 * Alternate per-revision callback, for debugging.
328 * @param WikiRevision $revision
330 public function debugRevisionHandler( &$revision ) {
331 $this->debug( "Got revision:" );
332 if ( is_object( $revision->title
) ) {
333 $this->debug( "-- Title: " . $revision->title
->getPrefixedText() );
335 $this->debug( "-- Title: <invalid>" );
337 $this->debug( "-- User: " . $revision->user_text
);
338 $this->debug( "-- Timestamp: " . $revision->timestamp
);
339 $this->debug( "-- Comment: " . $revision->comment
);
340 $this->debug( "-- Text: " . $revision->text
);
344 * Notify the callback function when a new "<page>" is reached.
345 * @param Title $title
347 function pageCallback( $title ) {
348 if ( isset( $this->mPageCallback
) ) {
349 call_user_func( $this->mPageCallback
, $title );
354 * Notify the callback function when a "</page>" is closed.
355 * @param Title $title
356 * @param Title $origTitle
357 * @param int $revCount
358 * @param int $sucCount Number of revisions for which callback returned true
359 * @param array $pageInfo Associative array of page information
361 private function pageOutCallback( $title, $origTitle, $revCount, $sucCount, $pageInfo ) {
362 if ( isset( $this->mPageOutCallback
) ) {
363 $args = func_get_args();
364 call_user_func_array( $this->mPageOutCallback
, $args );
369 * Notify the callback function of a revision
370 * @param WikiRevision $revision
373 private function revisionCallback( $revision ) {
374 if ( isset( $this->mRevisionCallback
) ) {
375 return call_user_func_array( $this->mRevisionCallback
,
376 array( $revision, $this ) );
383 * Notify the callback function of a new log item
384 * @param WikiRevision $revision
387 private function logItemCallback( $revision ) {
388 if ( isset( $this->mLogItemCallback
) ) {
389 return call_user_func_array( $this->mLogItemCallback
,
390 array( $revision, $this ) );
397 * Shouldn't something like this be built-in to XMLReader?
398 * Fetches text contents of the current element, assuming
399 * no sub-elements or such scary things.
403 public function nodeContents() {
404 if ( $this->reader
->isEmptyElement
) {
408 while ( $this->reader
->read() ) {
409 switch ( $this->reader
->nodeType
) {
410 case XmlReader
::TEXT
:
411 case XmlReader
::SIGNIFICANT_WHITESPACE
:
412 $buffer .= $this->reader
->value
;
414 case XmlReader
::END_ELEMENT
:
419 $this->reader
->close();
425 /** Left in for debugging */
426 private function dumpElement() {
427 static $lookup = null;
429 $xmlReaderConstants = array(
444 "SIGNIFICANT_WHITESPACE",
451 foreach ( $xmlReaderConstants as $name ) {
452 $lookup[constant( "XmlReader::$name" )] = $name;
457 $lookup[$this->reader
->nodeType
],
464 * Primary entry point
465 * @throws MWException
468 public function doImport() {
470 // Calls to reader->read need to be wrapped in calls to
471 // libxml_disable_entity_loader() to avoid local file
472 // inclusion attacks (bug 46932).
473 $oldDisable = libxml_disable_entity_loader( true );
474 $this->reader
->read();
476 if ( $this->reader
->name
!= 'mediawiki' ) {
477 libxml_disable_entity_loader( $oldDisable );
478 throw new MWException( "Expected <mediawiki> tag, got " .
479 $this->reader
->name
);
481 $this->debug( "<mediawiki> tag is correct." );
483 $this->debug( "Starting primary dump processing loop." );
485 $keepReading = $this->reader
->read();
487 while ( $keepReading ) {
488 $tag = $this->reader
->name
;
489 $type = $this->reader
->nodeType
;
491 if ( !wfRunHooks( 'ImportHandleToplevelXMLTag', array( $this ) ) ) {
493 } elseif ( $tag == 'mediawiki' && $type == XmlReader
::END_ELEMENT
) {
495 } elseif ( $tag == 'siteinfo' ) {
496 $this->handleSiteInfo();
497 } elseif ( $tag == 'page' ) {
499 } elseif ( $tag == 'logitem' ) {
500 $this->handleLogItem();
501 } elseif ( $tag != '#text' ) {
502 $this->warn( "Unhandled top-level XML tag $tag" );
508 $keepReading = $this->reader
->next();
510 $this->debug( "Skip" );
512 $keepReading = $this->reader
->read();
516 libxml_disable_entity_loader( $oldDisable );
522 * @throws MWException
524 private function handleSiteInfo() {
525 // Site info is useful, but not actually used for dump imports.
526 // Includes a quick short-circuit to save performance.
527 if ( ! $this->mSiteInfoCallback
) {
528 $this->reader
->next();
531 throw new MWException( "SiteInfo tag is not yet handled, do not set mSiteInfoCallback" );
534 private function handleLogItem() {
535 $this->debug( "Enter log item handler." );
538 // Fields that can just be stuffed in the pageInfo object
539 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
540 'logtitle', 'params' );
542 while ( $this->reader
->read() ) {
543 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
544 $this->reader
->name
== 'logitem' ) {
548 $tag = $this->reader
->name
;
550 if ( !wfRunHooks( 'ImportHandleLogItemXMLTag', array(
554 } elseif ( in_array( $tag, $normalFields ) ) {
555 $logInfo[$tag] = $this->nodeContents();
556 } elseif ( $tag == 'contributor' ) {
557 $logInfo['contributor'] = $this->handleContributor();
558 } elseif ( $tag != '#text' ) {
559 $this->warn( "Unhandled log-item XML tag $tag" );
563 $this->processLogItem( $logInfo );
567 * @param array $logInfo
570 private function processLogItem( $logInfo ) {
571 $revision = new WikiRevision
;
573 $revision->setID( $logInfo['id'] );
574 $revision->setType( $logInfo['type'] );
575 $revision->setAction( $logInfo['action'] );
576 $revision->setTimestamp( $logInfo['timestamp'] );
577 $revision->setParams( $logInfo['params'] );
578 $revision->setTitle( Title
::newFromText( $logInfo['logtitle'] ) );
579 $revision->setNoUpdates( $this->mNoUpdates
);
581 if ( isset( $logInfo['comment'] ) ) {
582 $revision->setComment( $logInfo['comment'] );
585 if ( isset( $logInfo['contributor']['ip'] ) ) {
586 $revision->setUserIP( $logInfo['contributor']['ip'] );
588 if ( isset( $logInfo['contributor']['username'] ) ) {
589 $revision->setUserName( $logInfo['contributor']['username'] );
592 return $this->logItemCallback( $revision );
595 private function handlePage() {
597 $this->debug( "Enter page handler." );
598 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
600 // Fields that can just be stuffed in the pageInfo object
601 $normalFields = array( 'title', 'id', 'redirect', 'restrictions' );
606 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
607 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
608 $this->reader
->name
== 'page' ) {
612 $tag = $this->reader
->name
;
615 // The title is invalid, bail out of this page
617 } elseif ( !wfRunHooks( 'ImportHandlePageXMLTag', array( $this,
620 } elseif ( in_array( $tag, $normalFields ) ) {
621 $pageInfo[$tag] = $this->nodeContents();
622 if ( $tag == 'title' ) {
623 $title = $this->processTitle( $pageInfo['title'] );
630 $this->pageCallback( $title );
631 list( $pageInfo['_title'], $origTitle ) = $title;
633 } elseif ( $tag == 'revision' ) {
634 $this->handleRevision( $pageInfo );
635 } elseif ( $tag == 'upload' ) {
636 $this->handleUpload( $pageInfo );
637 } elseif ( $tag != '#text' ) {
638 $this->warn( "Unhandled page XML tag $tag" );
643 $this->pageOutCallback( $pageInfo['_title'], $origTitle,
644 $pageInfo['revisionCount'],
645 $pageInfo['successfulRevisionCount'],
650 * @param array $pageInfo
652 private function handleRevision( &$pageInfo ) {
653 $this->debug( "Enter revision handler" );
654 $revisionInfo = array();
656 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'model', 'format', 'text' );
660 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
661 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
662 $this->reader
->name
== 'revision' ) {
666 $tag = $this->reader
->name
;
668 if ( !wfRunHooks( 'ImportHandleRevisionXMLTag', array(
669 $this, $pageInfo, $revisionInfo
672 } elseif ( in_array( $tag, $normalFields ) ) {
673 $revisionInfo[$tag] = $this->nodeContents();
674 } elseif ( $tag == 'contributor' ) {
675 $revisionInfo['contributor'] = $this->handleContributor();
676 } elseif ( $tag != '#text' ) {
677 $this->warn( "Unhandled revision XML tag $tag" );
682 $pageInfo['revisionCount']++
;
683 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
684 $pageInfo['successfulRevisionCount']++
;
689 * @param array $pageInfo
690 * @param array $revisionInfo
693 private function processRevision( $pageInfo, $revisionInfo ) {
694 $revision = new WikiRevision
;
696 if ( isset( $revisionInfo['id'] ) ) {
697 $revision->setID( $revisionInfo['id'] );
699 if ( isset( $revisionInfo['model'] ) ) {
700 $revision->setModel( $revisionInfo['model'] );
702 if ( isset( $revisionInfo['format'] ) ) {
703 $revision->setFormat( $revisionInfo['format'] );
705 $revision->setTitle( $pageInfo['_title'] );
707 if ( isset( $revisionInfo['text'] ) ) {
708 $handler = $revision->getContentHandler();
709 $text = $handler->importTransform(
710 $revisionInfo['text'],
711 $revision->getFormat() );
713 $revision->setText( $text );
715 if ( isset( $revisionInfo['timestamp'] ) ) {
716 $revision->setTimestamp( $revisionInfo['timestamp'] );
718 $revision->setTimestamp( wfTimestampNow() );
721 if ( isset( $revisionInfo['comment'] ) ) {
722 $revision->setComment( $revisionInfo['comment'] );
725 if ( isset( $revisionInfo['minor'] ) ) {
726 $revision->setMinor( true );
728 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
729 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
731 if ( isset( $revisionInfo['contributor']['username'] ) ) {
732 $revision->setUserName( $revisionInfo['contributor']['username'] );
734 $revision->setNoUpdates( $this->mNoUpdates
);
736 return $this->revisionCallback( $revision );
740 * @param array $pageInfo
743 private function handleUpload( &$pageInfo ) {
744 $this->debug( "Enter upload handler" );
745 $uploadInfo = array();
747 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
748 'src', 'size', 'sha1base36', 'archivename', 'rel' );
752 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
753 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
754 $this->reader
->name
== 'upload' ) {
758 $tag = $this->reader
->name
;
760 if ( !wfRunHooks( 'ImportHandleUploadXMLTag', array(
764 } elseif ( in_array( $tag, $normalFields ) ) {
765 $uploadInfo[$tag] = $this->nodeContents();
766 } elseif ( $tag == 'contributor' ) {
767 $uploadInfo['contributor'] = $this->handleContributor();
768 } elseif ( $tag == 'contents' ) {
769 $contents = $this->nodeContents();
770 $encoding = $this->reader
->getAttribute( 'encoding' );
771 if ( $encoding === 'base64' ) {
772 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
773 $uploadInfo['isTempSrc'] = true;
775 } elseif ( $tag != '#text' ) {
776 $this->warn( "Unhandled upload XML tag $tag" );
781 if ( $this->mImageBasePath
&& isset( $uploadInfo['rel'] ) ) {
782 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
783 if ( file_exists( $path ) ) {
784 $uploadInfo['fileSrc'] = $path;
785 $uploadInfo['isTempSrc'] = false;
789 if ( $this->mImportUploads
) {
790 return $this->processUpload( $pageInfo, $uploadInfo );
795 * @param string $contents
798 private function dumpTemp( $contents ) {
799 $filename = tempnam( wfTempDir(), 'importupload' );
800 file_put_contents( $filename, $contents );
805 * @param array $pageInfo
806 * @param array $uploadInfo
809 private function processUpload( $pageInfo, $uploadInfo ) {
810 $revision = new WikiRevision
;
811 $text = isset( $uploadInfo['text'] ) ?
$uploadInfo['text'] : '';
813 $revision->setTitle( $pageInfo['_title'] );
814 $revision->setID( $pageInfo['id'] );
815 $revision->setTimestamp( $uploadInfo['timestamp'] );
816 $revision->setText( $text );
817 $revision->setFilename( $uploadInfo['filename'] );
818 if ( isset( $uploadInfo['archivename'] ) ) {
819 $revision->setArchiveName( $uploadInfo['archivename'] );
821 $revision->setSrc( $uploadInfo['src'] );
822 if ( isset( $uploadInfo['fileSrc'] ) ) {
823 $revision->setFileSrc( $uploadInfo['fileSrc'],
824 !empty( $uploadInfo['isTempSrc'] ) );
826 if ( isset( $uploadInfo['sha1base36'] ) ) {
827 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
829 $revision->setSize( intval( $uploadInfo['size'] ) );
830 $revision->setComment( $uploadInfo['comment'] );
832 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
833 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
835 if ( isset( $uploadInfo['contributor']['username'] ) ) {
836 $revision->setUserName( $uploadInfo['contributor']['username'] );
838 $revision->setNoUpdates( $this->mNoUpdates
);
840 return call_user_func( $this->mUploadCallback
, $revision );
846 private function handleContributor() {
847 $fields = array( 'id', 'ip', 'username' );
850 while ( $this->reader
->read() ) {
851 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
852 $this->reader
->name
== 'contributor' ) {
856 $tag = $this->reader
->name
;
858 if ( in_array( $tag, $fields ) ) {
859 $info[$tag] = $this->nodeContents();
867 * @param string $text
870 private function processTitle( $text ) {
871 global $wgCommandLineMode;
874 $origTitle = Title
::newFromText( $workTitle );
876 if ( !is_null( $this->mTargetNamespace
) && !is_null( $origTitle ) ) {
877 # makeTitleSafe, because $origTitle can have a interwiki (different setting of interwiki map)
878 # and than dbKey can begin with a lowercase char
879 $title = Title
::makeTitleSafe( $this->mTargetNamespace
,
880 $origTitle->getDBkey() );
882 if ( !is_null( $this->mTargetRootPage
) ) {
883 $workTitle = $this->mTargetRootPage
. '/' . $workTitle;
885 $title = Title
::newFromText( $workTitle );
888 if ( is_null( $title ) ) {
889 # Invalid page title? Ignore the page
890 $this->notice( 'import-error-invalid', $workTitle );
892 } elseif ( $title->isExternal() ) {
893 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
895 } elseif ( !$title->canExist() ) {
896 $this->notice( 'import-error-special', $title->getPrefixedText() );
898 } elseif ( !$title->userCan( 'edit' ) && !$wgCommandLineMode ) {
899 # Do not import if the importing wiki user cannot edit this page
900 $this->notice( 'import-error-edit', $title->getPrefixedText() );
902 } elseif ( !$title->exists() && !$title->userCan( 'create' ) && !$wgCommandLineMode ) {
903 # Do not import if the importing wiki user cannot create this page
904 $this->notice( 'import-error-create', $title->getPrefixedText() );
908 return array( $title, $origTitle );
912 /** This is a horrible hack used to keep source compatibility */
913 class UploadSourceAdapter
{
915 private static $sourceRegistrations = array();
927 * @param string $source
930 static function registerSource( $source ) {
931 $id = wfRandomString();
933 self
::$sourceRegistrations[$id] = $source;
939 * @param string $path
940 * @param string $mode
941 * @param array $options
942 * @param string $opened_path
945 function stream_open( $path, $mode, $options, &$opened_path ) {
946 $url = parse_url( $path );
949 if ( !isset( self
::$sourceRegistrations[$id] ) ) {
953 $this->mSource
= self
::$sourceRegistrations[$id];
962 function stream_read( $count ) {
966 while ( !$leave && !$this->mSource
->atEnd() &&
967 strlen( $this->mBuffer
) < $count ) {
968 $read = $this->mSource
->readChunk();
970 if ( !strlen( $read ) ) {
974 $this->mBuffer
.= $read;
977 if ( strlen( $this->mBuffer
) ) {
978 $return = substr( $this->mBuffer
, 0, $count );
979 $this->mBuffer
= substr( $this->mBuffer
, $count );
982 $this->mPosition +
= strlen( $return );
988 * @param string $data
991 function stream_write( $data ) {
998 function stream_tell() {
999 return $this->mPosition
;
1005 function stream_eof() {
1006 return $this->mSource
->atEnd();
1012 function url_stat() {
1015 $result['dev'] = $result[0] = 0;
1016 $result['ino'] = $result[1] = 0;
1017 $result['mode'] = $result[2] = 0;
1018 $result['nlink'] = $result[3] = 0;
1019 $result['uid'] = $result[4] = 0;
1020 $result['gid'] = $result[5] = 0;
1021 $result['rdev'] = $result[6] = 0;
1022 $result['size'] = $result[7] = 0;
1023 $result['atime'] = $result[8] = 0;
1024 $result['mtime'] = $result[9] = 0;
1025 $result['ctime'] = $result[10] = 0;
1026 $result['blksize'] = $result[11] = 0;
1027 $result['blocks'] = $result[12] = 0;
1033 class XMLReader2
extends XMLReader
{
1036 * @return bool|string
1038 function nodeContents() {
1039 if ( $this->isEmptyElement
) {
1043 while ( $this->read() ) {
1044 switch ( $this->nodeType
) {
1045 case XmlReader
::TEXT
:
1046 case XmlReader
::SIGNIFICANT_WHITESPACE
:
1047 $buffer .= $this->value
;
1049 case XmlReader
::END_ELEMENT
:
1053 return $this->close();
1058 * @todo document (e.g. one-sentence class description).
1059 * @ingroup SpecialPage
1061 class WikiRevision
{
1062 /** @todo Unused? */
1063 private $importer = null;
1066 public $title = null;
1072 public $timestamp = "20010115000000";
1076 * @todo Can't find any uses. Public, because that's suspicious. Get clarity. */
1080 public $user_text = "";
1083 protected $model = null;
1086 protected $format = null;
1095 protected $content = null;
1097 /** @var ContentHandler */
1098 protected $contentHandler = null;
1101 public $comment = "";
1104 protected $minor = false;
1107 protected $type = "";
1110 protected $action = "";
1113 protected $params = "";
1116 protected $fileSrc = '';
1118 /** @var bool|string */
1119 protected $sha1base36 = false;
1125 private $isTemp = false;
1128 protected $archiveName = '';
1130 protected $filename;
1135 /** @todo Unused? */
1136 private $fileIsTemp;
1139 private $mNoUpdates = false;
1142 * @param Title $title
1143 * @throws MWException
1145 function setTitle( $title ) {
1146 if ( is_object( $title ) ) {
1147 $this->title
= $title;
1148 } elseif ( is_null( $title ) ) {
1149 throw new MWException( "WikiRevision given a null title in import. "
1150 . "You may need to adjust \$wgLegalTitleChars." );
1152 throw new MWException( "WikiRevision given non-object title in import." );
1159 function setID( $id ) {
1166 function setTimestamp( $ts ) {
1167 # 2003-08-05T18:30:02Z
1168 $this->timestamp
= wfTimestamp( TS_MW
, $ts );
1172 * @param string $user
1174 function setUsername( $user ) {
1175 $this->user_text
= $user;
1181 function setUserIP( $ip ) {
1182 $this->user_text
= $ip;
1186 * @param string $model
1188 function setModel( $model ) {
1189 $this->model
= $model;
1193 * @param string $format
1195 function setFormat( $format ) {
1196 $this->format
= $format;
1200 * @param string $text
1202 function setText( $text ) {
1203 $this->text
= $text;
1207 * @param string $text
1209 function setComment( $text ) {
1210 $this->comment
= $text;
1214 * @param bool $minor
1216 function setMinor( $minor ) {
1217 $this->minor
= (bool)$minor;
1223 function setSrc( $src ) {
1228 * @param string $src
1229 * @param bool $isTemp
1231 function setFileSrc( $src, $isTemp ) {
1232 $this->fileSrc
= $src;
1233 $this->fileIsTemp
= $isTemp;
1237 * @param string $sha1base36
1239 function setSha1Base36( $sha1base36 ) {
1240 $this->sha1base36
= $sha1base36;
1244 * @param string $filename
1246 function setFilename( $filename ) {
1247 $this->filename
= $filename;
1251 * @param string $archiveName
1253 function setArchiveName( $archiveName ) {
1254 $this->archiveName
= $archiveName;
1260 function setSize( $size ) {
1261 $this->size
= intval( $size );
1265 * @param string $type
1267 function setType( $type ) {
1268 $this->type
= $type;
1272 * @param string $action
1274 function setAction( $action ) {
1275 $this->action
= $action;
1279 * @param array $params
1281 function setParams( $params ) {
1282 $this->params
= $params;
1286 * @param bool $noupdates
1288 public function setNoUpdates( $noupdates ) {
1289 $this->mNoUpdates
= $noupdates;
1295 function getTitle() {
1296 return $this->title
;
1309 function getTimestamp() {
1310 return $this->timestamp
;
1316 function getUser() {
1317 return $this->user_text
;
1323 * @deprecated Since 1.21, use getContent() instead.
1325 function getText() {
1326 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1332 * @return ContentHandler
1334 function getContentHandler() {
1335 if ( is_null( $this->contentHandler
) ) {
1336 $this->contentHandler
= ContentHandler
::getForModelID( $this->getModel() );
1339 return $this->contentHandler
;
1345 function getContent() {
1346 if ( is_null( $this->content
) ) {
1347 $handler = $this->getContentHandler();
1348 $this->content
= $handler->unserializeContent( $this->text
, $this->getFormat() );
1351 return $this->content
;
1357 function getModel() {
1358 if ( is_null( $this->model
) ) {
1359 $this->model
= $this->getTitle()->getContentModel();
1362 return $this->model
;
1368 function getFormat() {
1369 if ( is_null( $this->format
) ) {
1370 $this->format
= $this->getContentHandler()->getDefaultFormat();
1373 return $this->format
;
1379 function getComment() {
1380 return $this->comment
;
1386 function getMinor() {
1387 return $this->minor
;
1398 * @return bool|string
1400 function getSha1() {
1401 if ( $this->sha1base36
) {
1402 return wfBaseConvert( $this->sha1base36
, 36, 16 );
1410 function getFileSrc() {
1411 return $this->fileSrc
;
1417 function isTempSrc() {
1418 return $this->isTemp
;
1424 function getFilename() {
1425 return $this->filename
;
1431 function getArchiveName() {
1432 return $this->archiveName
;
1438 function getSize() {
1445 function getType() {
1452 function getAction() {
1453 return $this->action
;
1459 function getParams() {
1460 return $this->params
;
1466 function importOldRevision() {
1467 $dbw = wfGetDB( DB_MASTER
);
1469 # Sneak a single revision into place
1470 $user = User
::newFromName( $this->getUser() );
1472 $userId = intval( $user->getId() );
1473 $userText = $user->getName();
1477 $userText = $this->getUser();
1478 $userObj = new User
;
1481 // avoid memory leak...?
1482 $linkCache = LinkCache
::singleton();
1483 $linkCache->clear();
1485 $page = WikiPage
::factory( $this->title
);
1486 if ( !$page->exists() ) {
1487 # must create the page...
1488 $pageId = $page->insertOn( $dbw );
1490 $oldcountable = null;
1492 $pageId = $page->getId();
1495 $prior = $dbw->selectField( 'revision', '1',
1496 array( 'rev_page' => $pageId,
1497 'rev_timestamp' => $dbw->timestamp( $this->timestamp
),
1498 'rev_user_text' => $userText,
1499 'rev_comment' => $this->getComment() ),
1503 // @todo FIXME: This could fail slightly for multiple matches :P
1504 wfDebug( __METHOD__
. ": skipping existing revision for [[" .
1505 $this->title
->getPrefixedText() . "]], timestamp " . $this->timestamp
. "\n" );
1508 $oldcountable = $page->isCountable();
1511 # @todo FIXME: Use original rev_id optionally (better for backups)
1513 $revision = new Revision( array(
1514 'title' => $this->title
,
1516 'content_model' => $this->getModel(),
1517 'content_format' => $this->getFormat(),
1518 //XXX: just set 'content' => $this->getContent()?
1519 'text' => $this->getContent()->serialize( $this->getFormat() ),
1520 'comment' => $this->getComment(),
1522 'user_text' => $userText,
1523 'timestamp' => $this->timestamp
,
1524 'minor_edit' => $this->minor
,
1526 $revision->insertOn( $dbw );
1527 $changed = $page->updateIfNewerOn( $dbw, $revision );
1529 if ( $changed !== false && !$this->mNoUpdates
) {
1530 wfDebug( __METHOD__
. ": running updates\n" );
1531 $page->doEditUpdates(
1534 array( 'created' => $created, 'oldcountable' => $oldcountable )
1544 function importLogItem() {
1545 $dbw = wfGetDB( DB_MASTER
);
1546 # @todo FIXME: This will not record autoblocks
1547 if ( !$this->getTitle() ) {
1548 wfDebug( __METHOD__
. ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1549 $this->timestamp
. "\n" );
1552 # Check if it exists already
1553 // @todo FIXME: Use original log ID (better for backups)
1554 $prior = $dbw->selectField( 'logging', '1',
1555 array( 'log_type' => $this->getType(),
1556 'log_action' => $this->getAction(),
1557 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1558 'log_namespace' => $this->getTitle()->getNamespace(),
1559 'log_title' => $this->getTitle()->getDBkey(),
1560 'log_comment' => $this->getComment(),
1561 #'log_user_text' => $this->user_text,
1562 'log_params' => $this->params
),
1565 // @todo FIXME: This could fail slightly for multiple matches :P
1568 . ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp "
1569 . $this->timestamp
. "\n" );
1572 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1574 'log_id' => $log_id,
1575 'log_type' => $this->type
,
1576 'log_action' => $this->action
,
1577 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1578 'log_user' => User
::idFromName( $this->user_text
),
1579 #'log_user_text' => $this->user_text,
1580 'log_namespace' => $this->getTitle()->getNamespace(),
1581 'log_title' => $this->getTitle()->getDBkey(),
1582 'log_comment' => $this->getComment(),
1583 'log_params' => $this->params
1585 $dbw->insert( 'logging', $data, __METHOD__
);
1591 function importUpload() {
1593 $archiveName = $this->getArchiveName();
1594 if ( $archiveName ) {
1595 wfDebug( __METHOD__
. "Importing archived file as $archiveName\n" );
1596 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1597 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1599 $file = wfLocalFile( $this->getTitle() );
1600 wfDebug( __METHOD__
. 'Importing new file as ' . $file->getName() . "\n" );
1601 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1602 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1603 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1604 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1605 wfDebug( __METHOD__
. "File already exists; importing as $archiveName\n" );
1609 wfDebug( __METHOD__
. ': Bad file for ' . $this->getTitle() . "\n" );
1613 # Get the file source or download if necessary
1614 $source = $this->getFileSrc();
1615 $flags = $this->isTempSrc() ? File
::DELETE_SOURCE
: 0;
1617 $source = $this->downloadSource();
1618 $flags |
= File
::DELETE_SOURCE
;
1621 wfDebug( __METHOD__
. ": Could not fetch remote file.\n" );
1624 $sha1 = $this->getSha1();
1625 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1626 if ( $flags & File
::DELETE_SOURCE
) {
1627 # Broken file; delete it if it is a temporary file
1630 wfDebug( __METHOD__
. ": Corrupt file $source.\n" );
1634 $user = User
::newFromName( $this->user_text
);
1636 # Do the actual upload
1637 if ( $archiveName ) {
1638 $status = $file->uploadOld( $source, $archiveName,
1639 $this->getTimestamp(), $this->getComment(), $user, $flags );
1641 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1642 $flags, false, $this->getTimestamp(), $user );
1645 if ( $status->isGood() ) {
1646 wfDebug( __METHOD__
. ": Successful\n" );
1649 wfDebug( __METHOD__
. ': failed: ' . $status->getXml() . "\n" );
1655 * @return bool|string
1657 function downloadSource() {
1658 global $wgEnableUploads;
1659 if ( !$wgEnableUploads ) {
1663 $tempo = tempnam( wfTempDir(), 'download' );
1664 $f = fopen( $tempo, 'wb' );
1666 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1671 $src = $this->getSrc();
1672 $data = Http
::get( $src );
1674 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1680 fwrite( $f, $data );
1689 * @todo document (e.g. one-sentence class description).
1690 * @ingroup SpecialPage
1692 class ImportStringSource
{
1693 function __construct( $string ) {
1694 $this->mString
= $string;
1695 $this->mRead
= false;
1702 return $this->mRead
;
1706 * @return bool|string
1708 function readChunk() {
1709 if ( $this->atEnd() ) {
1712 $this->mRead
= true;
1713 return $this->mString
;
1718 * @todo document (e.g. one-sentence class description).
1719 * @ingroup SpecialPage
1721 class ImportStreamSource
{
1722 function __construct( $handle ) {
1723 $this->mHandle
= $handle;
1730 return feof( $this->mHandle
);
1736 function readChunk() {
1737 return fread( $this->mHandle
, 32768 );
1741 * @param string $filename
1744 static function newFromFile( $filename ) {
1745 wfSuppressWarnings();
1746 $file = fopen( $filename, 'rt' );
1747 wfRestoreWarnings();
1749 return Status
::newFatal( "importcantopen" );
1751 return Status
::newGood( new ImportStreamSource( $file ) );
1755 * @param string $fieldname
1758 static function newFromUpload( $fieldname = "xmlimport" ) {
1759 $upload =& $_FILES[$fieldname];
1761 if ( $upload === null ||
!$upload['name'] ) {
1762 return Status
::newFatal( 'importnofile' );
1764 if ( !empty( $upload['error'] ) ) {
1765 switch ( $upload['error'] ) {
1767 # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1768 return Status
::newFatal( 'importuploaderrorsize' );
1770 # The uploaded file exceeds the MAX_FILE_SIZE directive that
1771 # was specified in the HTML form.
1772 return Status
::newFatal( 'importuploaderrorsize' );
1774 # The uploaded file was only partially uploaded
1775 return Status
::newFatal( 'importuploaderrorpartial' );
1777 # Missing a temporary folder.
1778 return Status
::newFatal( 'importuploaderrortemp' );
1779 # case else: # Currently impossible
1783 $fname = $upload['tmp_name'];
1784 if ( is_uploaded_file( $fname ) ) {
1785 return ImportStreamSource
::newFromFile( $fname );
1787 return Status
::newFatal( 'importnofile' );
1792 * @param string $url
1793 * @param string $method
1796 static function newFromURL( $url, $method = 'GET' ) {
1797 wfDebug( __METHOD__
. ": opening $url\n" );
1798 # Use the standard HTTP fetch function; it times out
1799 # quicker and sorts out user-agent problems which might
1800 # otherwise prevent importing from large sites, such
1801 # as the Wikimedia cluster, etc.
1802 $data = Http
::request( $method, $url, array( 'followRedirects' => true ) );
1803 if ( $data !== false ) {
1805 fwrite( $file, $data );
1808 return Status
::newGood( new ImportStreamSource( $file ) );
1810 return Status
::newFatal( 'importcantopen' );
1815 * @param string $interwiki
1816 * @param string $page
1817 * @param bool $history
1818 * @param bool $templates
1819 * @param int $pageLinkDepth
1822 public static function newFromInterwiki( $interwiki, $page, $history = false,
1823 $templates = false, $pageLinkDepth = 0
1825 if ( $page == '' ) {
1826 return Status
::newFatal( 'import-noarticle' );
1828 $link = Title
::newFromText( "$interwiki:Special:Export/$page" );
1829 if ( is_null( $link ) ||
!$link->isExternal() ) {
1830 return Status
::newFatal( 'importbadinterwiki' );
1834 $params['history'] = 1;
1837 $params['templates'] = 1;
1839 if ( $pageLinkDepth ) {
1840 $params['pagelink-depth'] = $pageLinkDepth;
1842 $url = $link->getFullURL( $params );
1843 # For interwikis, use POST to avoid redirects.
1844 return ImportStreamSource
::newFromURL( $url, "POST" );