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
44 function __construct( $source ) {
45 $this->reader
= new XMLReader();
47 stream_wrapper_register( 'uploadsource', 'UploadSourceAdapter' );
48 $id = UploadSourceAdapter
::registerSource( $source );
49 if (defined( 'LIBXML_PARSEHUGE' ) ) {
50 $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" );
91 function setDebug( $debug ) {
92 $this->mDebug
= $debug;
96 * Set 'no updates' mode. In this mode, the link tables will not be updated by the importer
98 function setNoUpdates( $noupdates ) {
99 $this->mNoUpdates
= $noupdates;
103 * Sets the action to perform as each new page in the stream is reached.
104 * @param $callback callback
107 public function setPageCallback( $callback ) {
108 $previous = $this->mPageCallback
;
109 $this->mPageCallback
= $callback;
114 * Sets the action to perform as each page in the stream is completed.
115 * Callback accepts the page title (as a Title object), a second object
116 * with the original title form (in case it's been overridden into a
117 * local namespace), and a count of revisions.
119 * @param $callback callback
122 public function setPageOutCallback( $callback ) {
123 $previous = $this->mPageOutCallback
;
124 $this->mPageOutCallback
= $callback;
129 * Sets the action to perform as each page revision is reached.
130 * @param $callback callback
133 public function setRevisionCallback( $callback ) {
134 $previous = $this->mRevisionCallback
;
135 $this->mRevisionCallback
= $callback;
140 * Sets the action to perform as each file upload version is reached.
141 * @param $callback callback
144 public function setUploadCallback( $callback ) {
145 $previous = $this->mUploadCallback
;
146 $this->mUploadCallback
= $callback;
151 * Sets the action to perform as each log item reached.
152 * @param $callback callback
155 public function setLogItemCallback( $callback ) {
156 $previous = $this->mLogItemCallback
;
157 $this->mLogItemCallback
= $callback;
162 * Sets the action to perform when site info is encountered
163 * @param $callback callback
166 public function setSiteInfoCallback( $callback ) {
167 $previous = $this->mSiteInfoCallback
;
168 $this->mSiteInfoCallback
= $callback;
173 * Set a target namespace to override the defaults
175 public function setTargetNamespace( $namespace ) {
176 if( is_null( $namespace ) ) {
177 // Don't override namespaces
178 $this->mTargetNamespace
= null;
179 } elseif( $namespace >= 0 ) {
180 // @todo FIXME: Check for validity
181 $this->mTargetNamespace
= intval( $namespace );
190 public function setImageBasePath( $dir ) {
191 $this->mImageBasePath
= $dir;
193 public function setImportUploads( $import ) {
194 $this->mImportUploads
= $import;
198 * Default per-revision callback, performs the import.
199 * @param $revision WikiRevision
201 public function importRevision( $revision ) {
202 $dbw = wfGetDB( DB_MASTER
);
203 return $dbw->deadlockLoop( array( $revision, 'importOldRevision' ) );
207 * Default per-revision callback, performs the import.
208 * @param $rev WikiRevision
210 public function importLogItem( $rev ) {
211 $dbw = wfGetDB( DB_MASTER
);
212 return $dbw->deadlockLoop( array( $rev, 'importLogItem' ) );
218 public function importUpload( $revision ) {
219 $dbw = wfGetDB( DB_MASTER
);
220 return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
224 * Mostly for hook use
226 public function finishImportPage( $title, $origTitle, $revCount, $sRevCount, $pageInfo ) {
227 $args = func_get_args();
228 return wfRunHooks( 'AfterImportPage', $args );
232 * Alternate per-revision callback, for debugging.
233 * @param $revision WikiRevision
235 public function debugRevisionHandler( &$revision ) {
236 $this->debug( "Got revision:" );
237 if( is_object( $revision->title
) ) {
238 $this->debug( "-- Title: " . $revision->title
->getPrefixedText() );
240 $this->debug( "-- Title: <invalid>" );
242 $this->debug( "-- User: " . $revision->user_text
);
243 $this->debug( "-- Timestamp: " . $revision->timestamp
);
244 $this->debug( "-- Comment: " . $revision->comment
);
245 $this->debug( "-- Text: " . $revision->text
);
249 * Notify the callback function when a new <page> is reached.
250 * @param $title Title
252 function pageCallback( $title ) {
253 if( isset( $this->mPageCallback
) ) {
254 call_user_func( $this->mPageCallback
, $title );
259 * Notify the callback function when a </page> is closed.
260 * @param $title Title
261 * @param $origTitle Title
262 * @param $revCount Integer
263 * @param $sucCount Int: number of revisions for which callback returned true
264 * @param $pageInfo Array: associative array of page information
266 private function pageOutCallback( $title, $origTitle, $revCount, $sucCount, $pageInfo ) {
267 if( isset( $this->mPageOutCallback
) ) {
268 $args = func_get_args();
269 call_user_func_array( $this->mPageOutCallback
, $args );
274 * Notify the callback function of a revision
275 * @param $revision A WikiRevision object
277 private function revisionCallback( $revision ) {
278 if ( isset( $this->mRevisionCallback
) ) {
279 return call_user_func_array( $this->mRevisionCallback
,
280 array( $revision, $this ) );
287 * Notify the callback function of a new log item
288 * @param $revision A WikiRevision object
290 private function logItemCallback( $revision ) {
291 if ( isset( $this->mLogItemCallback
) ) {
292 return call_user_func_array( $this->mLogItemCallback
,
293 array( $revision, $this ) );
300 * Shouldn't something like this be built-in to XMLReader?
301 * Fetches text contents of the current element, assuming
302 * no sub-elements or such scary things.
306 private function nodeContents() {
307 if( $this->reader
->isEmptyElement
) {
311 while( $this->reader
->read() ) {
312 switch( $this->reader
->nodeType
) {
313 case XmlReader
::TEXT
:
314 case XmlReader
::SIGNIFICANT_WHITESPACE
:
315 $buffer .= $this->reader
->value
;
317 case XmlReader
::END_ELEMENT
:
322 $this->reader
->close();
328 /** Left in for debugging */
329 private function dumpElement() {
330 static $lookup = null;
332 $xmlReaderConstants = array(
347 "SIGNIFICANT_WHITESPACE",
354 foreach( $xmlReaderConstants as $name ) {
355 $lookup[constant("XmlReader::$name")] = $name;
360 $lookup[$this->reader
->nodeType
],
367 * Primary entry point
369 public function doImport() {
370 $this->reader
->read();
372 if ( $this->reader
->name
!= 'mediawiki' ) {
373 throw new MWException( "Expected <mediawiki> tag, got ".
374 $this->reader
->name
);
376 $this->debug( "<mediawiki> tag is correct." );
378 $this->debug( "Starting primary dump processing loop." );
380 $keepReading = $this->reader
->read();
382 while ( $keepReading ) {
383 $tag = $this->reader
->name
;
384 $type = $this->reader
->nodeType
;
386 if ( !wfRunHooks( 'ImportHandleToplevelXMLTag', $this ) ) {
388 } elseif ( $tag == 'mediawiki' && $type == XmlReader
::END_ELEMENT
) {
390 } elseif ( $tag == 'siteinfo' ) {
391 $this->handleSiteInfo();
392 } elseif ( $tag == 'page' ) {
394 } elseif ( $tag == 'logitem' ) {
395 $this->handleLogItem();
396 } elseif ( $tag != '#text' ) {
397 $this->warn( "Unhandled top-level XML tag $tag" );
403 $keepReading = $this->reader
->next();
405 $this->debug( "Skip" );
407 $keepReading = $this->reader
->read();
414 private function handleSiteInfo() {
415 // Site info is useful, but not actually used for dump imports.
416 // Includes a quick short-circuit to save performance.
417 if ( ! $this->mSiteInfoCallback
) {
418 $this->reader
->next();
421 throw new MWException( "SiteInfo tag is not yet handled, do not set mSiteInfoCallback" );
424 private function handleLogItem() {
425 $this->debug( "Enter log item handler." );
428 // Fields that can just be stuffed in the pageInfo object
429 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
430 'logtitle', 'params' );
432 while ( $this->reader
->read() ) {
433 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
434 $this->reader
->name
== 'logitem') {
438 $tag = $this->reader
->name
;
440 if ( !wfRunHooks( 'ImportHandleLogItemXMLTag',
441 $this, $logInfo ) ) {
443 } elseif ( in_array( $tag, $normalFields ) ) {
444 $logInfo[$tag] = $this->nodeContents();
445 } elseif ( $tag == 'contributor' ) {
446 $logInfo['contributor'] = $this->handleContributor();
447 } elseif ( $tag != '#text' ) {
448 $this->warn( "Unhandled log-item XML tag $tag" );
452 $this->processLogItem( $logInfo );
455 private function processLogItem( $logInfo ) {
456 $revision = new WikiRevision
;
458 $revision->setID( $logInfo['id'] );
459 $revision->setType( $logInfo['type'] );
460 $revision->setAction( $logInfo['action'] );
461 $revision->setTimestamp( $logInfo['timestamp'] );
462 $revision->setParams( $logInfo['params'] );
463 $revision->setTitle( Title
::newFromText( $logInfo['logtitle'] ) );
464 $revision->setNoUpdates( $this->mNoUpdates
);
466 if ( isset( $logInfo['comment'] ) ) {
467 $revision->setComment( $logInfo['comment'] );
470 if ( isset( $logInfo['contributor']['ip'] ) ) {
471 $revision->setUserIP( $logInfo['contributor']['ip'] );
473 if ( isset( $logInfo['contributor']['username'] ) ) {
474 $revision->setUserName( $logInfo['contributor']['username'] );
477 return $this->logItemCallback( $revision );
480 private function handlePage() {
482 $this->debug( "Enter page handler." );
483 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
485 // Fields that can just be stuffed in the pageInfo object
486 $normalFields = array( 'title', 'id', 'redirect', 'restrictions' );
491 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
492 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
493 $this->reader
->name
== 'page') {
497 $tag = $this->reader
->name
;
500 // The title is invalid, bail out of this page
502 } elseif ( !wfRunHooks( 'ImportHandlePageXMLTag', array( $this,
505 } elseif ( in_array( $tag, $normalFields ) ) {
506 $pageInfo[$tag] = $this->nodeContents();
507 if ( $tag == 'title' ) {
508 $title = $this->processTitle( $pageInfo['title'] );
515 $this->pageCallback( $title );
516 list( $pageInfo['_title'], $origTitle ) = $title;
518 } elseif ( $tag == 'revision' ) {
519 $this->handleRevision( $pageInfo );
520 } elseif ( $tag == 'upload' ) {
521 $this->handleUpload( $pageInfo );
522 } elseif ( $tag != '#text' ) {
523 $this->warn( "Unhandled page XML tag $tag" );
528 $this->pageOutCallback( $pageInfo['_title'], $origTitle,
529 $pageInfo['revisionCount'],
530 $pageInfo['successfulRevisionCount'],
534 private function handleRevision( &$pageInfo ) {
535 $this->debug( "Enter revision handler" );
536 $revisionInfo = array();
538 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'text' );
542 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
543 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
544 $this->reader
->name
== 'revision') {
548 $tag = $this->reader
->name
;
550 if ( !wfRunHooks( 'ImportHandleRevisionXMLTag', $this,
551 $pageInfo, $revisionInfo ) ) {
553 } elseif ( in_array( $tag, $normalFields ) ) {
554 $revisionInfo[$tag] = $this->nodeContents();
555 } elseif ( $tag == 'contributor' ) {
556 $revisionInfo['contributor'] = $this->handleContributor();
557 } elseif ( $tag != '#text' ) {
558 $this->warn( "Unhandled revision XML tag $tag" );
563 $pageInfo['revisionCount']++
;
564 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
565 $pageInfo['successfulRevisionCount']++
;
569 private function processRevision( $pageInfo, $revisionInfo ) {
570 $revision = new WikiRevision
;
572 if( isset( $revisionInfo['id'] ) ) {
573 $revision->setID( $revisionInfo['id'] );
575 if ( isset( $revisionInfo['text'] ) ) {
576 $revision->setText( $revisionInfo['text'] );
578 $revision->setTitle( $pageInfo['_title'] );
580 if ( isset( $revisionInfo['timestamp'] ) ) {
581 $revision->setTimestamp( $revisionInfo['timestamp'] );
583 $revision->setTimestamp( wfTimestampNow() );
586 if ( isset( $revisionInfo['comment'] ) ) {
587 $revision->setComment( $revisionInfo['comment'] );
590 if ( isset( $revisionInfo['minor'] ) ) {
591 $revision->setMinor( true );
593 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
594 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
596 if ( isset( $revisionInfo['contributor']['username'] ) ) {
597 $revision->setUserName( $revisionInfo['contributor']['username'] );
599 $revision->setNoUpdates( $this->mNoUpdates
);
601 return $this->revisionCallback( $revision );
604 private function handleUpload( &$pageInfo ) {
605 $this->debug( "Enter upload handler" );
606 $uploadInfo = array();
608 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
609 'src', 'size', 'sha1base36', 'archivename', 'rel' );
613 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
614 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
615 $this->reader
->name
== 'upload') {
619 $tag = $this->reader
->name
;
621 if ( !wfRunHooks( 'ImportHandleUploadXMLTag', $this,
624 } elseif ( in_array( $tag, $normalFields ) ) {
625 $uploadInfo[$tag] = $this->nodeContents();
626 } elseif ( $tag == 'contributor' ) {
627 $uploadInfo['contributor'] = $this->handleContributor();
628 } elseif ( $tag == 'contents' ) {
629 $contents = $this->nodeContents();
630 $encoding = $this->reader
->getAttribute( 'encoding' );
631 if ( $encoding === 'base64' ) {
632 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
633 $uploadInfo['isTempSrc'] = true;
635 } elseif ( $tag != '#text' ) {
636 $this->warn( "Unhandled upload XML tag $tag" );
641 if ( $this->mImageBasePath
&& isset( $uploadInfo['rel'] ) ) {
642 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
643 if ( file_exists( $path ) ) {
644 $uploadInfo['fileSrc'] = $path;
645 $uploadInfo['isTempSrc'] = false;
649 if ( $this->mImportUploads
) {
650 return $this->processUpload( $pageInfo, $uploadInfo );
654 private function dumpTemp( $contents ) {
655 $filename = tempnam( wfTempDir(), 'importupload' );
656 file_put_contents( $filename, $contents );
661 private function processUpload( $pageInfo, $uploadInfo ) {
662 $revision = new WikiRevision
;
663 $text = isset( $uploadInfo['text'] ) ?
$uploadInfo['text'] : '';
665 $revision->setTitle( $pageInfo['_title'] );
666 $revision->setID( $pageInfo['id'] );
667 $revision->setTimestamp( $uploadInfo['timestamp'] );
668 $revision->setText( $text );
669 $revision->setFilename( $uploadInfo['filename'] );
670 if ( isset( $uploadInfo['archivename'] ) ) {
671 $revision->setArchiveName( $uploadInfo['archivename'] );
673 $revision->setSrc( $uploadInfo['src'] );
674 if ( isset( $uploadInfo['fileSrc'] ) ) {
675 $revision->setFileSrc( $uploadInfo['fileSrc'],
676 !empty( $uploadInfo['isTempSrc'] ) );
678 if ( isset( $uploadInfo['sha1base36'] ) ) {
679 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
681 $revision->setSize( intval( $uploadInfo['size'] ) );
682 $revision->setComment( $uploadInfo['comment'] );
684 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
685 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
687 if ( isset( $uploadInfo['contributor']['username'] ) ) {
688 $revision->setUserName( $uploadInfo['contributor']['username'] );
690 $revision->setNoUpdates( $this->mNoUpdates
);
692 return call_user_func( $this->mUploadCallback
, $revision );
695 private function handleContributor() {
696 $fields = array( 'id', 'ip', 'username' );
699 while ( $this->reader
->read() ) {
700 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
701 $this->reader
->name
== 'contributor') {
705 $tag = $this->reader
->name
;
707 if ( in_array( $tag, $fields ) ) {
708 $info[$tag] = $this->nodeContents();
716 * @return Array or false
718 private function processTitle( $text ) {
719 global $wgCommandLineMode;
722 $origTitle = Title
::newFromText( $workTitle );
724 if( !is_null( $this->mTargetNamespace
) && !is_null( $origTitle ) ) {
725 $title = Title
::makeTitle( $this->mTargetNamespace
,
726 $origTitle->getDBkey() );
728 $title = Title
::newFromText( $workTitle );
731 if( is_null( $title ) ) {
732 # Invalid page title? Ignore the page
733 $this->notice( "Skipping invalid page title '$workTitle'" );
735 } elseif( $title->getInterwiki() != '' ) {
736 $this->notice( "Skipping interwiki page title '$workTitle'" );
738 } elseif( !$title->userCan( 'edit' ) && !$wgCommandLineMode ) {
739 # Do not import if the importing wiki user cannot edit this page
740 $this->notice( wfMessage( 'import-error-edit', $title->getText() )->text() );
742 } elseif( !$title->exists() && !$title->userCan( 'create' ) && !$wgCommandLineMode ) {
743 # Do not import if the importing wiki user cannot create this page
744 $this->notice( wfMessage( 'import-error-create', $title->getText() )->text() );
748 return array( $title, $origTitle );
752 /** This is a horrible hack used to keep source compatibility */
753 class UploadSourceAdapter
{
754 static $sourceRegistrations = array();
760 static function registerSource( $source ) {
761 $id = wfGenerateToken();
763 self
::$sourceRegistrations[$id] = $source;
768 function stream_open( $path, $mode, $options, &$opened_path ) {
769 $url = parse_url($path);
772 if ( !isset( self
::$sourceRegistrations[$id] ) ) {
776 $this->mSource
= self
::$sourceRegistrations[$id];
781 function stream_read( $count ) {
785 while ( !$leave && !$this->mSource
->atEnd() &&
786 strlen($this->mBuffer
) < $count ) {
787 $read = $this->mSource
->readChunk();
789 if ( !strlen($read) ) {
793 $this->mBuffer
.= $read;
796 if ( strlen($this->mBuffer
) ) {
797 $return = substr( $this->mBuffer
, 0, $count );
798 $this->mBuffer
= substr( $this->mBuffer
, $count );
801 $this->mPosition +
= strlen($return);
806 function stream_write( $data ) {
810 function stream_tell() {
811 return $this->mPosition
;
814 function stream_eof() {
815 return $this->mSource
->atEnd();
818 function url_stat() {
821 $result['dev'] = $result[0] = 0;
822 $result['ino'] = $result[1] = 0;
823 $result['mode'] = $result[2] = 0;
824 $result['nlink'] = $result[3] = 0;
825 $result['uid'] = $result[4] = 0;
826 $result['gid'] = $result[5] = 0;
827 $result['rdev'] = $result[6] = 0;
828 $result['size'] = $result[7] = 0;
829 $result['atime'] = $result[8] = 0;
830 $result['mtime'] = $result[9] = 0;
831 $result['ctime'] = $result[10] = 0;
832 $result['blksize'] = $result[11] = 0;
833 $result['blocks'] = $result[12] = 0;
839 class XMLReader2
extends XMLReader
{
840 function nodeContents() {
841 if( $this->isEmptyElement
) {
845 while( $this->read() ) {
846 switch( $this->nodeType
) {
847 case XmlReader
::TEXT
:
848 case XmlReader
::SIGNIFICANT_WHITESPACE
:
849 $buffer .= $this->value
;
851 case XmlReader
::END_ELEMENT
:
855 return $this->close();
860 * @todo document (e.g. one-sentence class description).
861 * @ingroup SpecialPage
864 var $importer = null;
867 var $timestamp = "20010115000000";
877 var $sha1base36 = false;
879 var $archiveName = '';
880 private $mNoUpdates = false;
882 function setTitle( $title ) {
883 if( is_object( $title ) ) {
884 $this->title
= $title;
885 } elseif( is_null( $title ) ) {
886 throw new MWException( "WikiRevision given a null title in import. You may need to adjust \$wgLegalTitleChars." );
888 throw new MWException( "WikiRevision given non-object title in import." );
892 function setID( $id ) {
896 function setTimestamp( $ts ) {
897 # 2003-08-05T18:30:02Z
898 $this->timestamp
= wfTimestamp( TS_MW
, $ts );
901 function setUsername( $user ) {
902 $this->user_text
= $user;
905 function setUserIP( $ip ) {
906 $this->user_text
= $ip;
909 function setText( $text ) {
913 function setComment( $text ) {
914 $this->comment
= $text;
917 function setMinor( $minor ) {
918 $this->minor
= (bool)$minor;
921 function setSrc( $src ) {
924 function setFileSrc( $src, $isTemp ) {
925 $this->fileSrc
= $src;
926 $this->fileIsTemp
= $isTemp;
928 function setSha1Base36( $sha1base36 ) {
929 $this->sha1base36
= $sha1base36;
932 function setFilename( $filename ) {
933 $this->filename
= $filename;
935 function setArchiveName( $archiveName ) {
936 $this->archiveName
= $archiveName;
939 function setSize( $size ) {
940 $this->size
= intval( $size );
943 function setType( $type ) {
947 function setAction( $action ) {
948 $this->action
= $action;
951 function setParams( $params ) {
952 $this->params
= $params;
955 public function setNoUpdates( $noupdates ) {
956 $this->mNoUpdates
= $noupdates;
962 function getTitle() {
970 function getTimestamp() {
971 return $this->timestamp
;
975 return $this->user_text
;
982 function getComment() {
983 return $this->comment
;
986 function getMinor() {
994 if ( $this->sha1base36
) {
995 return wfBaseConvert( $this->sha1base36
, 36, 16 );
999 function getFileSrc() {
1000 return $this->fileSrc
;
1002 function isTempSrc() {
1003 return $this->isTemp
;
1006 function getFilename() {
1007 return $this->filename
;
1009 function getArchiveName() {
1010 return $this->archiveName
;
1013 function getSize() {
1017 function getType() {
1021 function getAction() {
1022 return $this->action
;
1025 function getParams() {
1026 return $this->params
;
1029 function importOldRevision() {
1030 $dbw = wfGetDB( DB_MASTER
);
1032 # Sneak a single revision into place
1033 $user = User
::newFromName( $this->getUser() );
1035 $userId = intval( $user->getId() );
1036 $userText = $user->getName();
1040 $userText = $this->getUser();
1041 $userObj = new User
;
1044 // avoid memory leak...?
1045 $linkCache = LinkCache
::singleton();
1046 $linkCache->clear();
1048 $article = new Article( $this->title
);
1049 $pageId = $article->getId();
1050 if( $pageId == 0 ) {
1051 # must create the page...
1052 $pageId = $article->insertOn( $dbw );
1054 $oldcountable = null;
1058 $prior = $dbw->selectField( 'revision', '1',
1059 array( 'rev_page' => $pageId,
1060 'rev_timestamp' => $dbw->timestamp( $this->timestamp
),
1061 'rev_user_text' => $userText,
1062 'rev_comment' => $this->getComment() ),
1066 // @todo FIXME: This could fail slightly for multiple matches :P
1067 wfDebug( __METHOD__
. ": skipping existing revision for [[" .
1068 $this->title
->getPrefixedText() . "]], timestamp " . $this->timestamp
. "\n" );
1071 $oldcountable = $article->isCountable();
1074 # @todo FIXME: Use original rev_id optionally (better for backups)
1076 $revision = new Revision( array(
1078 'text' => $this->getText(),
1079 'comment' => $this->getComment(),
1081 'user_text' => $userText,
1082 'timestamp' => $this->timestamp
,
1083 'minor_edit' => $this->minor
,
1085 $revision->insertOn( $dbw );
1086 $changed = $article->updateIfNewerOn( $dbw, $revision );
1088 if ( $changed !== false && !$this->mNoUpdates
) {
1089 wfDebug( __METHOD__
. ": running updates\n" );
1090 $article->doEditUpdates( $revision, $userObj, array( 'created' => $created, 'oldcountable' => $oldcountable ) );
1096 function importLogItem() {
1097 $dbw = wfGetDB( DB_MASTER
);
1098 # @todo FIXME: This will not record autoblocks
1099 if( !$this->getTitle() ) {
1100 wfDebug( __METHOD__
. ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1101 $this->timestamp
. "\n" );
1104 # Check if it exists already
1105 // @todo FIXME: Use original log ID (better for backups)
1106 $prior = $dbw->selectField( 'logging', '1',
1107 array( 'log_type' => $this->getType(),
1108 'log_action' => $this->getAction(),
1109 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1110 'log_namespace' => $this->getTitle()->getNamespace(),
1111 'log_title' => $this->getTitle()->getDBkey(),
1112 'log_comment' => $this->getComment(),
1113 #'log_user_text' => $this->user_text,
1114 'log_params' => $this->params
),
1117 // @todo FIXME: This could fail slightly for multiple matches :P
1119 wfDebug( __METHOD__
. ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp " .
1120 $this->timestamp
. "\n" );
1123 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1125 'log_id' => $log_id,
1126 'log_type' => $this->type
,
1127 'log_action' => $this->action
,
1128 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1129 'log_user' => User
::idFromName( $this->user_text
),
1130 #'log_user_text' => $this->user_text,
1131 'log_namespace' => $this->getTitle()->getNamespace(),
1132 'log_title' => $this->getTitle()->getDBkey(),
1133 'log_comment' => $this->getComment(),
1134 'log_params' => $this->params
1136 $dbw->insert( 'logging', $data, __METHOD__
);
1139 function importUpload() {
1141 $archiveName = $this->getArchiveName();
1142 if ( $archiveName ) {
1143 wfDebug( __METHOD__
. "Importing archived file as $archiveName\n" );
1144 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1145 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1147 $file = wfLocalFile( $this->getTitle() );
1148 wfDebug( __METHOD__
. 'Importing new file as ' . $file->getName() . "\n" );
1149 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1150 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1151 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1152 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1153 wfDebug( __METHOD__
. "File already exists; importing as $archiveName\n" );
1157 wfDebug( __METHOD__
. ': Bad file for ' . $this->getTitle() . "\n" );
1161 # Get the file source or download if necessary
1162 $source = $this->getFileSrc();
1163 $flags = $this->isTempSrc() ? File
::DELETE_SOURCE
: 0;
1165 $source = $this->downloadSource();
1166 $flags |
= File
::DELETE_SOURCE
;
1169 wfDebug( __METHOD__
. ": Could not fetch remote file.\n" );
1172 $sha1 = $this->getSha1();
1173 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1174 if ( $flags & File
::DELETE_SOURCE
) {
1175 # Broken file; delete it if it is a temporary file
1178 wfDebug( __METHOD__
. ": Corrupt file $source.\n" );
1182 $user = User
::newFromName( $this->user_text
);
1184 # Do the actual upload
1185 if ( $archiveName ) {
1186 $status = $file->uploadOld( $source, $archiveName,
1187 $this->getTimestamp(), $this->getComment(), $user, $flags );
1189 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1190 $flags, false, $this->getTimestamp(), $user );
1193 if ( $status->isGood() ) {
1194 wfDebug( __METHOD__
. ": Succesful\n" );
1197 wfDebug( __METHOD__
. ': failed: ' . $status->getXml() . "\n" );
1202 function downloadSource() {
1203 global $wgEnableUploads;
1204 if( !$wgEnableUploads ) {
1208 $tempo = tempnam( wfTempDir(), 'download' );
1209 $f = fopen( $tempo, 'wb' );
1211 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1216 $src = $this->getSrc();
1217 $data = Http
::get( $src );
1219 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1225 fwrite( $f, $data );
1234 * @todo document (e.g. one-sentence class description).
1235 * @ingroup SpecialPage
1237 class ImportStringSource
{
1238 function __construct( $string ) {
1239 $this->mString
= $string;
1240 $this->mRead
= false;
1244 return $this->mRead
;
1247 function readChunk() {
1248 if( $this->atEnd() ) {
1251 $this->mRead
= true;
1252 return $this->mString
;
1258 * @todo document (e.g. one-sentence class description).
1259 * @ingroup SpecialPage
1261 class ImportStreamSource
{
1262 function __construct( $handle ) {
1263 $this->mHandle
= $handle;
1267 return feof( $this->mHandle
);
1270 function readChunk() {
1271 return fread( $this->mHandle
, 32768 );
1274 static function newFromFile( $filename ) {
1275 wfSuppressWarnings();
1276 $file = fopen( $filename, 'rt' );
1277 wfRestoreWarnings();
1279 return Status
::newFatal( "importcantopen" );
1281 return Status
::newGood( new ImportStreamSource( $file ) );
1284 static function newFromUpload( $fieldname = "xmlimport" ) {
1285 $upload =& $_FILES[$fieldname];
1287 if( !isset( $upload ) ||
!$upload['name'] ) {
1288 return Status
::newFatal( 'importnofile' );
1290 if( !empty( $upload['error'] ) ) {
1291 switch($upload['error']){
1292 case 1: # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1293 return Status
::newFatal( 'importuploaderrorsize' );
1294 case 2: # The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
1295 return Status
::newFatal( 'importuploaderrorsize' );
1296 case 3: # The uploaded file was only partially uploaded
1297 return Status
::newFatal( 'importuploaderrorpartial' );
1298 case 6: #Missing a temporary folder.
1299 return Status
::newFatal( 'importuploaderrortemp' );
1300 # case else: # Currently impossible
1304 $fname = $upload['tmp_name'];
1305 if( is_uploaded_file( $fname ) ) {
1306 return ImportStreamSource
::newFromFile( $fname );
1308 return Status
::newFatal( 'importnofile' );
1312 static function newFromURL( $url, $method = 'GET' ) {
1313 wfDebug( __METHOD__
. ": opening $url\n" );
1314 # Use the standard HTTP fetch function; it times out
1315 # quicker and sorts out user-agent problems which might
1316 # otherwise prevent importing from large sites, such
1317 # as the Wikimedia cluster, etc.
1318 $data = Http
::request( $method, $url );
1319 if( $data !== false ) {
1321 fwrite( $file, $data );
1324 return Status
::newGood( new ImportStreamSource( $file ) );
1326 return Status
::newFatal( 'importcantopen' );
1330 public static function newFromInterwiki( $interwiki, $page, $history = false, $templates = false, $pageLinkDepth = 0 ) {
1332 return Status
::newFatal( 'import-noarticle' );
1334 $link = Title
::newFromText( "$interwiki:Special:Export/$page" );
1335 if( is_null( $link ) ||
$link->getInterwiki() == '' ) {
1336 return Status
::newFatal( 'importbadinterwiki' );
1339 if ( $history ) $params['history'] = 1;
1340 if ( $templates ) $params['templates'] = 1;
1341 if ( $pageLinkDepth ) $params['pagelink-depth'] = $pageLinkDepth;
1342 $url = $link->getFullUrl( $params );
1343 # For interwikis, use POST to avoid redirects.
1344 return ImportStreamSource
::newFromURL( $url, "POST" );