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
400 public function doImport() {
401 $this->reader
->read();
403 if ( $this->reader
->name
!= 'mediawiki' ) {
404 throw new MWException( "Expected <mediawiki> tag, got ".
405 $this->reader
->name
);
407 $this->debug( "<mediawiki> tag is correct." );
409 $this->debug( "Starting primary dump processing loop." );
411 $keepReading = $this->reader
->read();
413 while ( $keepReading ) {
414 $tag = $this->reader
->name
;
415 $type = $this->reader
->nodeType
;
417 if ( !wfRunHooks( 'ImportHandleToplevelXMLTag', $this ) ) {
419 } elseif ( $tag == 'mediawiki' && $type == XmlReader
::END_ELEMENT
) {
421 } elseif ( $tag == 'siteinfo' ) {
422 $this->handleSiteInfo();
423 } elseif ( $tag == 'page' ) {
425 } elseif ( $tag == 'logitem' ) {
426 $this->handleLogItem();
427 } elseif ( $tag != '#text' ) {
428 $this->warn( "Unhandled top-level XML tag $tag" );
434 $keepReading = $this->reader
->next();
436 $this->debug( "Skip" );
438 $keepReading = $this->reader
->read();
447 * @throws MWException
449 private function handleSiteInfo() {
450 // Site info is useful, but not actually used for dump imports.
451 // Includes a quick short-circuit to save performance.
452 if ( ! $this->mSiteInfoCallback
) {
453 $this->reader
->next();
456 throw new MWException( "SiteInfo tag is not yet handled, do not set mSiteInfoCallback" );
459 private function handleLogItem() {
460 $this->debug( "Enter log item handler." );
463 // Fields that can just be stuffed in the pageInfo object
464 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
465 'logtitle', 'params' );
467 while ( $this->reader
->read() ) {
468 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
469 $this->reader
->name
== 'logitem') {
473 $tag = $this->reader
->name
;
475 if ( !wfRunHooks( 'ImportHandleLogItemXMLTag',
476 $this, $logInfo ) ) {
478 } elseif ( in_array( $tag, $normalFields ) ) {
479 $logInfo[$tag] = $this->nodeContents();
480 } elseif ( $tag == 'contributor' ) {
481 $logInfo['contributor'] = $this->handleContributor();
482 } elseif ( $tag != '#text' ) {
483 $this->warn( "Unhandled log-item XML tag $tag" );
487 $this->processLogItem( $logInfo );
494 private function processLogItem( $logInfo ) {
495 $revision = new WikiRevision
;
497 $revision->setID( $logInfo['id'] );
498 $revision->setType( $logInfo['type'] );
499 $revision->setAction( $logInfo['action'] );
500 $revision->setTimestamp( $logInfo['timestamp'] );
501 $revision->setParams( $logInfo['params'] );
502 $revision->setTitle( Title
::newFromText( $logInfo['logtitle'] ) );
503 $revision->setNoUpdates( $this->mNoUpdates
);
505 if ( isset( $logInfo['comment'] ) ) {
506 $revision->setComment( $logInfo['comment'] );
509 if ( isset( $logInfo['contributor']['ip'] ) ) {
510 $revision->setUserIP( $logInfo['contributor']['ip'] );
512 if ( isset( $logInfo['contributor']['username'] ) ) {
513 $revision->setUserName( $logInfo['contributor']['username'] );
516 return $this->logItemCallback( $revision );
519 private function handlePage() {
521 $this->debug( "Enter page handler." );
522 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
524 // Fields that can just be stuffed in the pageInfo object
525 $normalFields = array( 'title', 'id', 'redirect', 'restrictions' );
530 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
531 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
532 $this->reader
->name
== 'page') {
536 $tag = $this->reader
->name
;
539 // The title is invalid, bail out of this page
541 } elseif ( !wfRunHooks( 'ImportHandlePageXMLTag', array( $this,
544 } elseif ( in_array( $tag, $normalFields ) ) {
545 $pageInfo[$tag] = $this->nodeContents();
546 if ( $tag == 'title' ) {
547 $title = $this->processTitle( $pageInfo['title'] );
554 $this->pageCallback( $title );
555 list( $pageInfo['_title'], $origTitle ) = $title;
557 } elseif ( $tag == 'revision' ) {
558 $this->handleRevision( $pageInfo );
559 } elseif ( $tag == 'upload' ) {
560 $this->handleUpload( $pageInfo );
561 } elseif ( $tag != '#text' ) {
562 $this->warn( "Unhandled page XML tag $tag" );
567 $this->pageOutCallback( $pageInfo['_title'], $origTitle,
568 $pageInfo['revisionCount'],
569 $pageInfo['successfulRevisionCount'],
574 * @param $pageInfo array
576 private function handleRevision( &$pageInfo ) {
577 $this->debug( "Enter revision handler" );
578 $revisionInfo = array();
580 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'text' );
584 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
585 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
586 $this->reader
->name
== 'revision') {
590 $tag = $this->reader
->name
;
592 if ( !wfRunHooks( 'ImportHandleRevisionXMLTag', $this,
593 $pageInfo, $revisionInfo ) ) {
595 } elseif ( in_array( $tag, $normalFields ) ) {
596 $revisionInfo[$tag] = $this->nodeContents();
597 } elseif ( $tag == 'contributor' ) {
598 $revisionInfo['contributor'] = $this->handleContributor();
599 } elseif ( $tag != '#text' ) {
600 $this->warn( "Unhandled revision XML tag $tag" );
605 $pageInfo['revisionCount']++
;
606 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
607 $pageInfo['successfulRevisionCount']++
;
613 * @param $revisionInfo
616 private function processRevision( $pageInfo, $revisionInfo ) {
617 $revision = new WikiRevision
;
619 if( isset( $revisionInfo['id'] ) ) {
620 $revision->setID( $revisionInfo['id'] );
622 if ( isset( $revisionInfo['text'] ) ) {
623 $revision->setText( $revisionInfo['text'] );
625 $revision->setTitle( $pageInfo['_title'] );
627 if ( isset( $revisionInfo['timestamp'] ) ) {
628 $revision->setTimestamp( $revisionInfo['timestamp'] );
630 $revision->setTimestamp( wfTimestampNow() );
633 if ( isset( $revisionInfo['comment'] ) ) {
634 $revision->setComment( $revisionInfo['comment'] );
637 if ( isset( $revisionInfo['minor'] ) ) {
638 $revision->setMinor( true );
640 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
641 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
643 if ( isset( $revisionInfo['contributor']['username'] ) ) {
644 $revision->setUserName( $revisionInfo['contributor']['username'] );
646 $revision->setNoUpdates( $this->mNoUpdates
);
648 return $this->revisionCallback( $revision );
655 private function handleUpload( &$pageInfo ) {
656 $this->debug( "Enter upload handler" );
657 $uploadInfo = array();
659 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
660 'src', 'size', 'sha1base36', 'archivename', 'rel' );
664 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
665 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
666 $this->reader
->name
== 'upload') {
670 $tag = $this->reader
->name
;
672 if ( !wfRunHooks( 'ImportHandleUploadXMLTag', $this,
675 } elseif ( in_array( $tag, $normalFields ) ) {
676 $uploadInfo[$tag] = $this->nodeContents();
677 } elseif ( $tag == 'contributor' ) {
678 $uploadInfo['contributor'] = $this->handleContributor();
679 } elseif ( $tag == 'contents' ) {
680 $contents = $this->nodeContents();
681 $encoding = $this->reader
->getAttribute( 'encoding' );
682 if ( $encoding === 'base64' ) {
683 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
684 $uploadInfo['isTempSrc'] = true;
686 } elseif ( $tag != '#text' ) {
687 $this->warn( "Unhandled upload XML tag $tag" );
692 if ( $this->mImageBasePath
&& isset( $uploadInfo['rel'] ) ) {
693 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
694 if ( file_exists( $path ) ) {
695 $uploadInfo['fileSrc'] = $path;
696 $uploadInfo['isTempSrc'] = false;
700 if ( $this->mImportUploads
) {
701 return $this->processUpload( $pageInfo, $uploadInfo );
709 private function dumpTemp( $contents ) {
710 $filename = tempnam( wfTempDir(), 'importupload' );
711 file_put_contents( $filename, $contents );
720 private function processUpload( $pageInfo, $uploadInfo ) {
721 $revision = new WikiRevision
;
722 $text = isset( $uploadInfo['text'] ) ?
$uploadInfo['text'] : '';
724 $revision->setTitle( $pageInfo['_title'] );
725 $revision->setID( $pageInfo['id'] );
726 $revision->setTimestamp( $uploadInfo['timestamp'] );
727 $revision->setText( $text );
728 $revision->setFilename( $uploadInfo['filename'] );
729 if ( isset( $uploadInfo['archivename'] ) ) {
730 $revision->setArchiveName( $uploadInfo['archivename'] );
732 $revision->setSrc( $uploadInfo['src'] );
733 if ( isset( $uploadInfo['fileSrc'] ) ) {
734 $revision->setFileSrc( $uploadInfo['fileSrc'],
735 !empty( $uploadInfo['isTempSrc'] ) );
737 if ( isset( $uploadInfo['sha1base36'] ) ) {
738 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
740 $revision->setSize( intval( $uploadInfo['size'] ) );
741 $revision->setComment( $uploadInfo['comment'] );
743 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
744 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
746 if ( isset( $uploadInfo['contributor']['username'] ) ) {
747 $revision->setUserName( $uploadInfo['contributor']['username'] );
749 $revision->setNoUpdates( $this->mNoUpdates
);
751 return call_user_func( $this->mUploadCallback
, $revision );
757 private function handleContributor() {
758 $fields = array( 'id', 'ip', 'username' );
761 while ( $this->reader
->read() ) {
762 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
763 $this->reader
->name
== 'contributor') {
767 $tag = $this->reader
->name
;
769 if ( in_array( $tag, $fields ) ) {
770 $info[$tag] = $this->nodeContents();
778 * @param $text string
779 * @return Array or false
781 private function processTitle( $text ) {
782 global $wgCommandLineMode;
785 $origTitle = Title
::newFromText( $workTitle );
787 if( !is_null( $this->mTargetNamespace
) && !is_null( $origTitle ) ) {
788 $title = Title
::makeTitle( $this->mTargetNamespace
,
789 $origTitle->getDBkey() );
791 $title = Title
::newFromText( $workTitle );
794 if( is_null( $title ) ) {
795 # Invalid page title? Ignore the page
796 $this->notice( 'import-error-invalid', $workTitle );
798 } elseif( $title->isExternal() ) {
799 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
801 } elseif( !$title->canExist() ) {
802 $this->notice( 'import-error-special', $title->getPrefixedText() );
804 } elseif( !$title->userCan( 'edit' ) && !$wgCommandLineMode ) {
805 # Do not import if the importing wiki user cannot edit this page
806 $this->notice( 'import-error-edit', $title->getPrefixedText() );
808 } elseif( !$title->exists() && !$title->userCan( 'create' ) && !$wgCommandLineMode ) {
809 # Do not import if the importing wiki user cannot create this page
810 $this->notice( 'import-error-create', $title->getPrefixedText() );
814 return array( $title, $origTitle );
818 /** This is a horrible hack used to keep source compatibility */
819 class UploadSourceAdapter
{
820 static $sourceRegistrations = array();
830 static function registerSource( $source ) {
831 $id = wfGenerateToken();
833 self
::$sourceRegistrations[$id] = $source;
842 * @param $opened_path
845 function stream_open( $path, $mode, $options, &$opened_path ) {
846 $url = parse_url($path);
849 if ( !isset( self
::$sourceRegistrations[$id] ) ) {
853 $this->mSource
= self
::$sourceRegistrations[$id];
862 function stream_read( $count ) {
866 while ( !$leave && !$this->mSource
->atEnd() &&
867 strlen($this->mBuffer
) < $count ) {
868 $read = $this->mSource
->readChunk();
870 if ( !strlen($read) ) {
874 $this->mBuffer
.= $read;
877 if ( strlen($this->mBuffer
) ) {
878 $return = substr( $this->mBuffer
, 0, $count );
879 $this->mBuffer
= substr( $this->mBuffer
, $count );
882 $this->mPosition +
= strlen($return);
891 function stream_write( $data ) {
898 function stream_tell() {
899 return $this->mPosition
;
905 function stream_eof() {
906 return $this->mSource
->atEnd();
912 function url_stat() {
915 $result['dev'] = $result[0] = 0;
916 $result['ino'] = $result[1] = 0;
917 $result['mode'] = $result[2] = 0;
918 $result['nlink'] = $result[3] = 0;
919 $result['uid'] = $result[4] = 0;
920 $result['gid'] = $result[5] = 0;
921 $result['rdev'] = $result[6] = 0;
922 $result['size'] = $result[7] = 0;
923 $result['atime'] = $result[8] = 0;
924 $result['mtime'] = $result[9] = 0;
925 $result['ctime'] = $result[10] = 0;
926 $result['blksize'] = $result[11] = 0;
927 $result['blocks'] = $result[12] = 0;
933 class XMLReader2
extends XMLReader
{
936 * @return bool|string
938 function nodeContents() {
939 if( $this->isEmptyElement
) {
943 while( $this->read() ) {
944 switch( $this->nodeType
) {
945 case XmlReader
::TEXT
:
946 case XmlReader
::SIGNIFICANT_WHITESPACE
:
947 $buffer .= $this->value
;
949 case XmlReader
::END_ELEMENT
:
953 return $this->close();
958 * @todo document (e.g. one-sentence class description).
959 * @ingroup SpecialPage
962 var $importer = null;
969 var $timestamp = "20010115000000";
979 var $sha1base36 = false;
981 var $archiveName = '';
983 private $mNoUpdates = false;
987 * @throws MWException
989 function setTitle( $title ) {
990 if( is_object( $title ) ) {
991 $this->title
= $title;
992 } elseif( is_null( $title ) ) {
993 throw new MWException( "WikiRevision given a null title in import. You may need to adjust \$wgLegalTitleChars." );
995 throw new MWException( "WikiRevision given non-object title in import." );
1002 function setID( $id ) {
1009 function setTimestamp( $ts ) {
1010 # 2003-08-05T18:30:02Z
1011 $this->timestamp
= wfTimestamp( TS_MW
, $ts );
1017 function setUsername( $user ) {
1018 $this->user_text
= $user;
1024 function setUserIP( $ip ) {
1025 $this->user_text
= $ip;
1031 function setText( $text ) {
1032 $this->text
= $text;
1038 function setComment( $text ) {
1039 $this->comment
= $text;
1045 function setMinor( $minor ) {
1046 $this->minor
= (bool)$minor;
1052 function setSrc( $src ) {
1060 function setFileSrc( $src, $isTemp ) {
1061 $this->fileSrc
= $src;
1062 $this->fileIsTemp
= $isTemp;
1066 * @param $sha1base36
1068 function setSha1Base36( $sha1base36 ) {
1069 $this->sha1base36
= $sha1base36;
1075 function setFilename( $filename ) {
1076 $this->filename
= $filename;
1080 * @param $archiveName
1082 function setArchiveName( $archiveName ) {
1083 $this->archiveName
= $archiveName;
1089 function setSize( $size ) {
1090 $this->size
= intval( $size );
1096 function setType( $type ) {
1097 $this->type
= $type;
1103 function setAction( $action ) {
1104 $this->action
= $action;
1110 function setParams( $params ) {
1111 $this->params
= $params;
1117 public function setNoUpdates( $noupdates ) {
1118 $this->mNoUpdates
= $noupdates;
1124 function getTitle() {
1125 return $this->title
;
1138 function getTimestamp() {
1139 return $this->timestamp
;
1145 function getUser() {
1146 return $this->user_text
;
1152 function getText() {
1159 function getComment() {
1160 return $this->comment
;
1166 function getMinor() {
1167 return $this->minor
;
1178 * @return bool|String
1180 function getSha1() {
1181 if ( $this->sha1base36
) {
1182 return wfBaseConvert( $this->sha1base36
, 36, 16 );
1190 function getFileSrc() {
1191 return $this->fileSrc
;
1197 function isTempSrc() {
1198 return $this->isTemp
;
1204 function getFilename() {
1205 return $this->filename
;
1211 function getArchiveName() {
1212 return $this->archiveName
;
1218 function getSize() {
1225 function getType() {
1232 function getAction() {
1233 return $this->action
;
1239 function getParams() {
1240 return $this->params
;
1246 function importOldRevision() {
1247 $dbw = wfGetDB( DB_MASTER
);
1249 # Sneak a single revision into place
1250 $user = User
::newFromName( $this->getUser() );
1252 $userId = intval( $user->getId() );
1253 $userText = $user->getName();
1257 $userText = $this->getUser();
1258 $userObj = new User
;
1261 // avoid memory leak...?
1262 $linkCache = LinkCache
::singleton();
1263 $linkCache->clear();
1265 $page = WikiPage
::factory( $this->title
);
1266 if( !$page->exists() ) {
1267 # must create the page...
1268 $pageId = $page->insertOn( $dbw );
1270 $oldcountable = null;
1272 $pageId = $page->getId();
1275 $prior = $dbw->selectField( 'revision', '1',
1276 array( 'rev_page' => $pageId,
1277 'rev_timestamp' => $dbw->timestamp( $this->timestamp
),
1278 'rev_user_text' => $userText,
1279 'rev_comment' => $this->getComment() ),
1283 // @todo FIXME: This could fail slightly for multiple matches :P
1284 wfDebug( __METHOD__
. ": skipping existing revision for [[" .
1285 $this->title
->getPrefixedText() . "]], timestamp " . $this->timestamp
. "\n" );
1288 $oldcountable = $page->isCountable();
1291 # @todo FIXME: Use original rev_id optionally (better for backups)
1293 $revision = new Revision( array(
1295 'text' => $this->getText(),
1296 'comment' => $this->getComment(),
1298 'user_text' => $userText,
1299 'timestamp' => $this->timestamp
,
1300 'minor_edit' => $this->minor
,
1302 $revision->insertOn( $dbw );
1303 $changed = $page->updateIfNewerOn( $dbw, $revision );
1305 if ( $changed !== false && !$this->mNoUpdates
) {
1306 wfDebug( __METHOD__
. ": running updates\n" );
1307 $page->doEditUpdates( $revision, $userObj, array( 'created' => $created, 'oldcountable' => $oldcountable ) );
1316 function importLogItem() {
1317 $dbw = wfGetDB( DB_MASTER
);
1318 # @todo FIXME: This will not record autoblocks
1319 if( !$this->getTitle() ) {
1320 wfDebug( __METHOD__
. ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1321 $this->timestamp
. "\n" );
1324 # Check if it exists already
1325 // @todo FIXME: Use original log ID (better for backups)
1326 $prior = $dbw->selectField( 'logging', '1',
1327 array( 'log_type' => $this->getType(),
1328 'log_action' => $this->getAction(),
1329 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1330 'log_namespace' => $this->getTitle()->getNamespace(),
1331 'log_title' => $this->getTitle()->getDBkey(),
1332 'log_comment' => $this->getComment(),
1333 #'log_user_text' => $this->user_text,
1334 'log_params' => $this->params
),
1337 // @todo FIXME: This could fail slightly for multiple matches :P
1339 wfDebug( __METHOD__
. ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp " .
1340 $this->timestamp
. "\n" );
1343 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1345 'log_id' => $log_id,
1346 'log_type' => $this->type
,
1347 'log_action' => $this->action
,
1348 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1349 'log_user' => User
::idFromName( $this->user_text
),
1350 #'log_user_text' => $this->user_text,
1351 'log_namespace' => $this->getTitle()->getNamespace(),
1352 'log_title' => $this->getTitle()->getDBkey(),
1353 'log_comment' => $this->getComment(),
1354 'log_params' => $this->params
1356 $dbw->insert( 'logging', $data, __METHOD__
);
1362 function importUpload() {
1364 $archiveName = $this->getArchiveName();
1365 if ( $archiveName ) {
1366 wfDebug( __METHOD__
. "Importing archived file as $archiveName\n" );
1367 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1368 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1370 $file = wfLocalFile( $this->getTitle() );
1371 wfDebug( __METHOD__
. 'Importing new file as ' . $file->getName() . "\n" );
1372 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1373 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1374 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1375 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1376 wfDebug( __METHOD__
. "File already exists; importing as $archiveName\n" );
1380 wfDebug( __METHOD__
. ': Bad file for ' . $this->getTitle() . "\n" );
1384 # Get the file source or download if necessary
1385 $source = $this->getFileSrc();
1386 $flags = $this->isTempSrc() ? File
::DELETE_SOURCE
: 0;
1388 $source = $this->downloadSource();
1389 $flags |
= File
::DELETE_SOURCE
;
1392 wfDebug( __METHOD__
. ": Could not fetch remote file.\n" );
1395 $sha1 = $this->getSha1();
1396 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1397 if ( $flags & File
::DELETE_SOURCE
) {
1398 # Broken file; delete it if it is a temporary file
1401 wfDebug( __METHOD__
. ": Corrupt file $source.\n" );
1405 $user = User
::newFromName( $this->user_text
);
1407 # Do the actual upload
1408 if ( $archiveName ) {
1409 $status = $file->uploadOld( $source, $archiveName,
1410 $this->getTimestamp(), $this->getComment(), $user, $flags );
1412 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1413 $flags, false, $this->getTimestamp(), $user );
1416 if ( $status->isGood() ) {
1417 wfDebug( __METHOD__
. ": Succesful\n" );
1420 wfDebug( __METHOD__
. ': failed: ' . $status->getXml() . "\n" );
1426 * @return bool|string
1428 function downloadSource() {
1429 global $wgEnableUploads;
1430 if( !$wgEnableUploads ) {
1434 $tempo = tempnam( wfTempDir(), 'download' );
1435 $f = fopen( $tempo, 'wb' );
1437 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1442 $src = $this->getSrc();
1443 $data = Http
::get( $src );
1445 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1451 fwrite( $f, $data );
1460 * @todo document (e.g. one-sentence class description).
1461 * @ingroup SpecialPage
1463 class ImportStringSource
{
1464 function __construct( $string ) {
1465 $this->mString
= $string;
1466 $this->mRead
= false;
1473 return $this->mRead
;
1477 * @return bool|string
1479 function readChunk() {
1480 if( $this->atEnd() ) {
1483 $this->mRead
= true;
1484 return $this->mString
;
1489 * @todo document (e.g. one-sentence class description).
1490 * @ingroup SpecialPage
1492 class ImportStreamSource
{
1493 function __construct( $handle ) {
1494 $this->mHandle
= $handle;
1501 return feof( $this->mHandle
);
1507 function readChunk() {
1508 return fread( $this->mHandle
, 32768 );
1512 * @param $filename string
1515 static function newFromFile( $filename ) {
1516 wfSuppressWarnings();
1517 $file = fopen( $filename, 'rt' );
1518 wfRestoreWarnings();
1520 return Status
::newFatal( "importcantopen" );
1522 return Status
::newGood( new ImportStreamSource( $file ) );
1526 * @param $fieldname string
1529 static function newFromUpload( $fieldname = "xmlimport" ) {
1530 $upload =& $_FILES[$fieldname];
1532 if( !isset( $upload ) ||
!$upload['name'] ) {
1533 return Status
::newFatal( 'importnofile' );
1535 if( !empty( $upload['error'] ) ) {
1536 switch($upload['error']){
1537 case 1: # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1538 return Status
::newFatal( 'importuploaderrorsize' );
1539 case 2: # The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
1540 return Status
::newFatal( 'importuploaderrorsize' );
1541 case 3: # The uploaded file was only partially uploaded
1542 return Status
::newFatal( 'importuploaderrorpartial' );
1543 case 6: #Missing a temporary folder.
1544 return Status
::newFatal( 'importuploaderrortemp' );
1545 # case else: # Currently impossible
1549 $fname = $upload['tmp_name'];
1550 if( is_uploaded_file( $fname ) ) {
1551 return ImportStreamSource
::newFromFile( $fname );
1553 return Status
::newFatal( 'importnofile' );
1559 * @param $method string
1562 static function newFromURL( $url, $method = 'GET' ) {
1563 wfDebug( __METHOD__
. ": opening $url\n" );
1564 # Use the standard HTTP fetch function; it times out
1565 # quicker and sorts out user-agent problems which might
1566 # otherwise prevent importing from large sites, such
1567 # as the Wikimedia cluster, etc.
1568 $data = Http
::request( $method, $url, array( 'followRedirects' => true ) );
1569 if( $data !== false ) {
1571 fwrite( $file, $data );
1574 return Status
::newGood( new ImportStreamSource( $file ) );
1576 return Status
::newFatal( 'importcantopen' );
1583 * @param $history bool
1584 * @param $templates bool
1585 * @param $pageLinkDepth int
1588 public static function newFromInterwiki( $interwiki, $page, $history = false, $templates = false, $pageLinkDepth = 0 ) {
1590 return Status
::newFatal( 'import-noarticle' );
1592 $link = Title
::newFromText( "$interwiki:Special:Export/$page" );
1593 if( is_null( $link ) ||
$link->getInterwiki() == '' ) {
1594 return Status
::newFatal( 'importbadinterwiki' );
1597 if ( $history ) $params['history'] = 1;
1598 if ( $templates ) $params['templates'] = 1;
1599 if ( $pageLinkDepth ) $params['pagelink-depth'] = $pageLinkDepth;
1600 $url = $link->getFullUrl( $params );
1601 # For interwikis, use POST to avoid redirects.
1602 return ImportStreamSource
::newFromURL( $url, "POST" );