3 * MediaWiki page data importer
4 * Copyright (C) 2003,2005 Brion Vibber <brion@pobox.com>
5 * http://www.mediawiki.org/
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
22 * @addtogroup SpecialPage
28 function wfSpecialImport( $page = '' ) {
29 global $wgUser, $wgOut, $wgRequest, $wgTitle, $wgImportSources;
30 global $wgImportTargetNamespace;
33 $namespace = $wgImportTargetNamespace;
37 if( $wgRequest->wasPosted() && $wgRequest->getVal( 'action' ) == 'submit') {
39 $namespace = $wgRequest->getIntOrNull( 'namespace' );
41 switch( $wgRequest->getVal( "source" ) ) {
44 if( $wgUser->isAllowed( 'importupload' ) ) {
45 $source = ImportStreamSource
::newFromUpload( "xmlimport" );
47 return $wgOut->permissionRequired( 'importupload' );
51 $interwiki = $wgRequest->getVal( 'interwiki' );
52 $history = $wgRequest->getCheck( 'interwikiHistory' );
53 $frompage = $wgRequest->getText( "frompage" );
54 $source = ImportStreamSource
::newFromInterwiki(
60 $source = new WikiErrorMsg( "importunknownsource" );
63 if( WikiError
::isError( $source ) ) {
64 $wgOut->addWikiText( wfEscapeWikiText( $source->getMessage() ) );
66 $wgOut->addWikiText( wfMsg( "importstart" ) );
68 $importer = new WikiImporter( $source );
69 if( !is_null( $namespace ) ) {
70 $importer->setTargetNamespace( $namespace );
72 $reporter = new ImportReporter( $importer, $isUpload, $interwiki );
75 $result = $importer->doImport();
78 if( WikiError
::isError( $result ) ) {
79 $wgOut->addWikiText( wfMsg( "importfailed",
80 wfEscapeWikiText( $result->getMessage() ) ) );
83 $wgOut->addWikiText( wfMsg( "importsuccess" ) );
88 $action = $wgTitle->escapeLocalUrl( 'action=submit' );
90 if( $wgUser->isAllowed( 'importupload' ) ) {
91 $wgOut->addWikiText( wfMsg( "importtext" ) );
94 <legend>" . wfMsgHtml('upload') . "</legend>
95 <form enctype='multipart/form-data' method='post' action=\"$action\">
96 <input type='hidden' name='action' value='submit' />
97 <input type='hidden' name='source' value='upload' />
98 <input type='hidden' name='MAX_FILE_SIZE' value='2000000' />
99 <input type='file' name='xmlimport' value='' size='30' />
100 <input type='submit' value=\"" . wfMsgHtml( "uploadbtn" ) . "\" />
105 if( empty( $wgImportSources ) ) {
106 $wgOut->addWikiText( wfMsg( 'importnosources' ) );
110 if( !empty( $wgImportSources ) ) {
113 <legend>" . wfMsgHtml('importinterwiki') . "</legend>
114 <form method='post' action=\"$action\">" .
115 $wgOut->parse( wfMsg( 'import-interwiki-text' ) ) . "
116 <input type='hidden' name='action' value='submit' />
117 <input type='hidden' name='source' value='interwiki' />
121 <select name='interwiki'>" );
122 foreach( $wgImportSources as $prefix ) {
123 $iw = htmlspecialchars( $prefix );
124 $selected = ($interwiki === $prefix) ?
' selected="selected"' : '';
125 $wgOut->addHTML( "<option value=\"$iw\"$selected>$iw</option>\n" );
131 wfInput( 'frompage', 50, $frompage ) .
137 wfCheckLabel( wfMsg( 'import-interwiki-history' ),
138 'interwikiHistory', 'interwikiHistory', $history ) .
144 " . wfMsgHtml( 'import-interwiki-namespace' ) . " " .
145 HTMLnamespaceselector( $namespace, '' ) . "
151 wfSubmitButton( wfMsg( 'import-interwiki-submit' ) ) .
163 * @addtogroup SpecialPage
165 class ImportReporter
{
166 function __construct( $importer, $upload, $interwiki ) {
167 $importer->setPageOutCallback( array( $this, 'reportPage' ) );
168 $this->mPageCount
= 0;
169 $this->mIsUpload
= $upload;
170 $this->mInterwiki
= $interwiki;
175 $wgOut->addHtml( "<ul>\n" );
178 function reportPage( $title, $origTitle, $revisionCount, $successCount ) {
179 global $wgOut, $wgUser, $wgLang, $wgContLang;
181 $skin = $wgUser->getSkin();
185 $localCount = $wgLang->formatNum( $successCount );
186 $contentCount = $wgContLang->formatNum( $successCount );
188 $wgOut->addHtml( "<li>" . $skin->makeKnownLinkObj( $title ) .
190 wfMsgExt( 'import-revision-count', array( 'parsemag', 'escape' ), $localCount ) .
193 if( $successCount > 0 ) {
194 $log = new LogPage( 'import' );
195 if( $this->mIsUpload
) {
196 $detail = wfMsgForContent( 'import-logentry-upload-detail',
198 $log->addEntry( 'upload', $title, $detail );
200 $interwiki = '[[:' . $this->mInterwiki
. ':' .
201 $origTitle->getPrefixedText() . ']]';
202 $detail = wfMsgForContent( 'import-logentry-interwiki-detail',
203 $contentCount, $interwiki );
204 $log->addEntry( 'interwiki', $title, $detail );
207 $comment = $detail; // quick
208 $dbw = wfGetDB( DB_MASTER
);
209 $nullRevision = Revision
::newNullRevision(
210 $dbw, $title->getArticleId(), $comment, true );
211 $nullRevision->insertOn( $dbw );
217 if( $this->mPageCount
== 0 ) {
218 $wgOut->addHtml( "<li>" . wfMsgHtml( 'importnopages' ) . "</li>\n" );
220 $wgOut->addHtml( "</ul>\n" );
226 * @addtogroup SpecialPage
231 var $timestamp = "20010115000000";
238 function setTitle( $title ) {
239 if( is_object( $title ) ) {
240 $this->title
= $title;
241 } elseif( is_null( $title ) ) {
242 throw new MWException( "WikiRevision given a null title in import. You may need to adjust \$wgLegalTitleChars." );
244 throw new MWException( "WikiRevision given non-object title in import." );
248 function setID( $id ) {
252 function setTimestamp( $ts ) {
253 # 2003-08-05T18:30:02Z
254 $this->timestamp
= wfTimestamp( TS_MW
, $ts );
257 function setUsername( $user ) {
258 $this->user_text
= $user;
261 function setUserIP( $ip ) {
262 $this->user_text
= $ip;
265 function setText( $text ) {
269 function setComment( $text ) {
270 $this->comment
= $text;
273 function setMinor( $minor ) {
274 $this->minor
= (bool)$minor;
277 function getTitle() {
285 function getTimestamp() {
286 return $this->timestamp
;
290 return $this->user_text
;
297 function getComment() {
298 return $this->comment
;
301 function getMinor() {
305 function importOldRevision() {
306 $dbw = wfGetDB( DB_MASTER
);
308 # Sneak a single revision into place
309 $user = User
::newFromName( $this->getUser() );
311 $userId = intval( $user->getId() );
312 $userText = $user->getName();
315 $userText = $this->getUser();
318 // avoid memory leak...?
319 $linkCache =& LinkCache
::singleton();
322 $article = new Article( $this->title
);
323 $pageId = $article->getId();
325 # must create the page...
326 $pageId = $article->insertOn( $dbw );
331 $prior = Revision
::loadFromTimestamp( $dbw, $this->title
, $this->timestamp
);
332 if( !is_null( $prior ) ) {
333 // FIXME: this could fail slightly for multiple matches :P
334 wfDebug( __METHOD__
. ": skipping existing revision for [[" .
335 $this->title
->getPrefixedText() . "]], timestamp " .
336 $this->timestamp
. "\n" );
341 # FIXME: Use original rev_id optionally
342 # FIXME: blah blah blah
344 #if( $numrows > 0 ) {
345 # return wfMsg( "importhistoryconflict" );
349 $revision = new Revision( array(
351 'text' => $this->getText(),
352 'comment' => $this->getComment(),
354 'user_text' => $userText,
355 'timestamp' => $this->timestamp
,
356 'minor_edit' => $this->minor
,
358 $revId = $revision->insertOn( $dbw );
359 $changed = $article->updateIfNewerOn( $dbw, $revision );
362 wfDebug( __METHOD__
. ": running onArticleCreate\n" );
363 Article
::onArticleCreate( $this->title
);
365 wfDebug( __METHOD__
. ": running create updates\n" );
366 $article->createUpdates( $revision );
368 } elseif( $changed ) {
369 wfDebug( __METHOD__
. ": running onArticleEdit\n" );
370 Article
::onArticleEdit( $this->title
);
372 wfDebug( __METHOD__
. ": running edit updates\n" );
373 $article->editUpdates(
387 * implements Special:Import
388 * @addtogroup SpecialPage
392 var $mPageCallback = null;
393 var $mPageOutCallback = null;
394 var $mRevisionCallback = null;
395 var $mTargetNamespace = null;
398 function WikiImporter( $source ) {
399 $this->setRevisionCallback( array( &$this, "importRevision" ) );
400 $this->mSource
= $source;
403 function throwXmlError( $err ) {
404 $this->debug( "FAILURE: $err" );
405 wfDebug( "WikiImporter XML error: $err\n" );
410 function doImport() {
411 if( empty( $this->mSource
) ) {
412 return new WikiErrorMsg( "importnotext" );
415 $parser = xml_parser_create( "UTF-8" );
417 # case folding violates XML standard, turn it off
418 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING
, false );
420 xml_set_object( $parser, $this );
421 xml_set_element_handler( $parser, "in_start", "" );
423 $offset = 0; // for context extraction on error reporting
425 $chunk = $this->mSource
->readChunk();
426 if( !xml_parse( $parser, $chunk, $this->mSource
->atEnd() ) ) {
427 wfDebug( "WikiImporter::doImport encountered XML parsing error\n" );
428 return new WikiXmlError( $parser, 'XML import parse failure', $chunk, $offset );
430 $offset +
= strlen( $chunk );
431 } while( $chunk !== false && !$this->mSource
->atEnd() );
432 xml_parser_free( $parser );
437 function debug( $data ) {
438 #wfDebug( "IMPORT: $data\n" );
441 function notice( $data ) {
442 global $wgCommandLineMode;
443 if( $wgCommandLineMode ) {
447 $wgOut->addHTML( "<li>" . htmlspecialchars( $data ) . "</li>\n" );
452 * Sets the action to perform as each new page in the stream is reached.
453 * @param callable $callback
456 function setPageCallback( $callback ) {
457 $previous = $this->mPageCallback
;
458 $this->mPageCallback
= $callback;
463 * Sets the action to perform as each page in the stream is completed.
464 * Callback accepts the page title (as a Title object), a second object
465 * with the original title form (in case it's been overridden into a
466 * local namespace), and a count of revisions.
468 * @param callable $callback
471 function setPageOutCallback( $callback ) {
472 $previous = $this->mPageOutCallback
;
473 $this->mPageOutCallback
= $callback;
478 * Sets the action to perform as each page revision is reached.
479 * @param callable $callback
482 function setRevisionCallback( $callback ) {
483 $previous = $this->mRevisionCallback
;
484 $this->mRevisionCallback
= $callback;
489 * Set a target namespace to override the defaults
491 function setTargetNamespace( $namespace ) {
492 if( is_null( $namespace ) ) {
493 // Don't override namespaces
494 $this->mTargetNamespace
= null;
495 } elseif( $namespace >= 0 ) {
496 // FIXME: Check for validity
497 $this->mTargetNamespace
= intval( $namespace );
504 * Default per-revision callback, performs the import.
505 * @param WikiRevision $revision
508 function importRevision( &$revision ) {
509 $dbw = wfGetDB( DB_MASTER
);
510 return $dbw->deadlockLoop( array( &$revision, 'importOldRevision' ) );
514 * Alternate per-revision callback, for debugging.
515 * @param WikiRevision $revision
518 function debugRevisionHandler( &$revision ) {
519 $this->debug( "Got revision:" );
520 if( is_object( $revision->title
) ) {
521 $this->debug( "-- Title: " . $revision->title
->getPrefixedText() );
523 $this->debug( "-- Title: <invalid>" );
525 $this->debug( "-- User: " . $revision->user_text
);
526 $this->debug( "-- Timestamp: " . $revision->timestamp
);
527 $this->debug( "-- Comment: " . $revision->comment
);
528 $this->debug( "-- Text: " . $revision->text
);
532 * Notify the callback function when a new <page> is reached.
533 * @param Title $title
536 function pageCallback( $title ) {
537 if( is_callable( $this->mPageCallback
) ) {
538 call_user_func( $this->mPageCallback
, $title );
543 * Notify the callback function when a </page> is closed.
544 * @param Title $title
545 * @param Title $origTitle
546 * @param int $revisionCount
547 * @param int $successCount number of revisions for which callback returned true
550 function pageOutCallback( $title, $origTitle, $revisionCount, $successCount ) {
551 if( is_callable( $this->mPageOutCallback
) ) {
552 call_user_func( $this->mPageOutCallback
, $title, $origTitle,
553 $revisionCount, $successCount );
558 # XML parser callbacks from here out -- beware!
559 function donothing( $parser, $x, $y="" ) {
560 #$this->debug( "donothing" );
563 function in_start( $parser, $name, $attribs ) {
564 $this->debug( "in_start $name" );
565 if( $name != "mediawiki" ) {
566 return $this->throwXMLerror( "Expected <mediawiki>, got <$name>" );
568 xml_set_element_handler( $parser, "in_mediawiki", "out_mediawiki" );
571 function in_mediawiki( $parser, $name, $attribs ) {
572 $this->debug( "in_mediawiki $name" );
573 if( $name == 'siteinfo' ) {
574 xml_set_element_handler( $parser, "in_siteinfo", "out_siteinfo" );
575 } elseif( $name == 'page' ) {
576 $this->workRevisionCount
= 0;
577 $this->workSuccessCount
= 0;
578 xml_set_element_handler( $parser, "in_page", "out_page" );
580 return $this->throwXMLerror( "Expected <page>, got <$name>" );
583 function out_mediawiki( $parser, $name ) {
584 $this->debug( "out_mediawiki $name" );
585 if( $name != "mediawiki" ) {
586 return $this->throwXMLerror( "Expected </mediawiki>, got </$name>" );
588 xml_set_element_handler( $parser, "donothing", "donothing" );
592 function in_siteinfo( $parser, $name, $attribs ) {
594 $this->debug( "in_siteinfo $name" );
604 return $this->throwXMLerror( "Element <$name> not allowed in <siteinfo>." );
608 function out_siteinfo( $parser, $name ) {
609 if( $name == "siteinfo" ) {
610 xml_set_element_handler( $parser, "in_mediawiki", "out_mediawiki" );
615 function in_page( $parser, $name, $attribs ) {
616 $this->debug( "in_page $name" );
621 $this->appendfield
= $name;
622 $this->appenddata
= "";
623 $this->parenttag
= "page";
624 xml_set_element_handler( $parser, "in_nothing", "out_append" );
625 xml_set_character_data_handler( $parser, "char_append" );
628 if( is_object( $this->pageTitle
) ) {
629 $this->workRevision
= new WikiRevision
;
630 $this->workRevision
->setTitle( $this->pageTitle
);
631 $this->workRevisionCount++
;
633 // Skipping items due to invalid page title
634 $this->workRevision
= null;
636 xml_set_element_handler( $parser, "in_revision", "out_revision" );
639 return $this->throwXMLerror( "Element <$name> not allowed in a <page>." );
643 function out_page( $parser, $name ) {
644 $this->debug( "out_page $name" );
645 if( $name != "page" ) {
646 return $this->throwXMLerror( "Expected </page>, got </$name>" );
648 xml_set_element_handler( $parser, "in_mediawiki", "out_mediawiki" );
650 $this->pageOutCallback( $this->pageTitle
, $this->origTitle
,
651 $this->workRevisionCount
, $this->workSuccessCount
);
653 $this->workTitle
= null;
654 $this->workRevision
= null;
655 $this->workRevisionCount
= 0;
656 $this->workSuccessCount
= 0;
657 $this->pageTitle
= null;
658 $this->origTitle
= null;
661 function in_nothing( $parser, $name, $attribs ) {
662 $this->debug( "in_nothing $name" );
663 return $this->throwXMLerror( "No child elements allowed here; got <$name>" );
665 function char_append( $parser, $data ) {
666 $this->debug( "char_append '$data'" );
667 $this->appenddata
.= $data;
669 function out_append( $parser, $name ) {
670 $this->debug( "out_append $name" );
671 if( $name != $this->appendfield
) {
672 return $this->throwXMLerror( "Expected </{$this->appendfield}>, got </$name>" );
674 xml_set_element_handler( $parser, "in_$this->parenttag", "out_$this->parenttag" );
675 xml_set_character_data_handler( $parser, "donothing" );
677 switch( $this->appendfield
) {
679 $this->workTitle
= $this->appenddata
;
680 $this->origTitle
= Title
::newFromText( $this->workTitle
);
681 if( !is_null( $this->mTargetNamespace
) && !is_null( $this->origTitle
) ) {
682 $this->pageTitle
= Title
::makeTitle( $this->mTargetNamespace
,
683 $this->origTitle
->getDbKey() );
685 $this->pageTitle
= Title
::newFromText( $this->workTitle
);
687 if( is_null( $this->pageTitle
) ) {
688 // Invalid page title? Ignore the page
689 $this->notice( "Skipping invalid page title '$this->workTitle'" );
691 $this->pageCallback( $this->workTitle
);
695 if ( $this->parenttag
== 'revision' ) {
696 if( $this->workRevision
)
697 $this->workRevision
->setID( $this->appenddata
);
701 if( $this->workRevision
)
702 $this->workRevision
->setText( $this->appenddata
);
705 if( $this->workRevision
)
706 $this->workRevision
->setUsername( $this->appenddata
);
709 if( $this->workRevision
)
710 $this->workRevision
->setUserIP( $this->appenddata
);
713 if( $this->workRevision
)
714 $this->workRevision
->setTimestamp( $this->appenddata
);
717 if( $this->workRevision
)
718 $this->workRevision
->setComment( $this->appenddata
);
721 if( $this->workRevision
)
722 $this->workRevision
->setMinor( true );
725 $this->debug( "Bad append: {$this->appendfield}" );
727 $this->appendfield
= "";
728 $this->appenddata
= "";
731 function in_revision( $parser, $name, $attribs ) {
732 $this->debug( "in_revision $name" );
739 $this->parenttag
= "revision";
740 $this->appendfield
= $name;
741 xml_set_element_handler( $parser, "in_nothing", "out_append" );
742 xml_set_character_data_handler( $parser, "char_append" );
745 xml_set_element_handler( $parser, "in_contributor", "out_contributor" );
748 return $this->throwXMLerror( "Element <$name> not allowed in a <revision>." );
752 function out_revision( $parser, $name ) {
753 $this->debug( "out_revision $name" );
754 if( $name != "revision" ) {
755 return $this->throwXMLerror( "Expected </revision>, got </$name>" );
757 xml_set_element_handler( $parser, "in_page", "out_page" );
759 if( $this->workRevision
) {
760 $ok = call_user_func_array( $this->mRevisionCallback
,
761 array( &$this->workRevision
, &$this ) );
763 $this->workSuccessCount++
;
768 function in_contributor( $parser, $name, $attribs ) {
769 $this->debug( "in_contributor $name" );
774 $this->parenttag
= "contributor";
775 $this->appendfield
= $name;
776 xml_set_element_handler( $parser, "in_nothing", "out_append" );
777 xml_set_character_data_handler( $parser, "char_append" );
780 $this->throwXMLerror( "Invalid tag <$name> in <contributor>" );
784 function out_contributor( $parser, $name ) {
785 $this->debug( "out_contributor $name" );
786 if( $name != "contributor" ) {
787 return $this->throwXMLerror( "Expected </contributor>, got </$name>" );
789 xml_set_element_handler( $parser, "in_revision", "out_revision" );
795 * @todo document (e.g. one-sentence class description).
796 * @addtogroup SpecialPage
798 class ImportStringSource
{
799 function ImportStringSource( $string ) {
800 $this->mString
= $string;
801 $this->mRead
= false;
808 function readChunk() {
809 if( $this->atEnd() ) {
813 return $this->mString
;
819 * @todo document (e.g. one-sentence class description).
820 * @addtogroup SpecialPage
822 class ImportStreamSource
{
823 function ImportStreamSource( $handle ) {
824 $this->mHandle
= $handle;
828 return feof( $this->mHandle
);
831 function readChunk() {
832 return fread( $this->mHandle
, 32768 );
835 static function newFromFile( $filename ) {
836 $file = @fopen
( $filename, 'rt' );
838 return new WikiErrorMsg( "importcantopen" );
840 return new ImportStreamSource( $file );
843 static function newFromUpload( $fieldname = "xmlimport" ) {
844 $upload =& $_FILES[$fieldname];
846 if( !isset( $upload ) ||
!$upload['name'] ) {
847 return new WikiErrorMsg( 'importnofile' );
849 if( !empty( $upload['error'] ) ) {
850 return new WikiErrorMsg( 'importuploaderror', $upload['error'] );
852 $fname = $upload['tmp_name'];
853 if( is_uploaded_file( $fname ) ) {
854 return ImportStreamSource
::newFromFile( $fname );
856 return new WikiErrorMsg( 'importnofile' );
860 function newFromURL( $url, $method = 'GET' ) {
861 wfDebug( __METHOD__
. ": opening $url\n" );
862 # Use the standard HTTP fetch function; it times out
863 # quicker and sorts out user-agent problems which might
864 # otherwise prevent importing from large sites, such
865 # as the Wikimedia cluster, etc.
866 $data = Http
::request( $method, $url );
867 if( $data !== false ) {
869 fwrite( $file, $data );
872 return new ImportStreamSource( $file );
874 return new WikiErrorMsg( 'importcantopen' );
878 public static function newFromInterwiki( $interwiki, $page, $history=false ) {
879 $link = Title
::newFromText( "$interwiki:Special:Export/$page" );
880 if( is_null( $link ) ||
$link->getInterwiki() == '' ) {
881 return new WikiErrorMsg( 'importbadinterwiki' );
883 $params = $history ?
'history=1' : '';
884 $url = $link->getFullUrl( $params );
885 # For interwikis, use POST to avoid redirects.
886 return ImportStreamSource
::newFromURL( $url, "POST" );