3 * MediaWiki page data importer.
5 * Copyright © 2003,2005 Brion Vibber <brion@pobox.com>
6 * http://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
45 function __construct( $source ) {
46 $this->reader
= new XMLReader();
48 stream_wrapper_register( 'uploadsource', 'UploadSourceAdapter' );
49 $id = UploadSourceAdapter
::registerSource( $source );
50 if (defined( 'LIBXML_PARSEHUGE' ) ) {
51 $this->reader
->open( "uploadsource://$id", null, LIBXML_PARSEHUGE
);
53 $this->reader
->open( "uploadsource://$id" );
57 $this->setRevisionCallback( array( $this, "importRevision" ) );
58 $this->setUploadCallback( array( $this, 'importUpload' ) );
59 $this->setLogItemCallback( array( $this, 'importLogItem' ) );
60 $this->setPageOutCallback( array( $this, 'finishImportPage' ) );
63 private function throwXmlError( $err ) {
64 $this->debug( "FAILURE: $err" );
65 wfDebug( "WikiImporter XML error: $err\n" );
68 private function debug( $data ) {
70 wfDebug( "IMPORT: $data\n" );
74 private function warn( $data ) {
75 wfDebug( "IMPORT: $data\n" );
78 private function notice( $msg /*, $param, ...*/ ) {
79 $params = func_get_args();
80 array_shift( $params );
82 if ( is_callable( $this->mNoticeCallback
) ) {
83 call_user_func( $this->mNoticeCallback
, $msg, $params );
84 } else { # No ImportReporter -> CLI
85 echo wfMessage( $msg, $params )->text() . "\n";
93 function setDebug( $debug ) {
94 $this->mDebug
= $debug;
98 * Set 'no updates' mode. In this mode, the link tables will not be updated by the importer
99 * @param $noupdates bool
101 function setNoUpdates( $noupdates ) {
102 $this->mNoUpdates
= $noupdates;
106 * Set a callback that displays notice messages
108 * @param $callback callback
111 public function setNoticeCallback( $callback ) {
112 return wfSetVar( $this->mNoticeCallback
, $callback );
116 * Sets the action to perform as each new page in the stream is reached.
117 * @param $callback callback
120 public function setPageCallback( $callback ) {
121 $previous = $this->mPageCallback
;
122 $this->mPageCallback
= $callback;
127 * Sets the action to perform as each page in the stream is completed.
128 * Callback accepts the page title (as a Title object), a second object
129 * with the original title form (in case it's been overridden into a
130 * local namespace), and a count of revisions.
132 * @param $callback callback
135 public function setPageOutCallback( $callback ) {
136 $previous = $this->mPageOutCallback
;
137 $this->mPageOutCallback
= $callback;
142 * Sets the action to perform as each page revision is reached.
143 * @param $callback callback
146 public function setRevisionCallback( $callback ) {
147 $previous = $this->mRevisionCallback
;
148 $this->mRevisionCallback
= $callback;
153 * Sets the action to perform as each file upload version is reached.
154 * @param $callback callback
157 public function setUploadCallback( $callback ) {
158 $previous = $this->mUploadCallback
;
159 $this->mUploadCallback
= $callback;
164 * Sets the action to perform as each log item reached.
165 * @param $callback callback
168 public function setLogItemCallback( $callback ) {
169 $previous = $this->mLogItemCallback
;
170 $this->mLogItemCallback
= $callback;
175 * Sets the action to perform when site info is encountered
176 * @param $callback callback
179 public function setSiteInfoCallback( $callback ) {
180 $previous = $this->mSiteInfoCallback
;
181 $this->mSiteInfoCallback
= $callback;
186 * Set a target namespace to override the defaults
190 public function setTargetNamespace( $namespace ) {
191 if( is_null( $namespace ) ) {
192 // Don't override namespaces
193 $this->mTargetNamespace
= null;
194 } elseif( $namespace >= 0 ) {
195 // @todo FIXME: Check for validity
196 $this->mTargetNamespace
= intval( $namespace );
203 * Set a target root page under which all pages are imported
205 * @return status object
207 public function setTargetRootPage( $rootpage ) {
208 $status = Status
::newGood();
209 if( is_null( $rootpage ) ) {
211 $this->mTargetRootPage
= null;
212 } elseif( $rootpage !== '' ) {
213 $rootpage = rtrim( $rootpage, '/' ); //avoid double slashes
214 $title = Title
::newFromText( $rootpage, !is_null( $this->mTargetNamespace
) ?
$this->mTargetNamespace
: NS_MAIN
);
215 if( !$title ||
$title->isExternal() ) {
216 $status->fatal( 'import-rootpage-invalid' );
218 if( !MWNamespace
::hasSubpages( $title->getNamespace() ) ) {
221 $displayNSText = $title->getNamespace() == NS_MAIN
222 ?
wfMessage( 'blanknamespace' )->text()
223 : $wgContLang->getNsText( $title->getNamespace() );
224 $status->fatal( 'import-rootpage-nosubpage', $displayNSText );
226 // set namespace to 'all', so the namespace check in processTitle() can passed
227 $this->setTargetNamespace( null );
228 $this->mTargetRootPage
= $title->getPrefixedDBKey();
238 public function setImageBasePath( $dir ) {
239 $this->mImageBasePath
= $dir;
245 public function setImportUploads( $import ) {
246 $this->mImportUploads
= $import;
250 * Default per-revision callback, performs the import.
251 * @param $revision WikiRevision
254 public function importRevision( $revision ) {
255 $dbw = wfGetDB( DB_MASTER
);
256 return $dbw->deadlockLoop( array( $revision, 'importOldRevision' ) );
260 * Default per-revision callback, performs the import.
261 * @param $rev WikiRevision
264 public function importLogItem( $rev ) {
265 $dbw = wfGetDB( DB_MASTER
);
266 return $dbw->deadlockLoop( array( $rev, 'importLogItem' ) );
274 public function importUpload( $revision ) {
275 $dbw = wfGetDB( DB_MASTER
);
276 return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
280 * Mostly for hook use
288 public function finishImportPage( $title, $origTitle, $revCount, $sRevCount, $pageInfo ) {
289 $args = func_get_args();
290 return wfRunHooks( 'AfterImportPage', $args );
294 * Alternate per-revision callback, for debugging.
295 * @param $revision WikiRevision
297 public function debugRevisionHandler( &$revision ) {
298 $this->debug( "Got revision:" );
299 if( is_object( $revision->title
) ) {
300 $this->debug( "-- Title: " . $revision->title
->getPrefixedText() );
302 $this->debug( "-- Title: <invalid>" );
304 $this->debug( "-- User: " . $revision->user_text
);
305 $this->debug( "-- Timestamp: " . $revision->timestamp
);
306 $this->debug( "-- Comment: " . $revision->comment
);
307 $this->debug( "-- Text: " . $revision->text
);
311 * Notify the callback function when a new "<page>" is reached.
312 * @param $title Title
314 function pageCallback( $title ) {
315 if( isset( $this->mPageCallback
) ) {
316 call_user_func( $this->mPageCallback
, $title );
321 * Notify the callback function when a "</page>" is closed.
322 * @param $title Title
323 * @param $origTitle Title
324 * @param $revCount Integer
325 * @param $sucCount Int: number of revisions for which callback returned true
326 * @param $pageInfo Array: associative array of page information
328 private function pageOutCallback( $title, $origTitle, $revCount, $sucCount, $pageInfo ) {
329 if( isset( $this->mPageOutCallback
) ) {
330 $args = func_get_args();
331 call_user_func_array( $this->mPageOutCallback
, $args );
336 * Notify the callback function of a revision
337 * @param $revision WikiRevision object
340 private function revisionCallback( $revision ) {
341 if ( isset( $this->mRevisionCallback
) ) {
342 return call_user_func_array( $this->mRevisionCallback
,
343 array( $revision, $this ) );
350 * Notify the callback function of a new log item
351 * @param $revision WikiRevision object
354 private function logItemCallback( $revision ) {
355 if ( isset( $this->mLogItemCallback
) ) {
356 return call_user_func_array( $this->mLogItemCallback
,
357 array( $revision, $this ) );
364 * Shouldn't something like this be built-in to XMLReader?
365 * Fetches text contents of the current element, assuming
366 * no sub-elements or such scary things.
370 private function nodeContents() {
371 if( $this->reader
->isEmptyElement
) {
375 while( $this->reader
->read() ) {
376 switch( $this->reader
->nodeType
) {
377 case XmlReader
::TEXT
:
378 case XmlReader
::SIGNIFICANT_WHITESPACE
:
379 $buffer .= $this->reader
->value
;
381 case XmlReader
::END_ELEMENT
:
386 $this->reader
->close();
392 /** Left in for debugging */
393 private function dumpElement() {
394 static $lookup = null;
396 $xmlReaderConstants = array(
411 "SIGNIFICANT_WHITESPACE",
418 foreach( $xmlReaderConstants as $name ) {
419 $lookup[constant("XmlReader::$name")] = $name;
424 $lookup[$this->reader
->nodeType
],
431 * Primary entry point
434 public function doImport() {
435 $this->reader
->read();
437 if ( $this->reader
->name
!= 'mediawiki' ) {
438 throw new MWException( "Expected <mediawiki> tag, got ".
439 $this->reader
->name
);
441 $this->debug( "<mediawiki> tag is correct." );
443 $this->debug( "Starting primary dump processing loop." );
445 $keepReading = $this->reader
->read();
447 while ( $keepReading ) {
448 $tag = $this->reader
->name
;
449 $type = $this->reader
->nodeType
;
451 if ( !wfRunHooks( 'ImportHandleToplevelXMLTag', $this ) ) {
453 } elseif ( $tag == 'mediawiki' && $type == XmlReader
::END_ELEMENT
) {
455 } elseif ( $tag == 'siteinfo' ) {
456 $this->handleSiteInfo();
457 } elseif ( $tag == 'page' ) {
459 } elseif ( $tag == 'logitem' ) {
460 $this->handleLogItem();
461 } elseif ( $tag != '#text' ) {
462 $this->warn( "Unhandled top-level XML tag $tag" );
468 $keepReading = $this->reader
->next();
470 $this->debug( "Skip" );
472 $keepReading = $this->reader
->read();
481 * @throws MWException
483 private function handleSiteInfo() {
484 // Site info is useful, but not actually used for dump imports.
485 // Includes a quick short-circuit to save performance.
486 if ( ! $this->mSiteInfoCallback
) {
487 $this->reader
->next();
490 throw new MWException( "SiteInfo tag is not yet handled, do not set mSiteInfoCallback" );
493 private function handleLogItem() {
494 $this->debug( "Enter log item handler." );
497 // Fields that can just be stuffed in the pageInfo object
498 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
499 'logtitle', 'params' );
501 while ( $this->reader
->read() ) {
502 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
503 $this->reader
->name
== 'logitem') {
507 $tag = $this->reader
->name
;
509 if ( !wfRunHooks( 'ImportHandleLogItemXMLTag',
510 $this, $logInfo ) ) {
512 } elseif ( in_array( $tag, $normalFields ) ) {
513 $logInfo[$tag] = $this->nodeContents();
514 } elseif ( $tag == 'contributor' ) {
515 $logInfo['contributor'] = $this->handleContributor();
516 } elseif ( $tag != '#text' ) {
517 $this->warn( "Unhandled log-item XML tag $tag" );
521 $this->processLogItem( $logInfo );
528 private function processLogItem( $logInfo ) {
529 $revision = new WikiRevision
;
531 $revision->setID( $logInfo['id'] );
532 $revision->setType( $logInfo['type'] );
533 $revision->setAction( $logInfo['action'] );
534 $revision->setTimestamp( $logInfo['timestamp'] );
535 $revision->setParams( $logInfo['params'] );
536 $revision->setTitle( Title
::newFromText( $logInfo['logtitle'] ) );
537 $revision->setNoUpdates( $this->mNoUpdates
);
539 if ( isset( $logInfo['comment'] ) ) {
540 $revision->setComment( $logInfo['comment'] );
543 if ( isset( $logInfo['contributor']['ip'] ) ) {
544 $revision->setUserIP( $logInfo['contributor']['ip'] );
546 if ( isset( $logInfo['contributor']['username'] ) ) {
547 $revision->setUserName( $logInfo['contributor']['username'] );
550 return $this->logItemCallback( $revision );
553 private function handlePage() {
555 $this->debug( "Enter page handler." );
556 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
558 // Fields that can just be stuffed in the pageInfo object
559 $normalFields = array( 'title', 'id', 'redirect', 'restrictions' );
564 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
565 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
566 $this->reader
->name
== 'page') {
570 $tag = $this->reader
->name
;
573 // The title is invalid, bail out of this page
575 } elseif ( !wfRunHooks( 'ImportHandlePageXMLTag', array( $this,
578 } elseif ( in_array( $tag, $normalFields ) ) {
579 $pageInfo[$tag] = $this->nodeContents();
580 if ( $tag == 'title' ) {
581 $title = $this->processTitle( $pageInfo['title'] );
588 $this->pageCallback( $title );
589 list( $pageInfo['_title'], $origTitle ) = $title;
591 } elseif ( $tag == 'revision' ) {
592 $this->handleRevision( $pageInfo );
593 } elseif ( $tag == 'upload' ) {
594 $this->handleUpload( $pageInfo );
595 } elseif ( $tag != '#text' ) {
596 $this->warn( "Unhandled page XML tag $tag" );
601 $this->pageOutCallback( $pageInfo['_title'], $origTitle,
602 $pageInfo['revisionCount'],
603 $pageInfo['successfulRevisionCount'],
608 * @param $pageInfo array
610 private function handleRevision( &$pageInfo ) {
611 $this->debug( "Enter revision handler" );
612 $revisionInfo = array();
614 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'text' );
618 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
619 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
620 $this->reader
->name
== 'revision') {
624 $tag = $this->reader
->name
;
626 if ( !wfRunHooks( 'ImportHandleRevisionXMLTag', $this,
627 $pageInfo, $revisionInfo ) ) {
629 } elseif ( in_array( $tag, $normalFields ) ) {
630 $revisionInfo[$tag] = $this->nodeContents();
631 } elseif ( $tag == 'contributor' ) {
632 $revisionInfo['contributor'] = $this->handleContributor();
633 } elseif ( $tag != '#text' ) {
634 $this->warn( "Unhandled revision XML tag $tag" );
639 $pageInfo['revisionCount']++
;
640 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
641 $pageInfo['successfulRevisionCount']++
;
647 * @param $revisionInfo
650 private function processRevision( $pageInfo, $revisionInfo ) {
651 $revision = new WikiRevision
;
653 if( isset( $revisionInfo['id'] ) ) {
654 $revision->setID( $revisionInfo['id'] );
656 if ( isset( $revisionInfo['text'] ) ) {
657 $revision->setText( $revisionInfo['text'] );
659 $revision->setTitle( $pageInfo['_title'] );
661 if ( isset( $revisionInfo['timestamp'] ) ) {
662 $revision->setTimestamp( $revisionInfo['timestamp'] );
664 $revision->setTimestamp( wfTimestampNow() );
667 if ( isset( $revisionInfo['comment'] ) ) {
668 $revision->setComment( $revisionInfo['comment'] );
671 if ( isset( $revisionInfo['minor'] ) ) {
672 $revision->setMinor( true );
674 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
675 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
677 if ( isset( $revisionInfo['contributor']['username'] ) ) {
678 $revision->setUserName( $revisionInfo['contributor']['username'] );
680 $revision->setNoUpdates( $this->mNoUpdates
);
682 return $this->revisionCallback( $revision );
689 private function handleUpload( &$pageInfo ) {
690 $this->debug( "Enter upload handler" );
691 $uploadInfo = array();
693 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
694 'src', 'size', 'sha1base36', 'archivename', 'rel' );
698 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
699 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
700 $this->reader
->name
== 'upload') {
704 $tag = $this->reader
->name
;
706 if ( !wfRunHooks( 'ImportHandleUploadXMLTag', $this,
709 } elseif ( in_array( $tag, $normalFields ) ) {
710 $uploadInfo[$tag] = $this->nodeContents();
711 } elseif ( $tag == 'contributor' ) {
712 $uploadInfo['contributor'] = $this->handleContributor();
713 } elseif ( $tag == 'contents' ) {
714 $contents = $this->nodeContents();
715 $encoding = $this->reader
->getAttribute( 'encoding' );
716 if ( $encoding === 'base64' ) {
717 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
718 $uploadInfo['isTempSrc'] = true;
720 } elseif ( $tag != '#text' ) {
721 $this->warn( "Unhandled upload XML tag $tag" );
726 if ( $this->mImageBasePath
&& isset( $uploadInfo['rel'] ) ) {
727 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
728 if ( file_exists( $path ) ) {
729 $uploadInfo['fileSrc'] = $path;
730 $uploadInfo['isTempSrc'] = false;
734 if ( $this->mImportUploads
) {
735 return $this->processUpload( $pageInfo, $uploadInfo );
743 private function dumpTemp( $contents ) {
744 $filename = tempnam( wfTempDir(), 'importupload' );
745 file_put_contents( $filename, $contents );
754 private function processUpload( $pageInfo, $uploadInfo ) {
755 $revision = new WikiRevision
;
756 $text = isset( $uploadInfo['text'] ) ?
$uploadInfo['text'] : '';
758 $revision->setTitle( $pageInfo['_title'] );
759 $revision->setID( $pageInfo['id'] );
760 $revision->setTimestamp( $uploadInfo['timestamp'] );
761 $revision->setText( $text );
762 $revision->setFilename( $uploadInfo['filename'] );
763 if ( isset( $uploadInfo['archivename'] ) ) {
764 $revision->setArchiveName( $uploadInfo['archivename'] );
766 $revision->setSrc( $uploadInfo['src'] );
767 if ( isset( $uploadInfo['fileSrc'] ) ) {
768 $revision->setFileSrc( $uploadInfo['fileSrc'],
769 !empty( $uploadInfo['isTempSrc'] ) );
771 if ( isset( $uploadInfo['sha1base36'] ) ) {
772 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
774 $revision->setSize( intval( $uploadInfo['size'] ) );
775 $revision->setComment( $uploadInfo['comment'] );
777 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
778 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
780 if ( isset( $uploadInfo['contributor']['username'] ) ) {
781 $revision->setUserName( $uploadInfo['contributor']['username'] );
783 $revision->setNoUpdates( $this->mNoUpdates
);
785 return call_user_func( $this->mUploadCallback
, $revision );
791 private function handleContributor() {
792 $fields = array( 'id', 'ip', 'username' );
795 while ( $this->reader
->read() ) {
796 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
797 $this->reader
->name
== 'contributor') {
801 $tag = $this->reader
->name
;
803 if ( in_array( $tag, $fields ) ) {
804 $info[$tag] = $this->nodeContents();
812 * @param $text string
813 * @return Array or false
815 private function processTitle( $text ) {
816 global $wgCommandLineMode;
819 $origTitle = Title
::newFromText( $workTitle );
821 if( !is_null( $this->mTargetNamespace
) && !is_null( $origTitle ) ) {
822 # makeTitleSafe, because $origTitle can have a interwiki (different setting of interwiki map)
823 # and than dbKey can begin with a lowercase char
824 $title = Title
::makeTitleSafe( $this->mTargetNamespace
,
825 $origTitle->getDBkey() );
827 if( !is_null( $this->mTargetRootPage
) ) {
828 $workTitle = $this->mTargetRootPage
. '/' . $workTitle;
830 $title = Title
::newFromText( $workTitle );
833 if( is_null( $title ) ) {
834 # Invalid page title? Ignore the page
835 $this->notice( 'import-error-invalid', $workTitle );
837 } elseif( $title->isExternal() ) {
838 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
840 } elseif( !$title->canExist() ) {
841 $this->notice( 'import-error-special', $title->getPrefixedText() );
843 } elseif( !$title->userCan( 'edit' ) && !$wgCommandLineMode ) {
844 # Do not import if the importing wiki user cannot edit this page
845 $this->notice( 'import-error-edit', $title->getPrefixedText() );
847 } elseif( !$title->exists() && !$title->userCan( 'create' ) && !$wgCommandLineMode ) {
848 # Do not import if the importing wiki user cannot create this page
849 $this->notice( 'import-error-create', $title->getPrefixedText() );
853 return array( $title, $origTitle );
857 /** This is a horrible hack used to keep source compatibility */
858 class UploadSourceAdapter
{
859 static $sourceRegistrations = array();
869 static function registerSource( $source ) {
870 $id = wfRandomString();
872 self
::$sourceRegistrations[$id] = $source;
881 * @param $opened_path
884 function stream_open( $path, $mode, $options, &$opened_path ) {
885 $url = parse_url($path);
888 if ( !isset( self
::$sourceRegistrations[$id] ) ) {
892 $this->mSource
= self
::$sourceRegistrations[$id];
901 function stream_read( $count ) {
905 while ( !$leave && !$this->mSource
->atEnd() &&
906 strlen($this->mBuffer
) < $count ) {
907 $read = $this->mSource
->readChunk();
909 if ( !strlen($read) ) {
913 $this->mBuffer
.= $read;
916 if ( strlen($this->mBuffer
) ) {
917 $return = substr( $this->mBuffer
, 0, $count );
918 $this->mBuffer
= substr( $this->mBuffer
, $count );
921 $this->mPosition +
= strlen($return);
930 function stream_write( $data ) {
937 function stream_tell() {
938 return $this->mPosition
;
944 function stream_eof() {
945 return $this->mSource
->atEnd();
951 function url_stat() {
954 $result['dev'] = $result[0] = 0;
955 $result['ino'] = $result[1] = 0;
956 $result['mode'] = $result[2] = 0;
957 $result['nlink'] = $result[3] = 0;
958 $result['uid'] = $result[4] = 0;
959 $result['gid'] = $result[5] = 0;
960 $result['rdev'] = $result[6] = 0;
961 $result['size'] = $result[7] = 0;
962 $result['atime'] = $result[8] = 0;
963 $result['mtime'] = $result[9] = 0;
964 $result['ctime'] = $result[10] = 0;
965 $result['blksize'] = $result[11] = 0;
966 $result['blocks'] = $result[12] = 0;
972 class XMLReader2
extends XMLReader
{
975 * @return bool|string
977 function nodeContents() {
978 if( $this->isEmptyElement
) {
982 while( $this->read() ) {
983 switch( $this->nodeType
) {
984 case XmlReader
::TEXT
:
985 case XmlReader
::SIGNIFICANT_WHITESPACE
:
986 $buffer .= $this->value
;
988 case XmlReader
::END_ELEMENT
:
992 return $this->close();
997 * @todo document (e.g. one-sentence class description).
998 * @ingroup SpecialPage
1000 class WikiRevision
{
1001 var $importer = null;
1008 var $timestamp = "20010115000000";
1010 var $user_text = "";
1018 var $sha1base36 = false;
1019 var $isTemp = false;
1020 var $archiveName = '';
1022 private $mNoUpdates = false;
1026 * @throws MWException
1028 function setTitle( $title ) {
1029 if( is_object( $title ) ) {
1030 $this->title
= $title;
1031 } elseif( is_null( $title ) ) {
1032 throw new MWException( "WikiRevision given a null title in import. You may need to adjust \$wgLegalTitleChars." );
1034 throw new MWException( "WikiRevision given non-object title in import." );
1041 function setID( $id ) {
1048 function setTimestamp( $ts ) {
1049 # 2003-08-05T18:30:02Z
1050 $this->timestamp
= wfTimestamp( TS_MW
, $ts );
1056 function setUsername( $user ) {
1057 $this->user_text
= $user;
1063 function setUserIP( $ip ) {
1064 $this->user_text
= $ip;
1070 function setText( $text ) {
1071 $this->text
= $text;
1077 function setComment( $text ) {
1078 $this->comment
= $text;
1084 function setMinor( $minor ) {
1085 $this->minor
= (bool)$minor;
1091 function setSrc( $src ) {
1099 function setFileSrc( $src, $isTemp ) {
1100 $this->fileSrc
= $src;
1101 $this->fileIsTemp
= $isTemp;
1105 * @param $sha1base36
1107 function setSha1Base36( $sha1base36 ) {
1108 $this->sha1base36
= $sha1base36;
1114 function setFilename( $filename ) {
1115 $this->filename
= $filename;
1119 * @param $archiveName
1121 function setArchiveName( $archiveName ) {
1122 $this->archiveName
= $archiveName;
1128 function setSize( $size ) {
1129 $this->size
= intval( $size );
1135 function setType( $type ) {
1136 $this->type
= $type;
1142 function setAction( $action ) {
1143 $this->action
= $action;
1149 function setParams( $params ) {
1150 $this->params
= $params;
1156 public function setNoUpdates( $noupdates ) {
1157 $this->mNoUpdates
= $noupdates;
1163 function getTitle() {
1164 return $this->title
;
1177 function getTimestamp() {
1178 return $this->timestamp
;
1184 function getUser() {
1185 return $this->user_text
;
1191 function getText() {
1198 function getComment() {
1199 return $this->comment
;
1205 function getMinor() {
1206 return $this->minor
;
1217 * @return bool|String
1219 function getSha1() {
1220 if ( $this->sha1base36
) {
1221 return wfBaseConvert( $this->sha1base36
, 36, 16 );
1229 function getFileSrc() {
1230 return $this->fileSrc
;
1236 function isTempSrc() {
1237 return $this->isTemp
;
1243 function getFilename() {
1244 return $this->filename
;
1250 function getArchiveName() {
1251 return $this->archiveName
;
1257 function getSize() {
1264 function getType() {
1271 function getAction() {
1272 return $this->action
;
1278 function getParams() {
1279 return $this->params
;
1285 function importOldRevision() {
1286 $dbw = wfGetDB( DB_MASTER
);
1288 # Sneak a single revision into place
1289 $user = User
::newFromName( $this->getUser() );
1291 $userId = intval( $user->getId() );
1292 $userText = $user->getName();
1296 $userText = $this->getUser();
1297 $userObj = new User
;
1300 // avoid memory leak...?
1301 $linkCache = LinkCache
::singleton();
1302 $linkCache->clear();
1304 $page = WikiPage
::factory( $this->title
);
1305 if( !$page->exists() ) {
1306 # must create the page...
1307 $pageId = $page->insertOn( $dbw );
1309 $oldcountable = null;
1311 $pageId = $page->getId();
1314 $prior = $dbw->selectField( 'revision', '1',
1315 array( 'rev_page' => $pageId,
1316 'rev_timestamp' => $dbw->timestamp( $this->timestamp
),
1317 'rev_user_text' => $userText,
1318 'rev_comment' => $this->getComment() ),
1322 // @todo FIXME: This could fail slightly for multiple matches :P
1323 wfDebug( __METHOD__
. ": skipping existing revision for [[" .
1324 $this->title
->getPrefixedText() . "]], timestamp " . $this->timestamp
. "\n" );
1327 $oldcountable = $page->isCountable();
1330 # @todo FIXME: Use original rev_id optionally (better for backups)
1332 $revision = new Revision( array(
1334 'text' => $this->getText(),
1335 'comment' => $this->getComment(),
1337 'user_text' => $userText,
1338 'timestamp' => $this->timestamp
,
1339 'minor_edit' => $this->minor
,
1341 $revision->insertOn( $dbw );
1342 $changed = $page->updateIfNewerOn( $dbw, $revision );
1344 if ( $changed !== false && !$this->mNoUpdates
) {
1345 wfDebug( __METHOD__
. ": running updates\n" );
1346 $page->doEditUpdates( $revision, $userObj, array( 'created' => $created, 'oldcountable' => $oldcountable ) );
1355 function importLogItem() {
1356 $dbw = wfGetDB( DB_MASTER
);
1357 # @todo FIXME: This will not record autoblocks
1358 if( !$this->getTitle() ) {
1359 wfDebug( __METHOD__
. ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1360 $this->timestamp
. "\n" );
1363 # Check if it exists already
1364 // @todo FIXME: Use original log ID (better for backups)
1365 $prior = $dbw->selectField( 'logging', '1',
1366 array( 'log_type' => $this->getType(),
1367 'log_action' => $this->getAction(),
1368 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1369 'log_namespace' => $this->getTitle()->getNamespace(),
1370 'log_title' => $this->getTitle()->getDBkey(),
1371 'log_comment' => $this->getComment(),
1372 #'log_user_text' => $this->user_text,
1373 'log_params' => $this->params
),
1376 // @todo FIXME: This could fail slightly for multiple matches :P
1378 wfDebug( __METHOD__
. ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp " .
1379 $this->timestamp
. "\n" );
1382 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1384 'log_id' => $log_id,
1385 'log_type' => $this->type
,
1386 'log_action' => $this->action
,
1387 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1388 'log_user' => User
::idFromName( $this->user_text
),
1389 #'log_user_text' => $this->user_text,
1390 'log_namespace' => $this->getTitle()->getNamespace(),
1391 'log_title' => $this->getTitle()->getDBkey(),
1392 'log_comment' => $this->getComment(),
1393 'log_params' => $this->params
1395 $dbw->insert( 'logging', $data, __METHOD__
);
1401 function importUpload() {
1403 $archiveName = $this->getArchiveName();
1404 if ( $archiveName ) {
1405 wfDebug( __METHOD__
. "Importing archived file as $archiveName\n" );
1406 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1407 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1409 $file = wfLocalFile( $this->getTitle() );
1410 wfDebug( __METHOD__
. 'Importing new file as ' . $file->getName() . "\n" );
1411 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1412 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1413 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1414 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1415 wfDebug( __METHOD__
. "File already exists; importing as $archiveName\n" );
1419 wfDebug( __METHOD__
. ': Bad file for ' . $this->getTitle() . "\n" );
1423 # Get the file source or download if necessary
1424 $source = $this->getFileSrc();
1425 $flags = $this->isTempSrc() ? File
::DELETE_SOURCE
: 0;
1427 $source = $this->downloadSource();
1428 $flags |
= File
::DELETE_SOURCE
;
1431 wfDebug( __METHOD__
. ": Could not fetch remote file.\n" );
1434 $sha1 = $this->getSha1();
1435 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1436 if ( $flags & File
::DELETE_SOURCE
) {
1437 # Broken file; delete it if it is a temporary file
1440 wfDebug( __METHOD__
. ": Corrupt file $source.\n" );
1444 $user = User
::newFromName( $this->user_text
);
1446 # Do the actual upload
1447 if ( $archiveName ) {
1448 $status = $file->uploadOld( $source, $archiveName,
1449 $this->getTimestamp(), $this->getComment(), $user, $flags );
1451 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1452 $flags, false, $this->getTimestamp(), $user );
1455 if ( $status->isGood() ) {
1456 wfDebug( __METHOD__
. ": Succesful\n" );
1459 wfDebug( __METHOD__
. ': failed: ' . $status->getXml() . "\n" );
1465 * @return bool|string
1467 function downloadSource() {
1468 global $wgEnableUploads;
1469 if( !$wgEnableUploads ) {
1473 $tempo = tempnam( wfTempDir(), 'download' );
1474 $f = fopen( $tempo, 'wb' );
1476 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1481 $src = $this->getSrc();
1482 $data = Http
::get( $src );
1484 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1490 fwrite( $f, $data );
1499 * @todo document (e.g. one-sentence class description).
1500 * @ingroup SpecialPage
1502 class ImportStringSource
{
1503 function __construct( $string ) {
1504 $this->mString
= $string;
1505 $this->mRead
= false;
1512 return $this->mRead
;
1516 * @return bool|string
1518 function readChunk() {
1519 if( $this->atEnd() ) {
1522 $this->mRead
= true;
1523 return $this->mString
;
1528 * @todo document (e.g. one-sentence class description).
1529 * @ingroup SpecialPage
1531 class ImportStreamSource
{
1532 function __construct( $handle ) {
1533 $this->mHandle
= $handle;
1540 return feof( $this->mHandle
);
1546 function readChunk() {
1547 return fread( $this->mHandle
, 32768 );
1551 * @param $filename string
1554 static function newFromFile( $filename ) {
1555 wfSuppressWarnings();
1556 $file = fopen( $filename, 'rt' );
1557 wfRestoreWarnings();
1559 return Status
::newFatal( "importcantopen" );
1561 return Status
::newGood( new ImportStreamSource( $file ) );
1565 * @param $fieldname string
1568 static function newFromUpload( $fieldname = "xmlimport" ) {
1569 $upload =& $_FILES[$fieldname];
1571 if( !isset( $upload ) ||
!$upload['name'] ) {
1572 return Status
::newFatal( 'importnofile' );
1574 if( !empty( $upload['error'] ) ) {
1575 switch($upload['error']){
1576 case 1: # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1577 return Status
::newFatal( 'importuploaderrorsize' );
1578 case 2: # The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
1579 return Status
::newFatal( 'importuploaderrorsize' );
1580 case 3: # The uploaded file was only partially uploaded
1581 return Status
::newFatal( 'importuploaderrorpartial' );
1582 case 6: #Missing a temporary folder.
1583 return Status
::newFatal( 'importuploaderrortemp' );
1584 # case else: # Currently impossible
1588 $fname = $upload['tmp_name'];
1589 if( is_uploaded_file( $fname ) ) {
1590 return ImportStreamSource
::newFromFile( $fname );
1592 return Status
::newFatal( 'importnofile' );
1598 * @param $method string
1601 static function newFromURL( $url, $method = 'GET' ) {
1602 wfDebug( __METHOD__
. ": opening $url\n" );
1603 # Use the standard HTTP fetch function; it times out
1604 # quicker and sorts out user-agent problems which might
1605 # otherwise prevent importing from large sites, such
1606 # as the Wikimedia cluster, etc.
1607 $data = Http
::request( $method, $url, array( 'followRedirects' => true ) );
1608 if( $data !== false ) {
1610 fwrite( $file, $data );
1613 return Status
::newGood( new ImportStreamSource( $file ) );
1615 return Status
::newFatal( 'importcantopen' );
1622 * @param $history bool
1623 * @param $templates bool
1624 * @param $pageLinkDepth int
1627 public static function newFromInterwiki( $interwiki, $page, $history = false, $templates = false, $pageLinkDepth = 0 ) {
1629 return Status
::newFatal( 'import-noarticle' );
1631 $link = Title
::newFromText( "$interwiki:Special:Export/$page" );
1632 if( is_null( $link ) ||
$link->getInterwiki() == '' ) {
1633 return Status
::newFatal( 'importbadinterwiki' );
1636 if ( $history ) $params['history'] = 1;
1637 if ( $templates ) $params['templates'] = 1;
1638 if ( $pageLinkDepth ) $params['pagelink-depth'] = $pageLinkDepth;
1639 $url = $link->getFullUrl( $params );
1640 # For interwikis, use POST to avoid redirects.
1641 return ImportStreamSource
::newFromURL( $url, "POST" );