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, $mTargetRootPage, $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 );
203 * Set a target root page under which all pages are imported
205 * @return status object
207 public function setTargetRootPage( $rootpage ) {
208 $status = Status
::newGood();
209 if( is_null( $rootpage ) ) {
211 $this->mTargetRootPage
= null;
212 } elseif( $rootpage !== '' ) {
213 $rootpage = rtrim( $rootpage, '/' ); //avoid double slashes
214 $title = Title
::newFromText( $rootpage, !is_null( $this->mTargetNamespace
) ?
$this->mTargetNamespace
: NS_MAIN
);
215 if( !$title ||
$title->isExternal() ) {
216 $status->fatal( 'import-rootpage-invalid' );
218 if( !MWNamespace
::hasSubpages( $title->getNamespace() ) ) {
221 $displayNSText = $title->getNamespace() == NS_MAIN
222 ?
wfMessage( 'blanknamespace' )->text()
223 : $wgContLang->getNsText( $title->getNamespace() );
224 $status->fatal( 'import-rootpage-nosubpage', $displayNSText );
226 // set namespace to 'all', so the namespace check in processTitle() can passed
227 $this->setTargetNamespace( null );
228 $this->mTargetRootPage
= $title->getPrefixedDBKey();
238 public function setImageBasePath( $dir ) {
239 $this->mImageBasePath
= $dir;
245 public function setImportUploads( $import ) {
246 $this->mImportUploads
= $import;
250 * Default per-revision callback, performs the import.
251 * @param $revision WikiRevision
254 public function importRevision( $revision ) {
255 $dbw = wfGetDB( DB_MASTER
);
256 return $dbw->deadlockLoop( array( $revision, 'importOldRevision' ) );
260 * Default per-revision callback, performs the import.
261 * @param $rev WikiRevision
264 public function importLogItem( $rev ) {
265 $dbw = wfGetDB( DB_MASTER
);
266 return $dbw->deadlockLoop( array( $rev, 'importLogItem' ) );
274 public function importUpload( $revision ) {
275 $dbw = wfGetDB( DB_MASTER
);
276 return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
280 * Mostly for hook use
288 public function finishImportPage( $title, $origTitle, $revCount, $sRevCount, $pageInfo ) {
289 $args = func_get_args();
290 return wfRunHooks( 'AfterImportPage', $args );
294 * Alternate per-revision callback, for debugging.
295 * @param $revision WikiRevision
297 public function debugRevisionHandler( &$revision ) {
298 $this->debug( "Got revision:" );
299 if( is_object( $revision->title
) ) {
300 $this->debug( "-- Title: " . $revision->title
->getPrefixedText() );
302 $this->debug( "-- Title: <invalid>" );
304 $this->debug( "-- User: " . $revision->user_text
);
305 $this->debug( "-- Timestamp: " . $revision->timestamp
);
306 $this->debug( "-- Comment: " . $revision->comment
);
307 $this->debug( "-- Text: " . $revision->text
);
311 * Notify the callback function when a new "<page>" is reached.
312 * @param $title Title
314 function pageCallback( $title ) {
315 if( isset( $this->mPageCallback
) ) {
316 call_user_func( $this->mPageCallback
, $title );
321 * Notify the callback function when a "</page>" is closed.
322 * @param $title Title
323 * @param $origTitle Title
324 * @param $revCount Integer
325 * @param $sucCount Int: number of revisions for which callback returned true
326 * @param $pageInfo Array: associative array of page information
328 private function pageOutCallback( $title, $origTitle, $revCount, $sucCount, $pageInfo ) {
329 if( isset( $this->mPageOutCallback
) ) {
330 $args = func_get_args();
331 call_user_func_array( $this->mPageOutCallback
, $args );
336 * Notify the callback function of a revision
337 * @param $revision WikiRevision object
340 private function revisionCallback( $revision ) {
341 if ( isset( $this->mRevisionCallback
) ) {
342 return call_user_func_array( $this->mRevisionCallback
,
343 array( $revision, $this ) );
350 * Notify the callback function of a new log item
351 * @param $revision WikiRevision object
354 private function logItemCallback( $revision ) {
355 if ( isset( $this->mLogItemCallback
) ) {
356 return call_user_func_array( $this->mLogItemCallback
,
357 array( $revision, $this ) );
364 * Shouldn't something like this be built-in to XMLReader?
365 * Fetches text contents of the current element, assuming
366 * no sub-elements or such scary things.
370 private function nodeContents() {
371 if( $this->reader
->isEmptyElement
) {
375 while( $this->reader
->read() ) {
376 switch( $this->reader
->nodeType
) {
377 case XmlReader
::TEXT
:
378 case XmlReader
::SIGNIFICANT_WHITESPACE
:
379 $buffer .= $this->reader
->value
;
381 case XmlReader
::END_ELEMENT
:
386 $this->reader
->close();
392 /** Left in for debugging */
393 private function dumpElement() {
394 static $lookup = null;
396 $xmlReaderConstants = array(
411 "SIGNIFICANT_WHITESPACE",
418 foreach( $xmlReaderConstants as $name ) {
419 $lookup[constant("XmlReader::$name")] = $name;
424 $lookup[$this->reader
->nodeType
],
431 * Primary entry point
434 public function doImport() {
435 $this->reader
->read();
437 if ( $this->reader
->name
!= 'mediawiki' ) {
438 throw new MWException( "Expected <mediawiki> tag, got ".
439 $this->reader
->name
);
441 $this->debug( "<mediawiki> tag is correct." );
443 $this->debug( "Starting primary dump processing loop." );
445 $keepReading = $this->reader
->read();
447 while ( $keepReading ) {
448 $tag = $this->reader
->name
;
449 $type = $this->reader
->nodeType
;
451 if ( !wfRunHooks( 'ImportHandleToplevelXMLTag', $this ) ) {
453 } elseif ( $tag == 'mediawiki' && $type == XmlReader
::END_ELEMENT
) {
455 } elseif ( $tag == 'siteinfo' ) {
456 $this->handleSiteInfo();
457 } elseif ( $tag == 'page' ) {
459 } elseif ( $tag == 'logitem' ) {
460 $this->handleLogItem();
461 } elseif ( $tag != '#text' ) {
462 $this->warn( "Unhandled top-level XML tag $tag" );
468 $keepReading = $this->reader
->next();
470 $this->debug( "Skip" );
472 $keepReading = $this->reader
->read();
481 * @throws MWException
483 private function handleSiteInfo() {
484 // Site info is useful, but not actually used for dump imports.
485 // Includes a quick short-circuit to save performance.
486 if ( ! $this->mSiteInfoCallback
) {
487 $this->reader
->next();
490 throw new MWException( "SiteInfo tag is not yet handled, do not set mSiteInfoCallback" );
493 private function handleLogItem() {
494 $this->debug( "Enter log item handler." );
497 // Fields that can just be stuffed in the pageInfo object
498 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
499 'logtitle', 'params' );
501 while ( $this->reader
->read() ) {
502 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
503 $this->reader
->name
== 'logitem') {
507 $tag = $this->reader
->name
;
509 if ( !wfRunHooks( 'ImportHandleLogItemXMLTag',
510 $this, $logInfo ) ) {
512 } elseif ( in_array( $tag, $normalFields ) ) {
513 $logInfo[$tag] = $this->nodeContents();
514 } elseif ( $tag == 'contributor' ) {
515 $logInfo['contributor'] = $this->handleContributor();
516 } elseif ( $tag != '#text' ) {
517 $this->warn( "Unhandled log-item XML tag $tag" );
521 $this->processLogItem( $logInfo );
528 private function processLogItem( $logInfo ) {
529 $revision = new WikiRevision
;
531 $revision->setID( $logInfo['id'] );
532 $revision->setType( $logInfo['type'] );
533 $revision->setAction( $logInfo['action'] );
534 $revision->setTimestamp( $logInfo['timestamp'] );
535 $revision->setParams( $logInfo['params'] );
536 $revision->setTitle( Title
::newFromText( $logInfo['logtitle'] ) );
537 $revision->setNoUpdates( $this->mNoUpdates
);
539 if ( isset( $logInfo['comment'] ) ) {
540 $revision->setComment( $logInfo['comment'] );
543 if ( isset( $logInfo['contributor']['ip'] ) ) {
544 $revision->setUserIP( $logInfo['contributor']['ip'] );
546 if ( isset( $logInfo['contributor']['username'] ) ) {
547 $revision->setUserName( $logInfo['contributor']['username'] );
550 return $this->logItemCallback( $revision );
553 private function handlePage() {
555 $this->debug( "Enter page handler." );
556 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
558 // Fields that can just be stuffed in the pageInfo object
559 $normalFields = array( 'title', 'id', 'redirect', 'restrictions' );
564 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
565 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
566 $this->reader
->name
== 'page') {
570 $tag = $this->reader
->name
;
573 // The title is invalid, bail out of this page
575 } elseif ( !wfRunHooks( 'ImportHandlePageXMLTag', array( $this,
578 } elseif ( in_array( $tag, $normalFields ) ) {
579 $pageInfo[$tag] = $this->nodeContents();
580 if ( $tag == 'title' ) {
581 $title = $this->processTitle( $pageInfo['title'] );
588 $this->pageCallback( $title );
589 list( $pageInfo['_title'], $origTitle ) = $title;
591 } elseif ( $tag == 'revision' ) {
592 $this->handleRevision( $pageInfo );
593 } elseif ( $tag == 'upload' ) {
594 $this->handleUpload( $pageInfo );
595 } elseif ( $tag != '#text' ) {
596 $this->warn( "Unhandled page XML tag $tag" );
601 $this->pageOutCallback( $pageInfo['_title'], $origTitle,
602 $pageInfo['revisionCount'],
603 $pageInfo['successfulRevisionCount'],
608 * @param $pageInfo array
610 private function handleRevision( &$pageInfo ) {
611 $this->debug( "Enter revision handler" );
612 $revisionInfo = array();
614 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'model', 'format', 'text' );
618 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
619 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
620 $this->reader
->name
== 'revision') {
624 $tag = $this->reader
->name
;
626 if ( !wfRunHooks( 'ImportHandleRevisionXMLTag', $this,
627 $pageInfo, $revisionInfo ) ) {
629 } elseif ( in_array( $tag, $normalFields ) ) {
630 $revisionInfo[$tag] = $this->nodeContents();
631 } elseif ( $tag == 'contributor' ) {
632 $revisionInfo['contributor'] = $this->handleContributor();
633 } elseif ( $tag != '#text' ) {
634 $this->warn( "Unhandled revision XML tag $tag" );
639 $pageInfo['revisionCount']++
;
640 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
641 $pageInfo['successfulRevisionCount']++
;
647 * @param $revisionInfo
650 private function processRevision( $pageInfo, $revisionInfo ) {
651 $revision = new WikiRevision
;
653 if( isset( $revisionInfo['id'] ) ) {
654 $revision->setID( $revisionInfo['id'] );
656 if ( isset( $revisionInfo['text'] ) ) {
657 $revision->setText( $revisionInfo['text'] );
659 if ( isset( $revisionInfo['model'] ) ) {
660 $revision->setModel( $revisionInfo['model'] );
662 if ( isset( $revisionInfo['text'] ) ) {
663 $revision->setFormat( $revisionInfo['format'] );
665 $revision->setTitle( $pageInfo['_title'] );
667 if ( isset( $revisionInfo['timestamp'] ) ) {
668 $revision->setTimestamp( $revisionInfo['timestamp'] );
670 $revision->setTimestamp( wfTimestampNow() );
673 if ( isset( $revisionInfo['comment'] ) ) {
674 $revision->setComment( $revisionInfo['comment'] );
677 if ( isset( $revisionInfo['minor'] ) ) {
678 $revision->setMinor( true );
680 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
681 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
683 if ( isset( $revisionInfo['contributor']['username'] ) ) {
684 $revision->setUserName( $revisionInfo['contributor']['username'] );
686 $revision->setNoUpdates( $this->mNoUpdates
);
688 return $this->revisionCallback( $revision );
695 private function handleUpload( &$pageInfo ) {
696 $this->debug( "Enter upload handler" );
697 $uploadInfo = array();
699 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
700 'src', 'size', 'sha1base36', 'archivename', 'rel' );
704 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
705 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
706 $this->reader
->name
== 'upload') {
710 $tag = $this->reader
->name
;
712 if ( !wfRunHooks( 'ImportHandleUploadXMLTag', $this,
715 } elseif ( in_array( $tag, $normalFields ) ) {
716 $uploadInfo[$tag] = $this->nodeContents();
717 } elseif ( $tag == 'contributor' ) {
718 $uploadInfo['contributor'] = $this->handleContributor();
719 } elseif ( $tag == 'contents' ) {
720 $contents = $this->nodeContents();
721 $encoding = $this->reader
->getAttribute( 'encoding' );
722 if ( $encoding === 'base64' ) {
723 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
724 $uploadInfo['isTempSrc'] = true;
726 } elseif ( $tag != '#text' ) {
727 $this->warn( "Unhandled upload XML tag $tag" );
732 if ( $this->mImageBasePath
&& isset( $uploadInfo['rel'] ) ) {
733 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
734 if ( file_exists( $path ) ) {
735 $uploadInfo['fileSrc'] = $path;
736 $uploadInfo['isTempSrc'] = false;
740 if ( $this->mImportUploads
) {
741 return $this->processUpload( $pageInfo, $uploadInfo );
749 private function dumpTemp( $contents ) {
750 $filename = tempnam( wfTempDir(), 'importupload' );
751 file_put_contents( $filename, $contents );
760 private function processUpload( $pageInfo, $uploadInfo ) {
761 $revision = new WikiRevision
;
762 $text = isset( $uploadInfo['text'] ) ?
$uploadInfo['text'] : '';
764 $revision->setTitle( $pageInfo['_title'] );
765 $revision->setID( $pageInfo['id'] );
766 $revision->setTimestamp( $uploadInfo['timestamp'] );
767 $revision->setText( $text );
768 $revision->setFilename( $uploadInfo['filename'] );
769 if ( isset( $uploadInfo['archivename'] ) ) {
770 $revision->setArchiveName( $uploadInfo['archivename'] );
772 $revision->setSrc( $uploadInfo['src'] );
773 if ( isset( $uploadInfo['fileSrc'] ) ) {
774 $revision->setFileSrc( $uploadInfo['fileSrc'],
775 !empty( $uploadInfo['isTempSrc'] ) );
777 if ( isset( $uploadInfo['sha1base36'] ) ) {
778 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
780 $revision->setSize( intval( $uploadInfo['size'] ) );
781 $revision->setComment( $uploadInfo['comment'] );
783 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
784 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
786 if ( isset( $uploadInfo['contributor']['username'] ) ) {
787 $revision->setUserName( $uploadInfo['contributor']['username'] );
789 $revision->setNoUpdates( $this->mNoUpdates
);
791 return call_user_func( $this->mUploadCallback
, $revision );
797 private function handleContributor() {
798 $fields = array( 'id', 'ip', 'username' );
801 while ( $this->reader
->read() ) {
802 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
803 $this->reader
->name
== 'contributor') {
807 $tag = $this->reader
->name
;
809 if ( in_array( $tag, $fields ) ) {
810 $info[$tag] = $this->nodeContents();
818 * @param $text string
819 * @return Array or false
821 private function processTitle( $text ) {
822 global $wgCommandLineMode;
825 $origTitle = Title
::newFromText( $workTitle );
827 if( !is_null( $this->mTargetNamespace
) && !is_null( $origTitle ) ) {
828 # makeTitleSafe, because $origTitle can have a interwiki (different setting of interwiki map)
829 # and than dbKey can begin with a lowercase char
830 $title = Title
::makeTitleSafe( $this->mTargetNamespace
,
831 $origTitle->getDBkey() );
833 if( !is_null( $this->mTargetRootPage
) ) {
834 $workTitle = $this->mTargetRootPage
. '/' . $workTitle;
836 $title = Title
::newFromText( $workTitle );
839 if( is_null( $title ) ) {
840 # Invalid page title? Ignore the page
841 $this->notice( 'import-error-invalid', $workTitle );
843 } elseif( $title->isExternal() ) {
844 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
846 } elseif( !$title->canExist() ) {
847 $this->notice( 'import-error-special', $title->getPrefixedText() );
849 } elseif( !$title->userCan( 'edit' ) && !$wgCommandLineMode ) {
850 # Do not import if the importing wiki user cannot edit this page
851 $this->notice( 'import-error-edit', $title->getPrefixedText() );
853 } elseif( !$title->exists() && !$title->userCan( 'create' ) && !$wgCommandLineMode ) {
854 # Do not import if the importing wiki user cannot create this page
855 $this->notice( 'import-error-create', $title->getPrefixedText() );
859 return array( $title, $origTitle );
863 /** This is a horrible hack used to keep source compatibility */
864 class UploadSourceAdapter
{
865 static $sourceRegistrations = array();
875 static function registerSource( $source ) {
876 $id = wfRandomString();
878 self
::$sourceRegistrations[$id] = $source;
887 * @param $opened_path
890 function stream_open( $path, $mode, $options, &$opened_path ) {
891 $url = parse_url($path);
894 if ( !isset( self
::$sourceRegistrations[$id] ) ) {
898 $this->mSource
= self
::$sourceRegistrations[$id];
907 function stream_read( $count ) {
911 while ( !$leave && !$this->mSource
->atEnd() &&
912 strlen($this->mBuffer
) < $count ) {
913 $read = $this->mSource
->readChunk();
915 if ( !strlen($read) ) {
919 $this->mBuffer
.= $read;
922 if ( strlen($this->mBuffer
) ) {
923 $return = substr( $this->mBuffer
, 0, $count );
924 $this->mBuffer
= substr( $this->mBuffer
, $count );
927 $this->mPosition +
= strlen($return);
936 function stream_write( $data ) {
943 function stream_tell() {
944 return $this->mPosition
;
950 function stream_eof() {
951 return $this->mSource
->atEnd();
957 function url_stat() {
960 $result['dev'] = $result[0] = 0;
961 $result['ino'] = $result[1] = 0;
962 $result['mode'] = $result[2] = 0;
963 $result['nlink'] = $result[3] = 0;
964 $result['uid'] = $result[4] = 0;
965 $result['gid'] = $result[5] = 0;
966 $result['rdev'] = $result[6] = 0;
967 $result['size'] = $result[7] = 0;
968 $result['atime'] = $result[8] = 0;
969 $result['mtime'] = $result[9] = 0;
970 $result['ctime'] = $result[10] = 0;
971 $result['blksize'] = $result[11] = 0;
972 $result['blocks'] = $result[12] = 0;
978 class XMLReader2
extends XMLReader
{
981 * @return bool|string
983 function nodeContents() {
984 if( $this->isEmptyElement
) {
988 while( $this->read() ) {
989 switch( $this->nodeType
) {
990 case XmlReader
::TEXT
:
991 case XmlReader
::SIGNIFICANT_WHITESPACE
:
992 $buffer .= $this->value
;
994 case XmlReader
::END_ELEMENT
:
998 return $this->close();
1003 * @todo document (e.g. one-sentence class description).
1004 * @ingroup SpecialPage
1006 class WikiRevision
{
1007 var $importer = null;
1014 var $timestamp = "20010115000000";
1016 var $user_text = "";
1020 var $content = null;
1027 var $sha1base36 = false;
1028 var $isTemp = false;
1029 var $archiveName = '';
1031 private $mNoUpdates = false;
1035 * @throws MWException
1037 function setTitle( $title ) {
1038 if( is_object( $title ) ) {
1039 $this->title
= $title;
1040 } elseif( is_null( $title ) ) {
1041 throw new MWException( "WikiRevision given a null title in import. You may need to adjust \$wgLegalTitleChars." );
1043 throw new MWException( "WikiRevision given non-object title in import." );
1050 function setID( $id ) {
1057 function setTimestamp( $ts ) {
1058 # 2003-08-05T18:30:02Z
1059 $this->timestamp
= wfTimestamp( TS_MW
, $ts );
1065 function setUsername( $user ) {
1066 $this->user_text
= $user;
1072 function setUserIP( $ip ) {
1073 $this->user_text
= $ip;
1079 function setModel( $model ) {
1080 $this->model
= $model;
1086 function setFormat( $format ) {
1087 $this->format
= $format;
1093 function setText( $text ) {
1094 $this->text
= $text;
1100 function setComment( $text ) {
1101 $this->comment
= $text;
1107 function setMinor( $minor ) {
1108 $this->minor
= (bool)$minor;
1114 function setSrc( $src ) {
1122 function setFileSrc( $src, $isTemp ) {
1123 $this->fileSrc
= $src;
1124 $this->fileIsTemp
= $isTemp;
1128 * @param $sha1base36
1130 function setSha1Base36( $sha1base36 ) {
1131 $this->sha1base36
= $sha1base36;
1137 function setFilename( $filename ) {
1138 $this->filename
= $filename;
1142 * @param $archiveName
1144 function setArchiveName( $archiveName ) {
1145 $this->archiveName
= $archiveName;
1151 function setSize( $size ) {
1152 $this->size
= intval( $size );
1158 function setType( $type ) {
1159 $this->type
= $type;
1165 function setAction( $action ) {
1166 $this->action
= $action;
1172 function setParams( $params ) {
1173 $this->params
= $params;
1179 public function setNoUpdates( $noupdates ) {
1180 $this->mNoUpdates
= $noupdates;
1186 function getTitle() {
1187 return $this->title
;
1200 function getTimestamp() {
1201 return $this->timestamp
;
1207 function getUser() {
1208 return $this->user_text
;
1214 * @deprecated Since 1.21, use getContent() instead.
1216 function getText() {
1217 wfDeprecated( "Use getContent() instead." );
1225 function getContent() {
1226 if ( is_null( $this->content
) ) {
1228 ContentHandler
::makeContent(
1236 return $this->content
;
1242 function getModel() {
1243 if ( is_null( $this->model
) ) {
1244 $this->model
= $this->getTitle()->getContentModel();
1247 return $this->model
;
1253 function getFormat() {
1254 if ( is_null( $this->model
) ) {
1255 $this->format
= ContentHandler
::getForTitle( $this->getTitle() )->getDefaultFormat();
1258 return $this->format
;
1264 function getComment() {
1265 return $this->comment
;
1271 function getMinor() {
1272 return $this->minor
;
1283 * @return bool|String
1285 function getSha1() {
1286 if ( $this->sha1base36
) {
1287 return wfBaseConvert( $this->sha1base36
, 36, 16 );
1295 function getFileSrc() {
1296 return $this->fileSrc
;
1302 function isTempSrc() {
1303 return $this->isTemp
;
1309 function getFilename() {
1310 return $this->filename
;
1316 function getArchiveName() {
1317 return $this->archiveName
;
1323 function getSize() {
1330 function getType() {
1337 function getAction() {
1338 return $this->action
;
1344 function getParams() {
1345 return $this->params
;
1351 function importOldRevision() {
1352 $dbw = wfGetDB( DB_MASTER
);
1354 # Sneak a single revision into place
1355 $user = User
::newFromName( $this->getUser() );
1357 $userId = intval( $user->getId() );
1358 $userText = $user->getName();
1362 $userText = $this->getUser();
1363 $userObj = new User
;
1366 // avoid memory leak...?
1367 $linkCache = LinkCache
::singleton();
1368 $linkCache->clear();
1370 $page = WikiPage
::factory( $this->title
);
1371 if( !$page->exists() ) {
1372 # must create the page...
1373 $pageId = $page->insertOn( $dbw );
1375 $oldcountable = null;
1377 $pageId = $page->getId();
1380 $prior = $dbw->selectField( 'revision', '1',
1381 array( 'rev_page' => $pageId,
1382 'rev_timestamp' => $dbw->timestamp( $this->timestamp
),
1383 'rev_user_text' => $userText,
1384 'rev_comment' => $this->getComment() ),
1388 // @todo FIXME: This could fail slightly for multiple matches :P
1389 wfDebug( __METHOD__
. ": skipping existing revision for [[" .
1390 $this->title
->getPrefixedText() . "]], timestamp " . $this->timestamp
. "\n" );
1393 $oldcountable = $page->isCountable();
1396 # @todo FIXME: Use original rev_id optionally (better for backups)
1398 $revision = new Revision( array(
1400 'content_model' => $this->getModel(),
1401 'content_format' => $this->getFormat(),
1402 'text' => $this->getContent()->serialize( $this->getFormat() ), //XXX: just set 'content' => $this->getContent()?
1403 'comment' => $this->getComment(),
1405 'user_text' => $userText,
1406 'timestamp' => $this->timestamp
,
1407 'minor_edit' => $this->minor
,
1409 $revision->insertOn( $dbw );
1410 $changed = $page->updateIfNewerOn( $dbw, $revision );
1412 if ( $changed !== false && !$this->mNoUpdates
) {
1413 wfDebug( __METHOD__
. ": running updates\n" );
1414 $page->doEditUpdates( $revision, $userObj, array( 'created' => $created, 'oldcountable' => $oldcountable ) );
1423 function importLogItem() {
1424 $dbw = wfGetDB( DB_MASTER
);
1425 # @todo FIXME: This will not record autoblocks
1426 if( !$this->getTitle() ) {
1427 wfDebug( __METHOD__
. ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1428 $this->timestamp
. "\n" );
1431 # Check if it exists already
1432 // @todo FIXME: Use original log ID (better for backups)
1433 $prior = $dbw->selectField( 'logging', '1',
1434 array( 'log_type' => $this->getType(),
1435 'log_action' => $this->getAction(),
1436 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1437 'log_namespace' => $this->getTitle()->getNamespace(),
1438 'log_title' => $this->getTitle()->getDBkey(),
1439 'log_comment' => $this->getComment(),
1440 #'log_user_text' => $this->user_text,
1441 'log_params' => $this->params
),
1444 // @todo FIXME: This could fail slightly for multiple matches :P
1446 wfDebug( __METHOD__
. ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp " .
1447 $this->timestamp
. "\n" );
1450 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1452 'log_id' => $log_id,
1453 'log_type' => $this->type
,
1454 'log_action' => $this->action
,
1455 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1456 'log_user' => User
::idFromName( $this->user_text
),
1457 #'log_user_text' => $this->user_text,
1458 'log_namespace' => $this->getTitle()->getNamespace(),
1459 'log_title' => $this->getTitle()->getDBkey(),
1460 'log_comment' => $this->getComment(),
1461 'log_params' => $this->params
1463 $dbw->insert( 'logging', $data, __METHOD__
);
1469 function importUpload() {
1471 $archiveName = $this->getArchiveName();
1472 if ( $archiveName ) {
1473 wfDebug( __METHOD__
. "Importing archived file as $archiveName\n" );
1474 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1475 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1477 $file = wfLocalFile( $this->getTitle() );
1478 wfDebug( __METHOD__
. 'Importing new file as ' . $file->getName() . "\n" );
1479 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1480 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1481 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1482 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1483 wfDebug( __METHOD__
. "File already exists; importing as $archiveName\n" );
1487 wfDebug( __METHOD__
. ': Bad file for ' . $this->getTitle() . "\n" );
1491 # Get the file source or download if necessary
1492 $source = $this->getFileSrc();
1493 $flags = $this->isTempSrc() ? File
::DELETE_SOURCE
: 0;
1495 $source = $this->downloadSource();
1496 $flags |
= File
::DELETE_SOURCE
;
1499 wfDebug( __METHOD__
. ": Could not fetch remote file.\n" );
1502 $sha1 = $this->getSha1();
1503 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1504 if ( $flags & File
::DELETE_SOURCE
) {
1505 # Broken file; delete it if it is a temporary file
1508 wfDebug( __METHOD__
. ": Corrupt file $source.\n" );
1512 $user = User
::newFromName( $this->user_text
);
1514 # Do the actual upload
1515 if ( $archiveName ) {
1516 $status = $file->uploadOld( $source, $archiveName,
1517 $this->getTimestamp(), $this->getComment(), $user, $flags );
1519 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1520 $flags, false, $this->getTimestamp(), $user );
1523 if ( $status->isGood() ) {
1524 wfDebug( __METHOD__
. ": Succesful\n" );
1527 wfDebug( __METHOD__
. ': failed: ' . $status->getXml() . "\n" );
1533 * @return bool|string
1535 function downloadSource() {
1536 global $wgEnableUploads;
1537 if( !$wgEnableUploads ) {
1541 $tempo = tempnam( wfTempDir(), 'download' );
1542 $f = fopen( $tempo, 'wb' );
1544 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1549 $src = $this->getSrc();
1550 $data = Http
::get( $src );
1552 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1558 fwrite( $f, $data );
1567 * @todo document (e.g. one-sentence class description).
1568 * @ingroup SpecialPage
1570 class ImportStringSource
{
1571 function __construct( $string ) {
1572 $this->mString
= $string;
1573 $this->mRead
= false;
1580 return $this->mRead
;
1584 * @return bool|string
1586 function readChunk() {
1587 if( $this->atEnd() ) {
1590 $this->mRead
= true;
1591 return $this->mString
;
1596 * @todo document (e.g. one-sentence class description).
1597 * @ingroup SpecialPage
1599 class ImportStreamSource
{
1600 function __construct( $handle ) {
1601 $this->mHandle
= $handle;
1608 return feof( $this->mHandle
);
1614 function readChunk() {
1615 return fread( $this->mHandle
, 32768 );
1619 * @param $filename string
1622 static function newFromFile( $filename ) {
1623 wfSuppressWarnings();
1624 $file = fopen( $filename, 'rt' );
1625 wfRestoreWarnings();
1627 return Status
::newFatal( "importcantopen" );
1629 return Status
::newGood( new ImportStreamSource( $file ) );
1633 * @param $fieldname string
1636 static function newFromUpload( $fieldname = "xmlimport" ) {
1637 $upload =& $_FILES[$fieldname];
1639 if( !isset( $upload ) ||
!$upload['name'] ) {
1640 return Status
::newFatal( 'importnofile' );
1642 if( !empty( $upload['error'] ) ) {
1643 switch($upload['error']){
1644 case 1: # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1645 return Status
::newFatal( 'importuploaderrorsize' );
1646 case 2: # The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
1647 return Status
::newFatal( 'importuploaderrorsize' );
1648 case 3: # The uploaded file was only partially uploaded
1649 return Status
::newFatal( 'importuploaderrorpartial' );
1650 case 6: #Missing a temporary folder.
1651 return Status
::newFatal( 'importuploaderrortemp' );
1652 # case else: # Currently impossible
1656 $fname = $upload['tmp_name'];
1657 if( is_uploaded_file( $fname ) ) {
1658 return ImportStreamSource
::newFromFile( $fname );
1660 return Status
::newFatal( 'importnofile' );
1666 * @param $method string
1669 static function newFromURL( $url, $method = 'GET' ) {
1670 wfDebug( __METHOD__
. ": opening $url\n" );
1671 # Use the standard HTTP fetch function; it times out
1672 # quicker and sorts out user-agent problems which might
1673 # otherwise prevent importing from large sites, such
1674 # as the Wikimedia cluster, etc.
1675 $data = Http
::request( $method, $url, array( 'followRedirects' => true ) );
1676 if( $data !== false ) {
1678 fwrite( $file, $data );
1681 return Status
::newGood( new ImportStreamSource( $file ) );
1683 return Status
::newFatal( 'importcantopen' );
1690 * @param $history bool
1691 * @param $templates bool
1692 * @param $pageLinkDepth int
1695 public static function newFromInterwiki( $interwiki, $page, $history = false, $templates = false, $pageLinkDepth = 0 ) {
1697 return Status
::newFatal( 'import-noarticle' );
1699 $link = Title
::newFromText( "$interwiki:Special:Export/$page" );
1700 if( is_null( $link ) ||
$link->getInterwiki() == '' ) {
1701 return Status
::newFatal( 'importbadinterwiki' );
1704 if ( $history ) $params['history'] = 1;
1705 if ( $templates ) $params['templates'] = 1;
1706 if ( $pageLinkDepth ) $params['pagelink-depth'] = $pageLinkDepth;
1707 $url = $link->getFullUrl( $params );
1708 # For interwikis, use POST to avoid redirects.
1709 return ImportStreamSource
::newFromURL( $url, "POST" );