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, $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 );
205 public function setImageBasePath( $dir ) {
206 $this->mImageBasePath
= $dir;
212 public function setImportUploads( $import ) {
213 $this->mImportUploads
= $import;
217 * Default per-revision callback, performs the import.
218 * @param $revision WikiRevision
221 public function importRevision( $revision ) {
222 $dbw = wfGetDB( DB_MASTER
);
223 return $dbw->deadlockLoop( array( $revision, 'importOldRevision' ) );
227 * Default per-revision callback, performs the import.
228 * @param $rev WikiRevision
231 public function importLogItem( $rev ) {
232 $dbw = wfGetDB( DB_MASTER
);
233 return $dbw->deadlockLoop( array( $rev, 'importLogItem' ) );
241 public function importUpload( $revision ) {
242 $dbw = wfGetDB( DB_MASTER
);
243 return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
247 * Mostly for hook use
255 public function finishImportPage( $title, $origTitle, $revCount, $sRevCount, $pageInfo ) {
256 $args = func_get_args();
257 return wfRunHooks( 'AfterImportPage', $args );
261 * Alternate per-revision callback, for debugging.
262 * @param $revision WikiRevision
264 public function debugRevisionHandler( &$revision ) {
265 $this->debug( "Got revision:" );
266 if( is_object( $revision->title
) ) {
267 $this->debug( "-- Title: " . $revision->title
->getPrefixedText() );
269 $this->debug( "-- Title: <invalid>" );
271 $this->debug( "-- User: " . $revision->user_text
);
272 $this->debug( "-- Timestamp: " . $revision->timestamp
);
273 $this->debug( "-- Comment: " . $revision->comment
);
274 $this->debug( "-- Text: " . $revision->text
);
278 * Notify the callback function when a new <page> is reached.
279 * @param $title Title
281 function pageCallback( $title ) {
282 if( isset( $this->mPageCallback
) ) {
283 call_user_func( $this->mPageCallback
, $title );
288 * Notify the callback function when a </page> is closed.
289 * @param $title Title
290 * @param $origTitle Title
291 * @param $revCount Integer
292 * @param $sucCount Int: number of revisions for which callback returned true
293 * @param $pageInfo Array: associative array of page information
295 private function pageOutCallback( $title, $origTitle, $revCount, $sucCount, $pageInfo ) {
296 if( isset( $this->mPageOutCallback
) ) {
297 $args = func_get_args();
298 call_user_func_array( $this->mPageOutCallback
, $args );
303 * Notify the callback function of a revision
304 * @param $revision WikiRevision object
307 private function revisionCallback( $revision ) {
308 if ( isset( $this->mRevisionCallback
) ) {
309 return call_user_func_array( $this->mRevisionCallback
,
310 array( $revision, $this ) );
317 * Notify the callback function of a new log item
318 * @param $revision WikiRevision object
321 private function logItemCallback( $revision ) {
322 if ( isset( $this->mLogItemCallback
) ) {
323 return call_user_func_array( $this->mLogItemCallback
,
324 array( $revision, $this ) );
331 * Shouldn't something like this be built-in to XMLReader?
332 * Fetches text contents of the current element, assuming
333 * no sub-elements or such scary things.
337 private function nodeContents() {
338 if( $this->reader
->isEmptyElement
) {
342 while( $this->reader
->read() ) {
343 switch( $this->reader
->nodeType
) {
344 case XmlReader
::TEXT
:
345 case XmlReader
::SIGNIFICANT_WHITESPACE
:
346 $buffer .= $this->reader
->value
;
348 case XmlReader
::END_ELEMENT
:
353 $this->reader
->close();
359 /** Left in for debugging */
360 private function dumpElement() {
361 static $lookup = null;
363 $xmlReaderConstants = array(
378 "SIGNIFICANT_WHITESPACE",
385 foreach( $xmlReaderConstants as $name ) {
386 $lookup[constant("XmlReader::$name")] = $name;
391 $lookup[$this->reader
->nodeType
],
398 * Primary entry point
401 public function doImport() {
402 $this->reader
->read();
404 if ( $this->reader
->name
!= 'mediawiki' ) {
405 throw new MWException( "Expected <mediawiki> tag, got ".
406 $this->reader
->name
);
408 $this->debug( "<mediawiki> tag is correct." );
410 $this->debug( "Starting primary dump processing loop." );
412 $keepReading = $this->reader
->read();
414 while ( $keepReading ) {
415 $tag = $this->reader
->name
;
416 $type = $this->reader
->nodeType
;
418 if ( !wfRunHooks( 'ImportHandleToplevelXMLTag', $this ) ) {
420 } elseif ( $tag == 'mediawiki' && $type == XmlReader
::END_ELEMENT
) {
422 } elseif ( $tag == 'siteinfo' ) {
423 $this->handleSiteInfo();
424 } elseif ( $tag == 'page' ) {
426 } elseif ( $tag == 'logitem' ) {
427 $this->handleLogItem();
428 } elseif ( $tag != '#text' ) {
429 $this->warn( "Unhandled top-level XML tag $tag" );
435 $keepReading = $this->reader
->next();
437 $this->debug( "Skip" );
439 $keepReading = $this->reader
->read();
448 * @throws MWException
450 private function handleSiteInfo() {
451 // Site info is useful, but not actually used for dump imports.
452 // Includes a quick short-circuit to save performance.
453 if ( ! $this->mSiteInfoCallback
) {
454 $this->reader
->next();
457 throw new MWException( "SiteInfo tag is not yet handled, do not set mSiteInfoCallback" );
460 private function handleLogItem() {
461 $this->debug( "Enter log item handler." );
464 // Fields that can just be stuffed in the pageInfo object
465 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
466 'logtitle', 'params' );
468 while ( $this->reader
->read() ) {
469 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
470 $this->reader
->name
== 'logitem') {
474 $tag = $this->reader
->name
;
476 if ( !wfRunHooks( 'ImportHandleLogItemXMLTag',
477 $this, $logInfo ) ) {
479 } elseif ( in_array( $tag, $normalFields ) ) {
480 $logInfo[$tag] = $this->nodeContents();
481 } elseif ( $tag == 'contributor' ) {
482 $logInfo['contributor'] = $this->handleContributor();
483 } elseif ( $tag != '#text' ) {
484 $this->warn( "Unhandled log-item XML tag $tag" );
488 $this->processLogItem( $logInfo );
495 private function processLogItem( $logInfo ) {
496 $revision = new WikiRevision
;
498 $revision->setID( $logInfo['id'] );
499 $revision->setType( $logInfo['type'] );
500 $revision->setAction( $logInfo['action'] );
501 $revision->setTimestamp( $logInfo['timestamp'] );
502 $revision->setParams( $logInfo['params'] );
503 $revision->setTitle( Title
::newFromText( $logInfo['logtitle'] ) );
504 $revision->setNoUpdates( $this->mNoUpdates
);
506 if ( isset( $logInfo['comment'] ) ) {
507 $revision->setComment( $logInfo['comment'] );
510 if ( isset( $logInfo['contributor']['ip'] ) ) {
511 $revision->setUserIP( $logInfo['contributor']['ip'] );
513 if ( isset( $logInfo['contributor']['username'] ) ) {
514 $revision->setUserName( $logInfo['contributor']['username'] );
517 return $this->logItemCallback( $revision );
520 private function handlePage() {
522 $this->debug( "Enter page handler." );
523 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
525 // Fields that can just be stuffed in the pageInfo object
526 $normalFields = array( 'title', 'id', 'redirect', 'restrictions' );
531 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
532 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
533 $this->reader
->name
== 'page') {
537 $tag = $this->reader
->name
;
540 // The title is invalid, bail out of this page
542 } elseif ( !wfRunHooks( 'ImportHandlePageXMLTag', array( $this,
545 } elseif ( in_array( $tag, $normalFields ) ) {
546 $pageInfo[$tag] = $this->nodeContents();
547 if ( $tag == 'title' ) {
548 $title = $this->processTitle( $pageInfo['title'] );
555 $this->pageCallback( $title );
556 list( $pageInfo['_title'], $origTitle ) = $title;
558 } elseif ( $tag == 'revision' ) {
559 $this->handleRevision( $pageInfo );
560 } elseif ( $tag == 'upload' ) {
561 $this->handleUpload( $pageInfo );
562 } elseif ( $tag != '#text' ) {
563 $this->warn( "Unhandled page XML tag $tag" );
568 $this->pageOutCallback( $pageInfo['_title'], $origTitle,
569 $pageInfo['revisionCount'],
570 $pageInfo['successfulRevisionCount'],
575 * @param $pageInfo array
577 private function handleRevision( &$pageInfo ) {
578 $this->debug( "Enter revision handler" );
579 $revisionInfo = array();
581 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'text' );
585 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
586 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
587 $this->reader
->name
== 'revision') {
591 $tag = $this->reader
->name
;
593 if ( !wfRunHooks( 'ImportHandleRevisionXMLTag', $this,
594 $pageInfo, $revisionInfo ) ) {
596 } elseif ( in_array( $tag, $normalFields ) ) {
597 $revisionInfo[$tag] = $this->nodeContents();
598 } elseif ( $tag == 'contributor' ) {
599 $revisionInfo['contributor'] = $this->handleContributor();
600 } elseif ( $tag != '#text' ) {
601 $this->warn( "Unhandled revision XML tag $tag" );
606 $pageInfo['revisionCount']++
;
607 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
608 $pageInfo['successfulRevisionCount']++
;
614 * @param $revisionInfo
617 private function processRevision( $pageInfo, $revisionInfo ) {
618 $revision = new WikiRevision
;
620 if( isset( $revisionInfo['id'] ) ) {
621 $revision->setID( $revisionInfo['id'] );
623 if ( isset( $revisionInfo['text'] ) ) {
624 $revision->setText( $revisionInfo['text'] );
626 $revision->setTitle( $pageInfo['_title'] );
628 if ( isset( $revisionInfo['timestamp'] ) ) {
629 $revision->setTimestamp( $revisionInfo['timestamp'] );
631 $revision->setTimestamp( wfTimestampNow() );
634 if ( isset( $revisionInfo['comment'] ) ) {
635 $revision->setComment( $revisionInfo['comment'] );
638 if ( isset( $revisionInfo['minor'] ) ) {
639 $revision->setMinor( true );
641 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
642 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
644 if ( isset( $revisionInfo['contributor']['username'] ) ) {
645 $revision->setUserName( $revisionInfo['contributor']['username'] );
647 $revision->setNoUpdates( $this->mNoUpdates
);
649 return $this->revisionCallback( $revision );
656 private function handleUpload( &$pageInfo ) {
657 $this->debug( "Enter upload handler" );
658 $uploadInfo = array();
660 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
661 'src', 'size', 'sha1base36', 'archivename', 'rel' );
665 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
666 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
667 $this->reader
->name
== 'upload') {
671 $tag = $this->reader
->name
;
673 if ( !wfRunHooks( 'ImportHandleUploadXMLTag', $this,
676 } elseif ( in_array( $tag, $normalFields ) ) {
677 $uploadInfo[$tag] = $this->nodeContents();
678 } elseif ( $tag == 'contributor' ) {
679 $uploadInfo['contributor'] = $this->handleContributor();
680 } elseif ( $tag == 'contents' ) {
681 $contents = $this->nodeContents();
682 $encoding = $this->reader
->getAttribute( 'encoding' );
683 if ( $encoding === 'base64' ) {
684 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
685 $uploadInfo['isTempSrc'] = true;
687 } elseif ( $tag != '#text' ) {
688 $this->warn( "Unhandled upload XML tag $tag" );
693 if ( $this->mImageBasePath
&& isset( $uploadInfo['rel'] ) ) {
694 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
695 if ( file_exists( $path ) ) {
696 $uploadInfo['fileSrc'] = $path;
697 $uploadInfo['isTempSrc'] = false;
701 if ( $this->mImportUploads
) {
702 return $this->processUpload( $pageInfo, $uploadInfo );
710 private function dumpTemp( $contents ) {
711 $filename = tempnam( wfTempDir(), 'importupload' );
712 file_put_contents( $filename, $contents );
721 private function processUpload( $pageInfo, $uploadInfo ) {
722 $revision = new WikiRevision
;
723 $text = isset( $uploadInfo['text'] ) ?
$uploadInfo['text'] : '';
725 $revision->setTitle( $pageInfo['_title'] );
726 $revision->setID( $pageInfo['id'] );
727 $revision->setTimestamp( $uploadInfo['timestamp'] );
728 $revision->setText( $text );
729 $revision->setFilename( $uploadInfo['filename'] );
730 if ( isset( $uploadInfo['archivename'] ) ) {
731 $revision->setArchiveName( $uploadInfo['archivename'] );
733 $revision->setSrc( $uploadInfo['src'] );
734 if ( isset( $uploadInfo['fileSrc'] ) ) {
735 $revision->setFileSrc( $uploadInfo['fileSrc'],
736 !empty( $uploadInfo['isTempSrc'] ) );
738 if ( isset( $uploadInfo['sha1base36'] ) ) {
739 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
741 $revision->setSize( intval( $uploadInfo['size'] ) );
742 $revision->setComment( $uploadInfo['comment'] );
744 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
745 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
747 if ( isset( $uploadInfo['contributor']['username'] ) ) {
748 $revision->setUserName( $uploadInfo['contributor']['username'] );
750 $revision->setNoUpdates( $this->mNoUpdates
);
752 return call_user_func( $this->mUploadCallback
, $revision );
758 private function handleContributor() {
759 $fields = array( 'id', 'ip', 'username' );
762 while ( $this->reader
->read() ) {
763 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
764 $this->reader
->name
== 'contributor') {
768 $tag = $this->reader
->name
;
770 if ( in_array( $tag, $fields ) ) {
771 $info[$tag] = $this->nodeContents();
779 * @param $text string
780 * @return Array or false
782 private function processTitle( $text ) {
783 global $wgCommandLineMode;
786 $origTitle = Title
::newFromText( $workTitle );
788 if( !is_null( $this->mTargetNamespace
) && !is_null( $origTitle ) ) {
789 $title = Title
::makeTitle( $this->mTargetNamespace
,
790 $origTitle->getDBkey() );
792 $title = Title
::newFromText( $workTitle );
795 if( is_null( $title ) ) {
796 # Invalid page title? Ignore the page
797 $this->notice( 'import-error-invalid', $workTitle );
799 } elseif( $title->isExternal() ) {
800 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
802 } elseif( !$title->canExist() ) {
803 $this->notice( 'import-error-special', $title->getPrefixedText() );
805 } elseif( !$title->userCan( 'edit' ) && !$wgCommandLineMode ) {
806 # Do not import if the importing wiki user cannot edit this page
807 $this->notice( 'import-error-edit', $title->getPrefixedText() );
809 } elseif( !$title->exists() && !$title->userCan( 'create' ) && !$wgCommandLineMode ) {
810 # Do not import if the importing wiki user cannot create this page
811 $this->notice( 'import-error-create', $title->getPrefixedText() );
815 return array( $title, $origTitle );
819 /** This is a horrible hack used to keep source compatibility */
820 class UploadSourceAdapter
{
821 static $sourceRegistrations = array();
831 static function registerSource( $source ) {
832 $id = wfRandomString();
834 self
::$sourceRegistrations[$id] = $source;
843 * @param $opened_path
846 function stream_open( $path, $mode, $options, &$opened_path ) {
847 $url = parse_url($path);
850 if ( !isset( self
::$sourceRegistrations[$id] ) ) {
854 $this->mSource
= self
::$sourceRegistrations[$id];
863 function stream_read( $count ) {
867 while ( !$leave && !$this->mSource
->atEnd() &&
868 strlen($this->mBuffer
) < $count ) {
869 $read = $this->mSource
->readChunk();
871 if ( !strlen($read) ) {
875 $this->mBuffer
.= $read;
878 if ( strlen($this->mBuffer
) ) {
879 $return = substr( $this->mBuffer
, 0, $count );
880 $this->mBuffer
= substr( $this->mBuffer
, $count );
883 $this->mPosition +
= strlen($return);
892 function stream_write( $data ) {
899 function stream_tell() {
900 return $this->mPosition
;
906 function stream_eof() {
907 return $this->mSource
->atEnd();
913 function url_stat() {
916 $result['dev'] = $result[0] = 0;
917 $result['ino'] = $result[1] = 0;
918 $result['mode'] = $result[2] = 0;
919 $result['nlink'] = $result[3] = 0;
920 $result['uid'] = $result[4] = 0;
921 $result['gid'] = $result[5] = 0;
922 $result['rdev'] = $result[6] = 0;
923 $result['size'] = $result[7] = 0;
924 $result['atime'] = $result[8] = 0;
925 $result['mtime'] = $result[9] = 0;
926 $result['ctime'] = $result[10] = 0;
927 $result['blksize'] = $result[11] = 0;
928 $result['blocks'] = $result[12] = 0;
934 class XMLReader2
extends XMLReader
{
937 * @return bool|string
939 function nodeContents() {
940 if( $this->isEmptyElement
) {
944 while( $this->read() ) {
945 switch( $this->nodeType
) {
946 case XmlReader
::TEXT
:
947 case XmlReader
::SIGNIFICANT_WHITESPACE
:
948 $buffer .= $this->value
;
950 case XmlReader
::END_ELEMENT
:
954 return $this->close();
959 * @todo document (e.g. one-sentence class description).
960 * @ingroup SpecialPage
963 var $importer = null;
970 var $timestamp = "20010115000000";
980 var $sha1base36 = false;
982 var $archiveName = '';
984 private $mNoUpdates = false;
988 * @throws MWException
990 function setTitle( $title ) {
991 if( is_object( $title ) ) {
992 $this->title
= $title;
993 } elseif( is_null( $title ) ) {
994 throw new MWException( "WikiRevision given a null title in import. You may need to adjust \$wgLegalTitleChars." );
996 throw new MWException( "WikiRevision given non-object title in import." );
1003 function setID( $id ) {
1010 function setTimestamp( $ts ) {
1011 # 2003-08-05T18:30:02Z
1012 $this->timestamp
= wfTimestamp( TS_MW
, $ts );
1018 function setUsername( $user ) {
1019 $this->user_text
= $user;
1025 function setUserIP( $ip ) {
1026 $this->user_text
= $ip;
1032 function setText( $text ) {
1033 $this->text
= $text;
1039 function setComment( $text ) {
1040 $this->comment
= $text;
1046 function setMinor( $minor ) {
1047 $this->minor
= (bool)$minor;
1053 function setSrc( $src ) {
1061 function setFileSrc( $src, $isTemp ) {
1062 $this->fileSrc
= $src;
1063 $this->fileIsTemp
= $isTemp;
1067 * @param $sha1base36
1069 function setSha1Base36( $sha1base36 ) {
1070 $this->sha1base36
= $sha1base36;
1076 function setFilename( $filename ) {
1077 $this->filename
= $filename;
1081 * @param $archiveName
1083 function setArchiveName( $archiveName ) {
1084 $this->archiveName
= $archiveName;
1090 function setSize( $size ) {
1091 $this->size
= intval( $size );
1097 function setType( $type ) {
1098 $this->type
= $type;
1104 function setAction( $action ) {
1105 $this->action
= $action;
1111 function setParams( $params ) {
1112 $this->params
= $params;
1118 public function setNoUpdates( $noupdates ) {
1119 $this->mNoUpdates
= $noupdates;
1125 function getTitle() {
1126 return $this->title
;
1139 function getTimestamp() {
1140 return $this->timestamp
;
1146 function getUser() {
1147 return $this->user_text
;
1153 function getText() {
1160 function getComment() {
1161 return $this->comment
;
1167 function getMinor() {
1168 return $this->minor
;
1179 * @return bool|String
1181 function getSha1() {
1182 if ( $this->sha1base36
) {
1183 return wfBaseConvert( $this->sha1base36
, 36, 16 );
1191 function getFileSrc() {
1192 return $this->fileSrc
;
1198 function isTempSrc() {
1199 return $this->isTemp
;
1205 function getFilename() {
1206 return $this->filename
;
1212 function getArchiveName() {
1213 return $this->archiveName
;
1219 function getSize() {
1226 function getType() {
1233 function getAction() {
1234 return $this->action
;
1240 function getParams() {
1241 return $this->params
;
1247 function importOldRevision() {
1248 $dbw = wfGetDB( DB_MASTER
);
1250 # Sneak a single revision into place
1251 $user = User
::newFromName( $this->getUser() );
1253 $userId = intval( $user->getId() );
1254 $userText = $user->getName();
1258 $userText = $this->getUser();
1259 $userObj = new User
;
1262 // avoid memory leak...?
1263 $linkCache = LinkCache
::singleton();
1264 $linkCache->clear();
1266 $page = WikiPage
::factory( $this->title
);
1267 if( !$page->exists() ) {
1268 # must create the page...
1269 $pageId = $page->insertOn( $dbw );
1271 $oldcountable = null;
1273 $pageId = $page->getId();
1276 $prior = $dbw->selectField( 'revision', '1',
1277 array( 'rev_page' => $pageId,
1278 'rev_timestamp' => $dbw->timestamp( $this->timestamp
),
1279 'rev_user_text' => $userText,
1280 'rev_comment' => $this->getComment() ),
1284 // @todo FIXME: This could fail slightly for multiple matches :P
1285 wfDebug( __METHOD__
. ": skipping existing revision for [[" .
1286 $this->title
->getPrefixedText() . "]], timestamp " . $this->timestamp
. "\n" );
1289 $oldcountable = $page->isCountable();
1292 # @todo FIXME: Use original rev_id optionally (better for backups)
1294 $revision = new Revision( array(
1296 'text' => $this->getText(),
1297 'comment' => $this->getComment(),
1299 'user_text' => $userText,
1300 'timestamp' => $this->timestamp
,
1301 'minor_edit' => $this->minor
,
1303 $revision->insertOn( $dbw );
1304 $changed = $page->updateIfNewerOn( $dbw, $revision );
1306 if ( $changed !== false && !$this->mNoUpdates
) {
1307 wfDebug( __METHOD__
. ": running updates\n" );
1308 $page->doEditUpdates( $revision, $userObj, array( 'created' => $created, 'oldcountable' => $oldcountable ) );
1317 function importLogItem() {
1318 $dbw = wfGetDB( DB_MASTER
);
1319 # @todo FIXME: This will not record autoblocks
1320 if( !$this->getTitle() ) {
1321 wfDebug( __METHOD__
. ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1322 $this->timestamp
. "\n" );
1325 # Check if it exists already
1326 // @todo FIXME: Use original log ID (better for backups)
1327 $prior = $dbw->selectField( 'logging', '1',
1328 array( 'log_type' => $this->getType(),
1329 'log_action' => $this->getAction(),
1330 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1331 'log_namespace' => $this->getTitle()->getNamespace(),
1332 'log_title' => $this->getTitle()->getDBkey(),
1333 'log_comment' => $this->getComment(),
1334 #'log_user_text' => $this->user_text,
1335 'log_params' => $this->params
),
1338 // @todo FIXME: This could fail slightly for multiple matches :P
1340 wfDebug( __METHOD__
. ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp " .
1341 $this->timestamp
. "\n" );
1344 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1346 'log_id' => $log_id,
1347 'log_type' => $this->type
,
1348 'log_action' => $this->action
,
1349 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1350 'log_user' => User
::idFromName( $this->user_text
),
1351 #'log_user_text' => $this->user_text,
1352 'log_namespace' => $this->getTitle()->getNamespace(),
1353 'log_title' => $this->getTitle()->getDBkey(),
1354 'log_comment' => $this->getComment(),
1355 'log_params' => $this->params
1357 $dbw->insert( 'logging', $data, __METHOD__
);
1363 function importUpload() {
1365 $archiveName = $this->getArchiveName();
1366 if ( $archiveName ) {
1367 wfDebug( __METHOD__
. "Importing archived file as $archiveName\n" );
1368 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1369 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1371 $file = wfLocalFile( $this->getTitle() );
1372 wfDebug( __METHOD__
. 'Importing new file as ' . $file->getName() . "\n" );
1373 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1374 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1375 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1376 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1377 wfDebug( __METHOD__
. "File already exists; importing as $archiveName\n" );
1381 wfDebug( __METHOD__
. ': Bad file for ' . $this->getTitle() . "\n" );
1385 # Get the file source or download if necessary
1386 $source = $this->getFileSrc();
1387 $flags = $this->isTempSrc() ? File
::DELETE_SOURCE
: 0;
1389 $source = $this->downloadSource();
1390 $flags |
= File
::DELETE_SOURCE
;
1393 wfDebug( __METHOD__
. ": Could not fetch remote file.\n" );
1396 $sha1 = $this->getSha1();
1397 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1398 if ( $flags & File
::DELETE_SOURCE
) {
1399 # Broken file; delete it if it is a temporary file
1402 wfDebug( __METHOD__
. ": Corrupt file $source.\n" );
1406 $user = User
::newFromName( $this->user_text
);
1408 # Do the actual upload
1409 if ( $archiveName ) {
1410 $status = $file->uploadOld( $source, $archiveName,
1411 $this->getTimestamp(), $this->getComment(), $user, $flags );
1413 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1414 $flags, false, $this->getTimestamp(), $user );
1417 if ( $status->isGood() ) {
1418 wfDebug( __METHOD__
. ": Succesful\n" );
1421 wfDebug( __METHOD__
. ': failed: ' . $status->getXml() . "\n" );
1427 * @return bool|string
1429 function downloadSource() {
1430 global $wgEnableUploads;
1431 if( !$wgEnableUploads ) {
1435 $tempo = tempnam( wfTempDir(), 'download' );
1436 $f = fopen( $tempo, 'wb' );
1438 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1443 $src = $this->getSrc();
1444 $data = Http
::get( $src );
1446 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1452 fwrite( $f, $data );
1461 * @todo document (e.g. one-sentence class description).
1462 * @ingroup SpecialPage
1464 class ImportStringSource
{
1465 function __construct( $string ) {
1466 $this->mString
= $string;
1467 $this->mRead
= false;
1474 return $this->mRead
;
1478 * @return bool|string
1480 function readChunk() {
1481 if( $this->atEnd() ) {
1484 $this->mRead
= true;
1485 return $this->mString
;
1490 * @todo document (e.g. one-sentence class description).
1491 * @ingroup SpecialPage
1493 class ImportStreamSource
{
1494 function __construct( $handle ) {
1495 $this->mHandle
= $handle;
1502 return feof( $this->mHandle
);
1508 function readChunk() {
1509 return fread( $this->mHandle
, 32768 );
1513 * @param $filename string
1516 static function newFromFile( $filename ) {
1517 wfSuppressWarnings();
1518 $file = fopen( $filename, 'rt' );
1519 wfRestoreWarnings();
1521 return Status
::newFatal( "importcantopen" );
1523 return Status
::newGood( new ImportStreamSource( $file ) );
1527 * @param $fieldname string
1530 static function newFromUpload( $fieldname = "xmlimport" ) {
1531 $upload =& $_FILES[$fieldname];
1533 if( !isset( $upload ) ||
!$upload['name'] ) {
1534 return Status
::newFatal( 'importnofile' );
1536 if( !empty( $upload['error'] ) ) {
1537 switch($upload['error']){
1538 case 1: # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1539 return Status
::newFatal( 'importuploaderrorsize' );
1540 case 2: # The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
1541 return Status
::newFatal( 'importuploaderrorsize' );
1542 case 3: # The uploaded file was only partially uploaded
1543 return Status
::newFatal( 'importuploaderrorpartial' );
1544 case 6: #Missing a temporary folder.
1545 return Status
::newFatal( 'importuploaderrortemp' );
1546 # case else: # Currently impossible
1550 $fname = $upload['tmp_name'];
1551 if( is_uploaded_file( $fname ) ) {
1552 return ImportStreamSource
::newFromFile( $fname );
1554 return Status
::newFatal( 'importnofile' );
1560 * @param $method string
1563 static function newFromURL( $url, $method = 'GET' ) {
1564 wfDebug( __METHOD__
. ": opening $url\n" );
1565 # Use the standard HTTP fetch function; it times out
1566 # quicker and sorts out user-agent problems which might
1567 # otherwise prevent importing from large sites, such
1568 # as the Wikimedia cluster, etc.
1569 $data = Http
::request( $method, $url, array( 'followRedirects' => true ) );
1570 if( $data !== false ) {
1572 fwrite( $file, $data );
1575 return Status
::newGood( new ImportStreamSource( $file ) );
1577 return Status
::newFatal( 'importcantopen' );
1584 * @param $history bool
1585 * @param $templates bool
1586 * @param $pageLinkDepth int
1589 public static function newFromInterwiki( $interwiki, $page, $history = false, $templates = false, $pageLinkDepth = 0 ) {
1591 return Status
::newFatal( 'import-noarticle' );
1593 $link = Title
::newFromText( "$interwiki:Special:Export/$page" );
1594 if( is_null( $link ) ||
$link->getInterwiki() == '' ) {
1595 return Status
::newFatal( 'importbadinterwiki' );
1598 if ( $history ) $params['history'] = 1;
1599 if ( $templates ) $params['templates'] = 1;
1600 if ( $pageLinkDepth ) $params['pagelink-depth'] = $pageLinkDepth;
1601 $url = $link->getFullUrl( $params );
1602 # For interwikis, use POST to avoid redirects.
1603 return ImportStreamSource
::newFromURL( $url, "POST" );