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;
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( $data ) {
79 global $wgCommandLineMode;
80 if( $wgCommandLineMode ) {
84 $wgOut->addHTML( "<li>" . htmlspecialchars( $data ) . "</li>\n" );
92 function setDebug( $debug ) {
93 $this->mDebug
= $debug;
97 * Set 'no updates' mode. In this mode, the link tables will not be updated by the importer
98 * @param $noupdates bool
100 function setNoUpdates( $noupdates ) {
101 $this->mNoUpdates
= $noupdates;
105 * Sets the action to perform as each new page in the stream is reached.
106 * @param $callback callback
109 public function setPageCallback( $callback ) {
110 $previous = $this->mPageCallback
;
111 $this->mPageCallback
= $callback;
116 * Sets the action to perform as each page in the stream is completed.
117 * Callback accepts the page title (as a Title object), a second object
118 * with the original title form (in case it's been overridden into a
119 * local namespace), and a count of revisions.
121 * @param $callback callback
124 public function setPageOutCallback( $callback ) {
125 $previous = $this->mPageOutCallback
;
126 $this->mPageOutCallback
= $callback;
131 * Sets the action to perform as each page revision is reached.
132 * @param $callback callback
135 public function setRevisionCallback( $callback ) {
136 $previous = $this->mRevisionCallback
;
137 $this->mRevisionCallback
= $callback;
142 * Sets the action to perform as each file upload version is reached.
143 * @param $callback callback
146 public function setUploadCallback( $callback ) {
147 $previous = $this->mUploadCallback
;
148 $this->mUploadCallback
= $callback;
153 * Sets the action to perform as each log item reached.
154 * @param $callback callback
157 public function setLogItemCallback( $callback ) {
158 $previous = $this->mLogItemCallback
;
159 $this->mLogItemCallback
= $callback;
164 * Sets the action to perform when site info is encountered
165 * @param $callback callback
168 public function setSiteInfoCallback( $callback ) {
169 $previous = $this->mSiteInfoCallback
;
170 $this->mSiteInfoCallback
= $callback;
175 * Set a target namespace to override the defaults
179 public function setTargetNamespace( $namespace ) {
180 if( is_null( $namespace ) ) {
181 // Don't override namespaces
182 $this->mTargetNamespace
= null;
183 } elseif( $namespace >= 0 ) {
184 // @todo FIXME: Check for validity
185 $this->mTargetNamespace
= intval( $namespace );
194 public function setImageBasePath( $dir ) {
195 $this->mImageBasePath
= $dir;
201 public function setImportUploads( $import ) {
202 $this->mImportUploads
= $import;
206 * Default per-revision callback, performs the import.
207 * @param $revision WikiRevision
210 public function importRevision( $revision ) {
211 $dbw = wfGetDB( DB_MASTER
);
212 return $dbw->deadlockLoop( array( $revision, 'importOldRevision' ) );
216 * Default per-revision callback, performs the import.
217 * @param $rev WikiRevision
220 public function importLogItem( $rev ) {
221 $dbw = wfGetDB( DB_MASTER
);
222 return $dbw->deadlockLoop( array( $rev, 'importLogItem' ) );
230 public function importUpload( $revision ) {
231 $dbw = wfGetDB( DB_MASTER
);
232 return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
236 * Mostly for hook use
244 public function finishImportPage( $title, $origTitle, $revCount, $sRevCount, $pageInfo ) {
245 $args = func_get_args();
246 return wfRunHooks( 'AfterImportPage', $args );
250 * Alternate per-revision callback, for debugging.
251 * @param $revision WikiRevision
253 public function debugRevisionHandler( &$revision ) {
254 $this->debug( "Got revision:" );
255 if( is_object( $revision->title
) ) {
256 $this->debug( "-- Title: " . $revision->title
->getPrefixedText() );
258 $this->debug( "-- Title: <invalid>" );
260 $this->debug( "-- User: " . $revision->user_text
);
261 $this->debug( "-- Timestamp: " . $revision->timestamp
);
262 $this->debug( "-- Comment: " . $revision->comment
);
263 $this->debug( "-- Text: " . $revision->text
);
267 * Notify the callback function when a new <page> is reached.
268 * @param $title Title
270 function pageCallback( $title ) {
271 if( isset( $this->mPageCallback
) ) {
272 call_user_func( $this->mPageCallback
, $title );
277 * Notify the callback function when a </page> is closed.
278 * @param $title Title
279 * @param $origTitle Title
280 * @param $revCount Integer
281 * @param $sucCount Int: number of revisions for which callback returned true
282 * @param $pageInfo Array: associative array of page information
284 private function pageOutCallback( $title, $origTitle, $revCount, $sucCount, $pageInfo ) {
285 if( isset( $this->mPageOutCallback
) ) {
286 $args = func_get_args();
287 call_user_func_array( $this->mPageOutCallback
, $args );
292 * Notify the callback function of a revision
293 * @param $revision A WikiRevision object
295 private function revisionCallback( $revision ) {
296 if ( isset( $this->mRevisionCallback
) ) {
297 return call_user_func_array( $this->mRevisionCallback
,
298 array( $revision, $this ) );
305 * Notify the callback function of a new log item
306 * @param $revision A WikiRevision object
308 private function logItemCallback( $revision ) {
309 if ( isset( $this->mLogItemCallback
) ) {
310 return call_user_func_array( $this->mLogItemCallback
,
311 array( $revision, $this ) );
318 * Shouldn't something like this be built-in to XMLReader?
319 * Fetches text contents of the current element, assuming
320 * no sub-elements or such scary things.
324 private function nodeContents() {
325 if( $this->reader
->isEmptyElement
) {
329 while( $this->reader
->read() ) {
330 switch( $this->reader
->nodeType
) {
331 case XmlReader
::TEXT
:
332 case XmlReader
::SIGNIFICANT_WHITESPACE
:
333 $buffer .= $this->reader
->value
;
335 case XmlReader
::END_ELEMENT
:
340 $this->reader
->close();
346 /** Left in for debugging */
347 private function dumpElement() {
348 static $lookup = null;
350 $xmlReaderConstants = array(
365 "SIGNIFICANT_WHITESPACE",
372 foreach( $xmlReaderConstants as $name ) {
373 $lookup[constant("XmlReader::$name")] = $name;
378 $lookup[$this->reader
->nodeType
],
385 * Primary entry point
387 public function doImport() {
388 $this->reader
->read();
390 if ( $this->reader
->name
!= 'mediawiki' ) {
391 throw new MWException( "Expected <mediawiki> tag, got ".
392 $this->reader
->name
);
394 $this->debug( "<mediawiki> tag is correct." );
396 $this->debug( "Starting primary dump processing loop." );
398 $keepReading = $this->reader
->read();
400 while ( $keepReading ) {
401 $tag = $this->reader
->name
;
402 $type = $this->reader
->nodeType
;
404 if ( !wfRunHooks( 'ImportHandleToplevelXMLTag', $this ) ) {
406 } elseif ( $tag == 'mediawiki' && $type == XmlReader
::END_ELEMENT
) {
408 } elseif ( $tag == 'siteinfo' ) {
409 $this->handleSiteInfo();
410 } elseif ( $tag == 'page' ) {
412 } elseif ( $tag == 'logitem' ) {
413 $this->handleLogItem();
414 } elseif ( $tag != '#text' ) {
415 $this->warn( "Unhandled top-level XML tag $tag" );
421 $keepReading = $this->reader
->next();
423 $this->debug( "Skip" );
425 $keepReading = $this->reader
->read();
434 * @throws MWException
436 private function handleSiteInfo() {
437 // Site info is useful, but not actually used for dump imports.
438 // Includes a quick short-circuit to save performance.
439 if ( ! $this->mSiteInfoCallback
) {
440 $this->reader
->next();
443 throw new MWException( "SiteInfo tag is not yet handled, do not set mSiteInfoCallback" );
446 private function handleLogItem() {
447 $this->debug( "Enter log item handler." );
450 // Fields that can just be stuffed in the pageInfo object
451 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
452 'logtitle', 'params' );
454 while ( $this->reader
->read() ) {
455 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
456 $this->reader
->name
== 'logitem') {
460 $tag = $this->reader
->name
;
462 if ( !wfRunHooks( 'ImportHandleLogItemXMLTag',
463 $this, $logInfo ) ) {
465 } elseif ( in_array( $tag, $normalFields ) ) {
466 $logInfo[$tag] = $this->nodeContents();
467 } elseif ( $tag == 'contributor' ) {
468 $logInfo['contributor'] = $this->handleContributor();
469 } elseif ( $tag != '#text' ) {
470 $this->warn( "Unhandled log-item XML tag $tag" );
474 $this->processLogItem( $logInfo );
481 private function processLogItem( $logInfo ) {
482 $revision = new WikiRevision
;
484 $revision->setID( $logInfo['id'] );
485 $revision->setType( $logInfo['type'] );
486 $revision->setAction( $logInfo['action'] );
487 $revision->setTimestamp( $logInfo['timestamp'] );
488 $revision->setParams( $logInfo['params'] );
489 $revision->setTitle( Title
::newFromText( $logInfo['logtitle'] ) );
490 $revision->setNoUpdates( $this->mNoUpdates
);
492 if ( isset( $logInfo['comment'] ) ) {
493 $revision->setComment( $logInfo['comment'] );
496 if ( isset( $logInfo['contributor']['ip'] ) ) {
497 $revision->setUserIP( $logInfo['contributor']['ip'] );
499 if ( isset( $logInfo['contributor']['username'] ) ) {
500 $revision->setUserName( $logInfo['contributor']['username'] );
503 return $this->logItemCallback( $revision );
506 private function handlePage() {
508 $this->debug( "Enter page handler." );
509 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
511 // Fields that can just be stuffed in the pageInfo object
512 $normalFields = array( 'title', 'id', 'redirect', 'restrictions' );
517 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
518 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
519 $this->reader
->name
== 'page') {
523 $tag = $this->reader
->name
;
526 // The title is invalid, bail out of this page
528 } elseif ( !wfRunHooks( 'ImportHandlePageXMLTag', array( $this,
531 } elseif ( in_array( $tag, $normalFields ) ) {
532 $pageInfo[$tag] = $this->nodeContents();
533 if ( $tag == 'title' ) {
534 $title = $this->processTitle( $pageInfo['title'] );
541 $this->pageCallback( $title );
542 list( $pageInfo['_title'], $origTitle ) = $title;
544 } elseif ( $tag == 'revision' ) {
545 $this->handleRevision( $pageInfo );
546 } elseif ( $tag == 'upload' ) {
547 $this->handleUpload( $pageInfo );
548 } elseif ( $tag != '#text' ) {
549 $this->warn( "Unhandled page XML tag $tag" );
554 $this->pageOutCallback( $pageInfo['_title'], $origTitle,
555 $pageInfo['revisionCount'],
556 $pageInfo['successfulRevisionCount'],
563 private function handleRevision( &$pageInfo ) {
564 $this->debug( "Enter revision handler" );
565 $revisionInfo = array();
567 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'text' );
571 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
572 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
573 $this->reader
->name
== 'revision') {
577 $tag = $this->reader
->name
;
579 if ( !wfRunHooks( 'ImportHandleRevisionXMLTag', $this,
580 $pageInfo, $revisionInfo ) ) {
582 } elseif ( in_array( $tag, $normalFields ) ) {
583 $revisionInfo[$tag] = $this->nodeContents();
584 } elseif ( $tag == 'contributor' ) {
585 $revisionInfo['contributor'] = $this->handleContributor();
586 } elseif ( $tag != '#text' ) {
587 $this->warn( "Unhandled revision XML tag $tag" );
592 $pageInfo['revisionCount']++
;
593 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
594 $pageInfo['successfulRevisionCount']++
;
600 * @param $revisionInfo
603 private function processRevision( $pageInfo, $revisionInfo ) {
604 $revision = new WikiRevision
;
606 if( isset( $revisionInfo['id'] ) ) {
607 $revision->setID( $revisionInfo['id'] );
609 if ( isset( $revisionInfo['text'] ) ) {
610 $revision->setText( $revisionInfo['text'] );
612 $revision->setTitle( $pageInfo['_title'] );
614 if ( isset( $revisionInfo['timestamp'] ) ) {
615 $revision->setTimestamp( $revisionInfo['timestamp'] );
617 $revision->setTimestamp( wfTimestampNow() );
620 if ( isset( $revisionInfo['comment'] ) ) {
621 $revision->setComment( $revisionInfo['comment'] );
624 if ( isset( $revisionInfo['minor'] ) ) {
625 $revision->setMinor( true );
627 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
628 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
630 if ( isset( $revisionInfo['contributor']['username'] ) ) {
631 $revision->setUserName( $revisionInfo['contributor']['username'] );
633 $revision->setNoUpdates( $this->mNoUpdates
);
635 return $this->revisionCallback( $revision );
642 private function handleUpload( &$pageInfo ) {
643 $this->debug( "Enter upload handler" );
644 $uploadInfo = array();
646 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
647 'src', 'size', 'sha1base36', 'archivename', 'rel' );
651 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
652 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
653 $this->reader
->name
== 'upload') {
657 $tag = $this->reader
->name
;
659 if ( !wfRunHooks( 'ImportHandleUploadXMLTag', $this,
662 } elseif ( in_array( $tag, $normalFields ) ) {
663 $uploadInfo[$tag] = $this->nodeContents();
664 } elseif ( $tag == 'contributor' ) {
665 $uploadInfo['contributor'] = $this->handleContributor();
666 } elseif ( $tag == 'contents' ) {
667 $contents = $this->nodeContents();
668 $encoding = $this->reader
->getAttribute( 'encoding' );
669 if ( $encoding === 'base64' ) {
670 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
671 $uploadInfo['isTempSrc'] = true;
673 } elseif ( $tag != '#text' ) {
674 $this->warn( "Unhandled upload XML tag $tag" );
679 if ( $this->mImageBasePath
&& isset( $uploadInfo['rel'] ) ) {
680 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
681 if ( file_exists( $path ) ) {
682 $uploadInfo['fileSrc'] = $path;
683 $uploadInfo['isTempSrc'] = false;
687 if ( $this->mImportUploads
) {
688 return $this->processUpload( $pageInfo, $uploadInfo );
696 private function dumpTemp( $contents ) {
697 $filename = tempnam( wfTempDir(), 'importupload' );
698 file_put_contents( $filename, $contents );
707 private function processUpload( $pageInfo, $uploadInfo ) {
708 $revision = new WikiRevision
;
709 $text = isset( $uploadInfo['text'] ) ?
$uploadInfo['text'] : '';
711 $revision->setTitle( $pageInfo['_title'] );
712 $revision->setID( $pageInfo['id'] );
713 $revision->setTimestamp( $uploadInfo['timestamp'] );
714 $revision->setText( $text );
715 $revision->setFilename( $uploadInfo['filename'] );
716 if ( isset( $uploadInfo['archivename'] ) ) {
717 $revision->setArchiveName( $uploadInfo['archivename'] );
719 $revision->setSrc( $uploadInfo['src'] );
720 if ( isset( $uploadInfo['fileSrc'] ) ) {
721 $revision->setFileSrc( $uploadInfo['fileSrc'],
722 !empty( $uploadInfo['isTempSrc'] ) );
724 if ( isset( $uploadInfo['sha1base36'] ) ) {
725 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
727 $revision->setSize( intval( $uploadInfo['size'] ) );
728 $revision->setComment( $uploadInfo['comment'] );
730 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
731 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
733 if ( isset( $uploadInfo['contributor']['username'] ) ) {
734 $revision->setUserName( $uploadInfo['contributor']['username'] );
736 $revision->setNoUpdates( $this->mNoUpdates
);
738 return call_user_func( $this->mUploadCallback
, $revision );
744 private function handleContributor() {
745 $fields = array( 'id', 'ip', 'username' );
748 while ( $this->reader
->read() ) {
749 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
750 $this->reader
->name
== 'contributor') {
754 $tag = $this->reader
->name
;
756 if ( in_array( $tag, $fields ) ) {
757 $info[$tag] = $this->nodeContents();
765 * @param $text string
766 * @return Array or false
768 private function processTitle( $text ) {
769 global $wgCommandLineMode;
772 $origTitle = Title
::newFromText( $workTitle );
774 if( !is_null( $this->mTargetNamespace
) && !is_null( $origTitle ) ) {
775 $title = Title
::makeTitle( $this->mTargetNamespace
,
776 $origTitle->getDBkey() );
778 $title = Title
::newFromText( $workTitle );
781 if( is_null( $title ) ) {
782 # Invalid page title? Ignore the page
783 $this->notice( "Skipping invalid page title '$workTitle'" );
785 } elseif( $title->getInterwiki() != '' ) {
786 $this->notice( "Skipping interwiki page title '$workTitle'" );
788 } elseif( !$title->userCan( 'edit' ) && !$wgCommandLineMode ) {
789 # Do not import if the importing wiki user cannot edit this page
790 $this->notice( wfMessage( 'import-error-edit', $title->getText() )->text() );
792 } elseif( !$title->exists() && !$title->userCan( 'create' ) && !$wgCommandLineMode ) {
793 # Do not import if the importing wiki user cannot create this page
794 $this->notice( wfMessage( 'import-error-create', $title->getText() )->text() );
798 return array( $title, $origTitle );
802 /** This is a horrible hack used to keep source compatibility */
803 class UploadSourceAdapter
{
804 static $sourceRegistrations = array();
814 static function registerSource( $source ) {
815 $id = wfGenerateToken();
817 self
::$sourceRegistrations[$id] = $source;
826 * @param $opened_path
829 function stream_open( $path, $mode, $options, &$opened_path ) {
830 $url = parse_url($path);
833 if ( !isset( self
::$sourceRegistrations[$id] ) ) {
837 $this->mSource
= self
::$sourceRegistrations[$id];
846 function stream_read( $count ) {
850 while ( !$leave && !$this->mSource
->atEnd() &&
851 strlen($this->mBuffer
) < $count ) {
852 $read = $this->mSource
->readChunk();
854 if ( !strlen($read) ) {
858 $this->mBuffer
.= $read;
861 if ( strlen($this->mBuffer
) ) {
862 $return = substr( $this->mBuffer
, 0, $count );
863 $this->mBuffer
= substr( $this->mBuffer
, $count );
866 $this->mPosition +
= strlen($return);
875 function stream_write( $data ) {
882 function stream_tell() {
883 return $this->mPosition
;
889 function stream_eof() {
890 return $this->mSource
->atEnd();
896 function url_stat() {
899 $result['dev'] = $result[0] = 0;
900 $result['ino'] = $result[1] = 0;
901 $result['mode'] = $result[2] = 0;
902 $result['nlink'] = $result[3] = 0;
903 $result['uid'] = $result[4] = 0;
904 $result['gid'] = $result[5] = 0;
905 $result['rdev'] = $result[6] = 0;
906 $result['size'] = $result[7] = 0;
907 $result['atime'] = $result[8] = 0;
908 $result['mtime'] = $result[9] = 0;
909 $result['ctime'] = $result[10] = 0;
910 $result['blksize'] = $result[11] = 0;
911 $result['blocks'] = $result[12] = 0;
917 class XMLReader2
extends XMLReader
{
920 * @return bool|string
922 function nodeContents() {
923 if( $this->isEmptyElement
) {
927 while( $this->read() ) {
928 switch( $this->nodeType
) {
929 case XmlReader
::TEXT
:
930 case XmlReader
::SIGNIFICANT_WHITESPACE
:
931 $buffer .= $this->value
;
933 case XmlReader
::END_ELEMENT
:
937 return $this->close();
942 * @todo document (e.g. one-sentence class description).
943 * @ingroup SpecialPage
946 var $importer = null;
953 var $timestamp = "20010115000000";
963 var $sha1base36 = false;
965 var $archiveName = '';
967 private $mNoUpdates = false;
971 * @throws MWException
973 function setTitle( $title ) {
974 if( is_object( $title ) ) {
975 $this->title
= $title;
976 } elseif( is_null( $title ) ) {
977 throw new MWException( "WikiRevision given a null title in import. You may need to adjust \$wgLegalTitleChars." );
979 throw new MWException( "WikiRevision given non-object title in import." );
986 function setID( $id ) {
993 function setTimestamp( $ts ) {
994 # 2003-08-05T18:30:02Z
995 $this->timestamp
= wfTimestamp( TS_MW
, $ts );
1001 function setUsername( $user ) {
1002 $this->user_text
= $user;
1008 function setUserIP( $ip ) {
1009 $this->user_text
= $ip;
1015 function setText( $text ) {
1016 $this->text
= $text;
1022 function setComment( $text ) {
1023 $this->comment
= $text;
1029 function setMinor( $minor ) {
1030 $this->minor
= (bool)$minor;
1036 function setSrc( $src ) {
1044 function setFileSrc( $src, $isTemp ) {
1045 $this->fileSrc
= $src;
1046 $this->fileIsTemp
= $isTemp;
1050 * @param $sha1base36
1052 function setSha1Base36( $sha1base36 ) {
1053 $this->sha1base36
= $sha1base36;
1059 function setFilename( $filename ) {
1060 $this->filename
= $filename;
1064 * @param $archiveName
1066 function setArchiveName( $archiveName ) {
1067 $this->archiveName
= $archiveName;
1073 function setSize( $size ) {
1074 $this->size
= intval( $size );
1080 function setType( $type ) {
1081 $this->type
= $type;
1087 function setAction( $action ) {
1088 $this->action
= $action;
1094 function setParams( $params ) {
1095 $this->params
= $params;
1101 public function setNoUpdates( $noupdates ) {
1102 $this->mNoUpdates
= $noupdates;
1108 function getTitle() {
1109 return $this->title
;
1122 function getTimestamp() {
1123 return $this->timestamp
;
1129 function getUser() {
1130 return $this->user_text
;
1136 function getText() {
1143 function getComment() {
1144 return $this->comment
;
1150 function getMinor() {
1151 return $this->minor
;
1162 * @return bool|String
1164 function getSha1() {
1165 if ( $this->sha1base36
) {
1166 return wfBaseConvert( $this->sha1base36
, 36, 16 );
1174 function getFileSrc() {
1175 return $this->fileSrc
;
1181 function isTempSrc() {
1182 return $this->isTemp
;
1188 function getFilename() {
1189 return $this->filename
;
1195 function getArchiveName() {
1196 return $this->archiveName
;
1202 function getSize() {
1209 function getType() {
1216 function getAction() {
1217 return $this->action
;
1223 function getParams() {
1224 return $this->params
;
1230 function importOldRevision() {
1231 $dbw = wfGetDB( DB_MASTER
);
1233 # Sneak a single revision into place
1234 $user = User
::newFromName( $this->getUser() );
1236 $userId = intval( $user->getId() );
1237 $userText = $user->getName();
1241 $userText = $this->getUser();
1242 $userObj = new User
;
1245 // avoid memory leak...?
1246 $linkCache = LinkCache
::singleton();
1247 $linkCache->clear();
1249 $page = WikiPage
::factory( $this->title
);
1250 if( !$page->exists() ) {
1251 # must create the page...
1252 $pageId = $page->insertOn( $dbw );
1254 $oldcountable = null;
1256 $pageId = $page->getId();
1259 $prior = $dbw->selectField( 'revision', '1',
1260 array( 'rev_page' => $pageId,
1261 'rev_timestamp' => $dbw->timestamp( $this->timestamp
),
1262 'rev_user_text' => $userText,
1263 'rev_comment' => $this->getComment() ),
1267 // @todo FIXME: This could fail slightly for multiple matches :P
1268 wfDebug( __METHOD__
. ": skipping existing revision for [[" .
1269 $this->title
->getPrefixedText() . "]], timestamp " . $this->timestamp
. "\n" );
1272 $oldcountable = $page->isCountable();
1275 # @todo FIXME: Use original rev_id optionally (better for backups)
1277 $revision = new Revision( array(
1279 'text' => $this->getText(),
1280 'comment' => $this->getComment(),
1282 'user_text' => $userText,
1283 'timestamp' => $this->timestamp
,
1284 'minor_edit' => $this->minor
,
1286 $revision->insertOn( $dbw );
1287 $changed = $page->updateIfNewerOn( $dbw, $revision );
1289 if ( $changed !== false && !$this->mNoUpdates
) {
1290 wfDebug( __METHOD__
. ": running updates\n" );
1291 $page->doEditUpdates( $revision, $userObj, array( 'created' => $created, 'oldcountable' => $oldcountable ) );
1300 function importLogItem() {
1301 $dbw = wfGetDB( DB_MASTER
);
1302 # @todo FIXME: This will not record autoblocks
1303 if( !$this->getTitle() ) {
1304 wfDebug( __METHOD__
. ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1305 $this->timestamp
. "\n" );
1308 # Check if it exists already
1309 // @todo FIXME: Use original log ID (better for backups)
1310 $prior = $dbw->selectField( 'logging', '1',
1311 array( 'log_type' => $this->getType(),
1312 'log_action' => $this->getAction(),
1313 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1314 'log_namespace' => $this->getTitle()->getNamespace(),
1315 'log_title' => $this->getTitle()->getDBkey(),
1316 'log_comment' => $this->getComment(),
1317 #'log_user_text' => $this->user_text,
1318 'log_params' => $this->params
),
1321 // @todo FIXME: This could fail slightly for multiple matches :P
1323 wfDebug( __METHOD__
. ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp " .
1324 $this->timestamp
. "\n" );
1327 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1329 'log_id' => $log_id,
1330 'log_type' => $this->type
,
1331 'log_action' => $this->action
,
1332 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1333 'log_user' => User
::idFromName( $this->user_text
),
1334 #'log_user_text' => $this->user_text,
1335 'log_namespace' => $this->getTitle()->getNamespace(),
1336 'log_title' => $this->getTitle()->getDBkey(),
1337 'log_comment' => $this->getComment(),
1338 'log_params' => $this->params
1340 $dbw->insert( 'logging', $data, __METHOD__
);
1346 function importUpload() {
1348 $archiveName = $this->getArchiveName();
1349 if ( $archiveName ) {
1350 wfDebug( __METHOD__
. "Importing archived file as $archiveName\n" );
1351 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1352 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1354 $file = wfLocalFile( $this->getTitle() );
1355 wfDebug( __METHOD__
. 'Importing new file as ' . $file->getName() . "\n" );
1356 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1357 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1358 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1359 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1360 wfDebug( __METHOD__
. "File already exists; importing as $archiveName\n" );
1364 wfDebug( __METHOD__
. ': Bad file for ' . $this->getTitle() . "\n" );
1368 # Get the file source or download if necessary
1369 $source = $this->getFileSrc();
1370 $flags = $this->isTempSrc() ? File
::DELETE_SOURCE
: 0;
1372 $source = $this->downloadSource();
1373 $flags |
= File
::DELETE_SOURCE
;
1376 wfDebug( __METHOD__
. ": Could not fetch remote file.\n" );
1379 $sha1 = $this->getSha1();
1380 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1381 if ( $flags & File
::DELETE_SOURCE
) {
1382 # Broken file; delete it if it is a temporary file
1385 wfDebug( __METHOD__
. ": Corrupt file $source.\n" );
1389 $user = User
::newFromName( $this->user_text
);
1391 # Do the actual upload
1392 if ( $archiveName ) {
1393 $status = $file->uploadOld( $source, $archiveName,
1394 $this->getTimestamp(), $this->getComment(), $user, $flags );
1396 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1397 $flags, false, $this->getTimestamp(), $user );
1400 if ( $status->isGood() ) {
1401 wfDebug( __METHOD__
. ": Succesful\n" );
1404 wfDebug( __METHOD__
. ': failed: ' . $status->getXml() . "\n" );
1410 * @return bool|string
1412 function downloadSource() {
1413 global $wgEnableUploads;
1414 if( !$wgEnableUploads ) {
1418 $tempo = tempnam( wfTempDir(), 'download' );
1419 $f = fopen( $tempo, 'wb' );
1421 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1426 $src = $this->getSrc();
1427 $data = Http
::get( $src );
1429 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1435 fwrite( $f, $data );
1444 * @todo document (e.g. one-sentence class description).
1445 * @ingroup SpecialPage
1447 class ImportStringSource
{
1448 function __construct( $string ) {
1449 $this->mString
= $string;
1450 $this->mRead
= false;
1457 return $this->mRead
;
1461 * @return bool|string
1463 function readChunk() {
1464 if( $this->atEnd() ) {
1467 $this->mRead
= true;
1468 return $this->mString
;
1473 * @todo document (e.g. one-sentence class description).
1474 * @ingroup SpecialPage
1476 class ImportStreamSource
{
1477 function __construct( $handle ) {
1478 $this->mHandle
= $handle;
1485 return feof( $this->mHandle
);
1491 function readChunk() {
1492 return fread( $this->mHandle
, 32768 );
1496 * @param $filename string
1499 static function newFromFile( $filename ) {
1500 wfSuppressWarnings();
1501 $file = fopen( $filename, 'rt' );
1502 wfRestoreWarnings();
1504 return Status
::newFatal( "importcantopen" );
1506 return Status
::newGood( new ImportStreamSource( $file ) );
1510 * @param $fieldname string
1513 static function newFromUpload( $fieldname = "xmlimport" ) {
1514 $upload =& $_FILES[$fieldname];
1516 if( !isset( $upload ) ||
!$upload['name'] ) {
1517 return Status
::newFatal( 'importnofile' );
1519 if( !empty( $upload['error'] ) ) {
1520 switch($upload['error']){
1521 case 1: # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1522 return Status
::newFatal( 'importuploaderrorsize' );
1523 case 2: # The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
1524 return Status
::newFatal( 'importuploaderrorsize' );
1525 case 3: # The uploaded file was only partially uploaded
1526 return Status
::newFatal( 'importuploaderrorpartial' );
1527 case 6: #Missing a temporary folder.
1528 return Status
::newFatal( 'importuploaderrortemp' );
1529 # case else: # Currently impossible
1533 $fname = $upload['tmp_name'];
1534 if( is_uploaded_file( $fname ) ) {
1535 return ImportStreamSource
::newFromFile( $fname );
1537 return Status
::newFatal( 'importnofile' );
1543 * @param $method string
1546 static function newFromURL( $url, $method = 'GET' ) {
1547 wfDebug( __METHOD__
. ": opening $url\n" );
1548 # Use the standard HTTP fetch function; it times out
1549 # quicker and sorts out user-agent problems which might
1550 # otherwise prevent importing from large sites, such
1551 # as the Wikimedia cluster, etc.
1552 $data = Http
::request( $method, $url, array( 'followRedirects' => true ) );
1553 if( $data !== false ) {
1555 fwrite( $file, $data );
1558 return Status
::newGood( new ImportStreamSource( $file ) );
1560 return Status
::newFatal( 'importcantopen' );
1567 * @param $history bool
1568 * @param $templates bool
1569 * @param $pageLinkDepth int
1572 public static function newFromInterwiki( $interwiki, $page, $history = false, $templates = false, $pageLinkDepth = 0 ) {
1574 return Status
::newFatal( 'import-noarticle' );
1576 $link = Title
::newFromText( "$interwiki:Special:Export/$page" );
1577 if( is_null( $link ) ||
$link->getInterwiki() == '' ) {
1578 return Status
::newFatal( 'importbadinterwiki' );
1581 if ( $history ) $params['history'] = 1;
1582 if ( $templates ) $params['templates'] = 1;
1583 if ( $pageLinkDepth ) $params['pagelink-depth'] = $pageLinkDepth;
1584 $url = $link->getFullUrl( $params );
1585 # For interwikis, use POST to avoid redirects.
1586 return ImportStreamSource
::newFromURL( $url, "POST" );