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 A WikiRevision object
306 private function revisionCallback( $revision ) {
307 if ( isset( $this->mRevisionCallback
) ) {
308 return call_user_func_array( $this->mRevisionCallback
,
309 array( $revision, $this ) );
316 * Notify the callback function of a new log item
317 * @param $revision A WikiRevision object
319 private function logItemCallback( $revision ) {
320 if ( isset( $this->mLogItemCallback
) ) {
321 return call_user_func_array( $this->mLogItemCallback
,
322 array( $revision, $this ) );
329 * Shouldn't something like this be built-in to XMLReader?
330 * Fetches text contents of the current element, assuming
331 * no sub-elements or such scary things.
335 private function nodeContents() {
336 if( $this->reader
->isEmptyElement
) {
340 while( $this->reader
->read() ) {
341 switch( $this->reader
->nodeType
) {
342 case XmlReader
::TEXT
:
343 case XmlReader
::SIGNIFICANT_WHITESPACE
:
344 $buffer .= $this->reader
->value
;
346 case XmlReader
::END_ELEMENT
:
351 $this->reader
->close();
357 /** Left in for debugging */
358 private function dumpElement() {
359 static $lookup = null;
361 $xmlReaderConstants = array(
376 "SIGNIFICANT_WHITESPACE",
383 foreach( $xmlReaderConstants as $name ) {
384 $lookup[constant("XmlReader::$name")] = $name;
389 $lookup[$this->reader
->nodeType
],
396 * Primary entry point
398 public function doImport() {
399 $this->reader
->read();
401 if ( $this->reader
->name
!= 'mediawiki' ) {
402 throw new MWException( "Expected <mediawiki> tag, got ".
403 $this->reader
->name
);
405 $this->debug( "<mediawiki> tag is correct." );
407 $this->debug( "Starting primary dump processing loop." );
409 $keepReading = $this->reader
->read();
411 while ( $keepReading ) {
412 $tag = $this->reader
->name
;
413 $type = $this->reader
->nodeType
;
415 if ( !wfRunHooks( 'ImportHandleToplevelXMLTag', $this ) ) {
417 } elseif ( $tag == 'mediawiki' && $type == XmlReader
::END_ELEMENT
) {
419 } elseif ( $tag == 'siteinfo' ) {
420 $this->handleSiteInfo();
421 } elseif ( $tag == 'page' ) {
423 } elseif ( $tag == 'logitem' ) {
424 $this->handleLogItem();
425 } elseif ( $tag != '#text' ) {
426 $this->warn( "Unhandled top-level XML tag $tag" );
432 $keepReading = $this->reader
->next();
434 $this->debug( "Skip" );
436 $keepReading = $this->reader
->read();
445 * @throws MWException
447 private function handleSiteInfo() {
448 // Site info is useful, but not actually used for dump imports.
449 // Includes a quick short-circuit to save performance.
450 if ( ! $this->mSiteInfoCallback
) {
451 $this->reader
->next();
454 throw new MWException( "SiteInfo tag is not yet handled, do not set mSiteInfoCallback" );
457 private function handleLogItem() {
458 $this->debug( "Enter log item handler." );
461 // Fields that can just be stuffed in the pageInfo object
462 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
463 'logtitle', 'params' );
465 while ( $this->reader
->read() ) {
466 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
467 $this->reader
->name
== 'logitem') {
471 $tag = $this->reader
->name
;
473 if ( !wfRunHooks( 'ImportHandleLogItemXMLTag',
474 $this, $logInfo ) ) {
476 } elseif ( in_array( $tag, $normalFields ) ) {
477 $logInfo[$tag] = $this->nodeContents();
478 } elseif ( $tag == 'contributor' ) {
479 $logInfo['contributor'] = $this->handleContributor();
480 } elseif ( $tag != '#text' ) {
481 $this->warn( "Unhandled log-item XML tag $tag" );
485 $this->processLogItem( $logInfo );
492 private function processLogItem( $logInfo ) {
493 $revision = new WikiRevision
;
495 $revision->setID( $logInfo['id'] );
496 $revision->setType( $logInfo['type'] );
497 $revision->setAction( $logInfo['action'] );
498 $revision->setTimestamp( $logInfo['timestamp'] );
499 $revision->setParams( $logInfo['params'] );
500 $revision->setTitle( Title
::newFromText( $logInfo['logtitle'] ) );
501 $revision->setNoUpdates( $this->mNoUpdates
);
503 if ( isset( $logInfo['comment'] ) ) {
504 $revision->setComment( $logInfo['comment'] );
507 if ( isset( $logInfo['contributor']['ip'] ) ) {
508 $revision->setUserIP( $logInfo['contributor']['ip'] );
510 if ( isset( $logInfo['contributor']['username'] ) ) {
511 $revision->setUserName( $logInfo['contributor']['username'] );
514 return $this->logItemCallback( $revision );
517 private function handlePage() {
519 $this->debug( "Enter page handler." );
520 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
522 // Fields that can just be stuffed in the pageInfo object
523 $normalFields = array( 'title', 'id', 'redirect', 'restrictions' );
528 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
529 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
530 $this->reader
->name
== 'page') {
534 $tag = $this->reader
->name
;
537 // The title is invalid, bail out of this page
539 } elseif ( !wfRunHooks( 'ImportHandlePageXMLTag', array( $this,
542 } elseif ( in_array( $tag, $normalFields ) ) {
543 $pageInfo[$tag] = $this->nodeContents();
544 if ( $tag == 'title' ) {
545 $title = $this->processTitle( $pageInfo['title'] );
552 $this->pageCallback( $title );
553 list( $pageInfo['_title'], $origTitle ) = $title;
555 } elseif ( $tag == 'revision' ) {
556 $this->handleRevision( $pageInfo );
557 } elseif ( $tag == 'upload' ) {
558 $this->handleUpload( $pageInfo );
559 } elseif ( $tag != '#text' ) {
560 $this->warn( "Unhandled page XML tag $tag" );
565 $this->pageOutCallback( $pageInfo['_title'], $origTitle,
566 $pageInfo['revisionCount'],
567 $pageInfo['successfulRevisionCount'],
574 private function handleRevision( &$pageInfo ) {
575 $this->debug( "Enter revision handler" );
576 $revisionInfo = array();
578 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'text' );
582 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
583 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
584 $this->reader
->name
== 'revision') {
588 $tag = $this->reader
->name
;
590 if ( !wfRunHooks( 'ImportHandleRevisionXMLTag', $this,
591 $pageInfo, $revisionInfo ) ) {
593 } elseif ( in_array( $tag, $normalFields ) ) {
594 $revisionInfo[$tag] = $this->nodeContents();
595 } elseif ( $tag == 'contributor' ) {
596 $revisionInfo['contributor'] = $this->handleContributor();
597 } elseif ( $tag != '#text' ) {
598 $this->warn( "Unhandled revision XML tag $tag" );
603 $pageInfo['revisionCount']++
;
604 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
605 $pageInfo['successfulRevisionCount']++
;
611 * @param $revisionInfo
614 private function processRevision( $pageInfo, $revisionInfo ) {
615 $revision = new WikiRevision
;
617 if( isset( $revisionInfo['id'] ) ) {
618 $revision->setID( $revisionInfo['id'] );
620 if ( isset( $revisionInfo['text'] ) ) {
621 $revision->setText( $revisionInfo['text'] );
623 $revision->setTitle( $pageInfo['_title'] );
625 if ( isset( $revisionInfo['timestamp'] ) ) {
626 $revision->setTimestamp( $revisionInfo['timestamp'] );
628 $revision->setTimestamp( wfTimestampNow() );
631 if ( isset( $revisionInfo['comment'] ) ) {
632 $revision->setComment( $revisionInfo['comment'] );
635 if ( isset( $revisionInfo['minor'] ) ) {
636 $revision->setMinor( true );
638 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
639 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
641 if ( isset( $revisionInfo['contributor']['username'] ) ) {
642 $revision->setUserName( $revisionInfo['contributor']['username'] );
644 $revision->setNoUpdates( $this->mNoUpdates
);
646 return $this->revisionCallback( $revision );
653 private function handleUpload( &$pageInfo ) {
654 $this->debug( "Enter upload handler" );
655 $uploadInfo = array();
657 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
658 'src', 'size', 'sha1base36', 'archivename', 'rel' );
662 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
663 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
664 $this->reader
->name
== 'upload') {
668 $tag = $this->reader
->name
;
670 if ( !wfRunHooks( 'ImportHandleUploadXMLTag', $this,
673 } elseif ( in_array( $tag, $normalFields ) ) {
674 $uploadInfo[$tag] = $this->nodeContents();
675 } elseif ( $tag == 'contributor' ) {
676 $uploadInfo['contributor'] = $this->handleContributor();
677 } elseif ( $tag == 'contents' ) {
678 $contents = $this->nodeContents();
679 $encoding = $this->reader
->getAttribute( 'encoding' );
680 if ( $encoding === 'base64' ) {
681 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
682 $uploadInfo['isTempSrc'] = true;
684 } elseif ( $tag != '#text' ) {
685 $this->warn( "Unhandled upload XML tag $tag" );
690 if ( $this->mImageBasePath
&& isset( $uploadInfo['rel'] ) ) {
691 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
692 if ( file_exists( $path ) ) {
693 $uploadInfo['fileSrc'] = $path;
694 $uploadInfo['isTempSrc'] = false;
698 if ( $this->mImportUploads
) {
699 return $this->processUpload( $pageInfo, $uploadInfo );
707 private function dumpTemp( $contents ) {
708 $filename = tempnam( wfTempDir(), 'importupload' );
709 file_put_contents( $filename, $contents );
718 private function processUpload( $pageInfo, $uploadInfo ) {
719 $revision = new WikiRevision
;
720 $text = isset( $uploadInfo['text'] ) ?
$uploadInfo['text'] : '';
722 $revision->setTitle( $pageInfo['_title'] );
723 $revision->setID( $pageInfo['id'] );
724 $revision->setTimestamp( $uploadInfo['timestamp'] );
725 $revision->setText( $text );
726 $revision->setFilename( $uploadInfo['filename'] );
727 if ( isset( $uploadInfo['archivename'] ) ) {
728 $revision->setArchiveName( $uploadInfo['archivename'] );
730 $revision->setSrc( $uploadInfo['src'] );
731 if ( isset( $uploadInfo['fileSrc'] ) ) {
732 $revision->setFileSrc( $uploadInfo['fileSrc'],
733 !empty( $uploadInfo['isTempSrc'] ) );
735 if ( isset( $uploadInfo['sha1base36'] ) ) {
736 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
738 $revision->setSize( intval( $uploadInfo['size'] ) );
739 $revision->setComment( $uploadInfo['comment'] );
741 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
742 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
744 if ( isset( $uploadInfo['contributor']['username'] ) ) {
745 $revision->setUserName( $uploadInfo['contributor']['username'] );
747 $revision->setNoUpdates( $this->mNoUpdates
);
749 return call_user_func( $this->mUploadCallback
, $revision );
755 private function handleContributor() {
756 $fields = array( 'id', 'ip', 'username' );
759 while ( $this->reader
->read() ) {
760 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
761 $this->reader
->name
== 'contributor') {
765 $tag = $this->reader
->name
;
767 if ( in_array( $tag, $fields ) ) {
768 $info[$tag] = $this->nodeContents();
776 * @param $text string
777 * @return Array or false
779 private function processTitle( $text ) {
780 global $wgCommandLineMode;
783 $origTitle = Title
::newFromText( $workTitle );
785 if( !is_null( $this->mTargetNamespace
) && !is_null( $origTitle ) ) {
786 $title = Title
::makeTitle( $this->mTargetNamespace
,
787 $origTitle->getDBkey() );
789 $title = Title
::newFromText( $workTitle );
792 if( is_null( $title ) ) {
793 # Invalid page title? Ignore the page
794 $this->notice( 'import-error-invalid', $workTitle );
796 } elseif( $title->isExternal() ) {
797 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
799 } elseif( !$title->canExist() ) {
800 $this->notice( 'import-error-special', $title->getPrefixedText() );
802 } elseif( !$title->userCan( 'edit' ) && !$wgCommandLineMode ) {
803 # Do not import if the importing wiki user cannot edit this page
804 $this->notice( 'import-error-edit', $title->getPrefixedText() );
806 } elseif( !$title->exists() && !$title->userCan( 'create' ) && !$wgCommandLineMode ) {
807 # Do not import if the importing wiki user cannot create this page
808 $this->notice( 'import-error-create', $title->getPrefixedText() );
812 return array( $title, $origTitle );
816 /** This is a horrible hack used to keep source compatibility */
817 class UploadSourceAdapter
{
818 static $sourceRegistrations = array();
828 static function registerSource( $source ) {
829 $id = wfGenerateToken();
831 self
::$sourceRegistrations[$id] = $source;
840 * @param $opened_path
843 function stream_open( $path, $mode, $options, &$opened_path ) {
844 $url = parse_url($path);
847 if ( !isset( self
::$sourceRegistrations[$id] ) ) {
851 $this->mSource
= self
::$sourceRegistrations[$id];
860 function stream_read( $count ) {
864 while ( !$leave && !$this->mSource
->atEnd() &&
865 strlen($this->mBuffer
) < $count ) {
866 $read = $this->mSource
->readChunk();
868 if ( !strlen($read) ) {
872 $this->mBuffer
.= $read;
875 if ( strlen($this->mBuffer
) ) {
876 $return = substr( $this->mBuffer
, 0, $count );
877 $this->mBuffer
= substr( $this->mBuffer
, $count );
880 $this->mPosition +
= strlen($return);
889 function stream_write( $data ) {
896 function stream_tell() {
897 return $this->mPosition
;
903 function stream_eof() {
904 return $this->mSource
->atEnd();
910 function url_stat() {
913 $result['dev'] = $result[0] = 0;
914 $result['ino'] = $result[1] = 0;
915 $result['mode'] = $result[2] = 0;
916 $result['nlink'] = $result[3] = 0;
917 $result['uid'] = $result[4] = 0;
918 $result['gid'] = $result[5] = 0;
919 $result['rdev'] = $result[6] = 0;
920 $result['size'] = $result[7] = 0;
921 $result['atime'] = $result[8] = 0;
922 $result['mtime'] = $result[9] = 0;
923 $result['ctime'] = $result[10] = 0;
924 $result['blksize'] = $result[11] = 0;
925 $result['blocks'] = $result[12] = 0;
931 class XMLReader2
extends XMLReader
{
934 * @return bool|string
936 function nodeContents() {
937 if( $this->isEmptyElement
) {
941 while( $this->read() ) {
942 switch( $this->nodeType
) {
943 case XmlReader
::TEXT
:
944 case XmlReader
::SIGNIFICANT_WHITESPACE
:
945 $buffer .= $this->value
;
947 case XmlReader
::END_ELEMENT
:
951 return $this->close();
956 * @todo document (e.g. one-sentence class description).
957 * @ingroup SpecialPage
960 var $importer = null;
967 var $timestamp = "20010115000000";
977 var $sha1base36 = false;
979 var $archiveName = '';
981 private $mNoUpdates = false;
985 * @throws MWException
987 function setTitle( $title ) {
988 if( is_object( $title ) ) {
989 $this->title
= $title;
990 } elseif( is_null( $title ) ) {
991 throw new MWException( "WikiRevision given a null title in import. You may need to adjust \$wgLegalTitleChars." );
993 throw new MWException( "WikiRevision given non-object title in import." );
1000 function setID( $id ) {
1007 function setTimestamp( $ts ) {
1008 # 2003-08-05T18:30:02Z
1009 $this->timestamp
= wfTimestamp( TS_MW
, $ts );
1015 function setUsername( $user ) {
1016 $this->user_text
= $user;
1022 function setUserIP( $ip ) {
1023 $this->user_text
= $ip;
1029 function setText( $text ) {
1030 $this->text
= $text;
1036 function setComment( $text ) {
1037 $this->comment
= $text;
1043 function setMinor( $minor ) {
1044 $this->minor
= (bool)$minor;
1050 function setSrc( $src ) {
1058 function setFileSrc( $src, $isTemp ) {
1059 $this->fileSrc
= $src;
1060 $this->fileIsTemp
= $isTemp;
1064 * @param $sha1base36
1066 function setSha1Base36( $sha1base36 ) {
1067 $this->sha1base36
= $sha1base36;
1073 function setFilename( $filename ) {
1074 $this->filename
= $filename;
1078 * @param $archiveName
1080 function setArchiveName( $archiveName ) {
1081 $this->archiveName
= $archiveName;
1087 function setSize( $size ) {
1088 $this->size
= intval( $size );
1094 function setType( $type ) {
1095 $this->type
= $type;
1101 function setAction( $action ) {
1102 $this->action
= $action;
1108 function setParams( $params ) {
1109 $this->params
= $params;
1115 public function setNoUpdates( $noupdates ) {
1116 $this->mNoUpdates
= $noupdates;
1122 function getTitle() {
1123 return $this->title
;
1136 function getTimestamp() {
1137 return $this->timestamp
;
1143 function getUser() {
1144 return $this->user_text
;
1150 function getText() {
1157 function getComment() {
1158 return $this->comment
;
1164 function getMinor() {
1165 return $this->minor
;
1176 * @return bool|String
1178 function getSha1() {
1179 if ( $this->sha1base36
) {
1180 return wfBaseConvert( $this->sha1base36
, 36, 16 );
1188 function getFileSrc() {
1189 return $this->fileSrc
;
1195 function isTempSrc() {
1196 return $this->isTemp
;
1202 function getFilename() {
1203 return $this->filename
;
1209 function getArchiveName() {
1210 return $this->archiveName
;
1216 function getSize() {
1223 function getType() {
1230 function getAction() {
1231 return $this->action
;
1237 function getParams() {
1238 return $this->params
;
1244 function importOldRevision() {
1245 $dbw = wfGetDB( DB_MASTER
);
1247 # Sneak a single revision into place
1248 $user = User
::newFromName( $this->getUser() );
1250 $userId = intval( $user->getId() );
1251 $userText = $user->getName();
1255 $userText = $this->getUser();
1256 $userObj = new User
;
1259 // avoid memory leak...?
1260 $linkCache = LinkCache
::singleton();
1261 $linkCache->clear();
1263 $page = WikiPage
::factory( $this->title
);
1264 if( !$page->exists() ) {
1265 # must create the page...
1266 $pageId = $page->insertOn( $dbw );
1268 $oldcountable = null;
1270 $pageId = $page->getId();
1273 $prior = $dbw->selectField( 'revision', '1',
1274 array( 'rev_page' => $pageId,
1275 'rev_timestamp' => $dbw->timestamp( $this->timestamp
),
1276 'rev_user_text' => $userText,
1277 'rev_comment' => $this->getComment() ),
1281 // @todo FIXME: This could fail slightly for multiple matches :P
1282 wfDebug( __METHOD__
. ": skipping existing revision for [[" .
1283 $this->title
->getPrefixedText() . "]], timestamp " . $this->timestamp
. "\n" );
1286 $oldcountable = $page->isCountable();
1289 # @todo FIXME: Use original rev_id optionally (better for backups)
1291 $revision = new Revision( array(
1293 'text' => $this->getText(),
1294 'comment' => $this->getComment(),
1296 'user_text' => $userText,
1297 'timestamp' => $this->timestamp
,
1298 'minor_edit' => $this->minor
,
1300 $revision->insertOn( $dbw );
1301 $changed = $page->updateIfNewerOn( $dbw, $revision );
1303 if ( $changed !== false && !$this->mNoUpdates
) {
1304 wfDebug( __METHOD__
. ": running updates\n" );
1305 $page->doEditUpdates( $revision, $userObj, array( 'created' => $created, 'oldcountable' => $oldcountable ) );
1314 function importLogItem() {
1315 $dbw = wfGetDB( DB_MASTER
);
1316 # @todo FIXME: This will not record autoblocks
1317 if( !$this->getTitle() ) {
1318 wfDebug( __METHOD__
. ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1319 $this->timestamp
. "\n" );
1322 # Check if it exists already
1323 // @todo FIXME: Use original log ID (better for backups)
1324 $prior = $dbw->selectField( 'logging', '1',
1325 array( 'log_type' => $this->getType(),
1326 'log_action' => $this->getAction(),
1327 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1328 'log_namespace' => $this->getTitle()->getNamespace(),
1329 'log_title' => $this->getTitle()->getDBkey(),
1330 'log_comment' => $this->getComment(),
1331 #'log_user_text' => $this->user_text,
1332 'log_params' => $this->params
),
1335 // @todo FIXME: This could fail slightly for multiple matches :P
1337 wfDebug( __METHOD__
. ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp " .
1338 $this->timestamp
. "\n" );
1341 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1343 'log_id' => $log_id,
1344 'log_type' => $this->type
,
1345 'log_action' => $this->action
,
1346 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1347 'log_user' => User
::idFromName( $this->user_text
),
1348 #'log_user_text' => $this->user_text,
1349 'log_namespace' => $this->getTitle()->getNamespace(),
1350 'log_title' => $this->getTitle()->getDBkey(),
1351 'log_comment' => $this->getComment(),
1352 'log_params' => $this->params
1354 $dbw->insert( 'logging', $data, __METHOD__
);
1360 function importUpload() {
1362 $archiveName = $this->getArchiveName();
1363 if ( $archiveName ) {
1364 wfDebug( __METHOD__
. "Importing archived file as $archiveName\n" );
1365 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1366 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1368 $file = wfLocalFile( $this->getTitle() );
1369 wfDebug( __METHOD__
. 'Importing new file as ' . $file->getName() . "\n" );
1370 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1371 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1372 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1373 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1374 wfDebug( __METHOD__
. "File already exists; importing as $archiveName\n" );
1378 wfDebug( __METHOD__
. ': Bad file for ' . $this->getTitle() . "\n" );
1382 # Get the file source or download if necessary
1383 $source = $this->getFileSrc();
1384 $flags = $this->isTempSrc() ? File
::DELETE_SOURCE
: 0;
1386 $source = $this->downloadSource();
1387 $flags |
= File
::DELETE_SOURCE
;
1390 wfDebug( __METHOD__
. ": Could not fetch remote file.\n" );
1393 $sha1 = $this->getSha1();
1394 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1395 if ( $flags & File
::DELETE_SOURCE
) {
1396 # Broken file; delete it if it is a temporary file
1399 wfDebug( __METHOD__
. ": Corrupt file $source.\n" );
1403 $user = User
::newFromName( $this->user_text
);
1405 # Do the actual upload
1406 if ( $archiveName ) {
1407 $status = $file->uploadOld( $source, $archiveName,
1408 $this->getTimestamp(), $this->getComment(), $user, $flags );
1410 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1411 $flags, false, $this->getTimestamp(), $user );
1414 if ( $status->isGood() ) {
1415 wfDebug( __METHOD__
. ": Succesful\n" );
1418 wfDebug( __METHOD__
. ': failed: ' . $status->getXml() . "\n" );
1424 * @return bool|string
1426 function downloadSource() {
1427 global $wgEnableUploads;
1428 if( !$wgEnableUploads ) {
1432 $tempo = tempnam( wfTempDir(), 'download' );
1433 $f = fopen( $tempo, 'wb' );
1435 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1440 $src = $this->getSrc();
1441 $data = Http
::get( $src );
1443 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1449 fwrite( $f, $data );
1458 * @todo document (e.g. one-sentence class description).
1459 * @ingroup SpecialPage
1461 class ImportStringSource
{
1462 function __construct( $string ) {
1463 $this->mString
= $string;
1464 $this->mRead
= false;
1471 return $this->mRead
;
1475 * @return bool|string
1477 function readChunk() {
1478 if( $this->atEnd() ) {
1481 $this->mRead
= true;
1482 return $this->mString
;
1487 * @todo document (e.g. one-sentence class description).
1488 * @ingroup SpecialPage
1490 class ImportStreamSource
{
1491 function __construct( $handle ) {
1492 $this->mHandle
= $handle;
1499 return feof( $this->mHandle
);
1505 function readChunk() {
1506 return fread( $this->mHandle
, 32768 );
1510 * @param $filename string
1513 static function newFromFile( $filename ) {
1514 wfSuppressWarnings();
1515 $file = fopen( $filename, 'rt' );
1516 wfRestoreWarnings();
1518 return Status
::newFatal( "importcantopen" );
1520 return Status
::newGood( new ImportStreamSource( $file ) );
1524 * @param $fieldname string
1527 static function newFromUpload( $fieldname = "xmlimport" ) {
1528 $upload =& $_FILES[$fieldname];
1530 if( !isset( $upload ) ||
!$upload['name'] ) {
1531 return Status
::newFatal( 'importnofile' );
1533 if( !empty( $upload['error'] ) ) {
1534 switch($upload['error']){
1535 case 1: # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1536 return Status
::newFatal( 'importuploaderrorsize' );
1537 case 2: # The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
1538 return Status
::newFatal( 'importuploaderrorsize' );
1539 case 3: # The uploaded file was only partially uploaded
1540 return Status
::newFatal( 'importuploaderrorpartial' );
1541 case 6: #Missing a temporary folder.
1542 return Status
::newFatal( 'importuploaderrortemp' );
1543 # case else: # Currently impossible
1547 $fname = $upload['tmp_name'];
1548 if( is_uploaded_file( $fname ) ) {
1549 return ImportStreamSource
::newFromFile( $fname );
1551 return Status
::newFatal( 'importnofile' );
1557 * @param $method string
1560 static function newFromURL( $url, $method = 'GET' ) {
1561 wfDebug( __METHOD__
. ": opening $url\n" );
1562 # Use the standard HTTP fetch function; it times out
1563 # quicker and sorts out user-agent problems which might
1564 # otherwise prevent importing from large sites, such
1565 # as the Wikimedia cluster, etc.
1566 $data = Http
::request( $method, $url, array( 'followRedirects' => true ) );
1567 if( $data !== false ) {
1569 fwrite( $file, $data );
1572 return Status
::newGood( new ImportStreamSource( $file ) );
1574 return Status
::newFatal( 'importcantopen' );
1581 * @param $history bool
1582 * @param $templates bool
1583 * @param $pageLinkDepth int
1586 public static function newFromInterwiki( $interwiki, $page, $history = false, $templates = false, $pageLinkDepth = 0 ) {
1588 return Status
::newFatal( 'import-noarticle' );
1590 $link = Title
::newFromText( "$interwiki:Special:Export/$page" );
1591 if( is_null( $link ) ||
$link->getInterwiki() == '' ) {
1592 return Status
::newFatal( 'importbadinterwiki' );
1595 if ( $history ) $params['history'] = 1;
1596 if ( $templates ) $params['templates'] = 1;
1597 if ( $pageLinkDepth ) $params['pagelink-depth'] = $pageLinkDepth;
1598 $url = $link->getFullUrl( $params );
1599 # For interwikis, use POST to avoid redirects.
1600 return ImportStreamSource
::newFromURL( $url, "POST" );