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
23 * @subpackage SpecialPage
29 function wfSpecialImport( $page = '' ) {
30 global $wgUser, $wgOut, $wgRequest, $wgTitle, $wgImportSources;
31 global $wgImportTargetNamespace;
34 $namespace = $wgImportTargetNamespace;
38 if( $wgRequest->wasPosted() && $wgRequest->getVal( 'action' ) == 'submit') {
40 $namespace = $wgRequest->getIntOrNull( 'namespace' );
42 switch( $wgRequest->getVal( "source" ) ) {
45 if( $wgUser->isAllowed( 'importupload' ) ) {
46 $source = ImportStreamSource
::newFromUpload( "xmlimport" );
48 return $wgOut->permissionRequired( 'importupload' );
52 $interwiki = $wgRequest->getVal( 'interwiki' );
53 $history = $wgRequest->getCheck( 'interwikiHistory' );
54 $frompage = $wgRequest->getText( "frompage" );
55 $source = ImportStreamSource
::newFromInterwiki(
61 $source = new WikiErrorMsg( "importunknownsource" );
64 if( WikiError
::isError( $source ) ) {
65 $wgOut->addWikiText( wfEscapeWikiText( $source->getMessage() ) );
67 $wgOut->addWikiText( wfMsg( "importstart" ) );
69 $importer = new WikiImporter( $source );
70 if( !is_null( $namespace ) ) {
71 $importer->setTargetNamespace( $namespace );
73 $reporter = new ImportReporter( $importer, $isUpload, $interwiki );
76 $result = $importer->doImport();
79 if( WikiError
::isError( $result ) ) {
80 $wgOut->addWikiText( wfMsg( "importfailed",
81 wfEscapeWikiText( $result->getMessage() ) ) );
84 $wgOut->addWikiText( wfMsg( "importsuccess" ) );
89 $action = $wgTitle->escapeLocalUrl( 'action=submit' );
91 if( $wgUser->isAllowed( 'importupload' ) ) {
92 $wgOut->addWikiText( wfMsg( "importtext" ) );
95 <legend>" . wfMsgHtml('upload') . "</legend>
96 <form enctype='multipart/form-data' method='post' action=\"$action\">
97 <input type='hidden' name='action' value='submit' />
98 <input type='hidden' name='source' value='upload' />
99 <input type='hidden' name='MAX_FILE_SIZE' value='2000000' />
100 <input type='file' name='xmlimport' value='' size='30' />
101 <input type='submit' value=\"" . wfMsgHtml( "uploadbtn" ) . "\" />
106 if( empty( $wgImportSources ) ) {
107 $wgOut->addWikiText( wfMsg( 'importnosources' ) );
111 if( !empty( $wgImportSources ) ) {
114 <legend>" . wfMsgHtml('importinterwiki') . "</legend>
115 <form method='post' action=\"$action\">" .
116 $wgOut->parse( wfMsg( 'import-interwiki-text' ) ) . "
117 <input type='hidden' name='action' value='submit' />
118 <input type='hidden' name='source' value='interwiki' />
122 <select name='interwiki'>" );
123 foreach( $wgImportSources as $prefix ) {
124 $iw = htmlspecialchars( $prefix );
125 $selected = ($interwiki === $prefix) ?
' selected="selected"' : '';
126 $wgOut->addHTML( "<option value=\"$iw\"$selected>$iw</option>\n" );
132 wfInput( 'frompage', 50, $frompage ) .
138 wfCheckLabel( wfMsg( 'import-interwiki-history' ),
139 'interwikiHistory', 'interwikiHistory', $history ) .
145 " . wfMsgHtml( 'import-interwiki-namespace' ) . " " .
146 HTMLnamespaceselector( $namespace, '' ) . "
152 wfSubmitButton( wfMsg( 'import-interwiki-submit' ) ) .
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 $nullRevId = $nullRevision->insertOn( $dbw );
217 if( $this->mPageCount
== 0 ) {
218 $wgOut->addHtml( "<li>" . wfMsgHtml( 'importnopages' ) . "</li>\n" );
220 $wgOut->addHtml( "</ul>\n" );
227 * @subpackage SpecialPage
232 var $timestamp = "20010115000000";
239 function setTitle( $title ) {
240 if( is_object( $title ) ) {
241 $this->title
= $title;
242 } elseif( is_null( $title ) ) {
243 throw new MWException( "WikiRevision given a null title in import. You may need to adjust \$wgLegalTitleChars." );
245 throw new MWException( "WikiRevision given non-object title in import." );
249 function setID( $id ) {
253 function setTimestamp( $ts ) {
254 # 2003-08-05T18:30:02Z
255 $this->timestamp
= wfTimestamp( TS_MW
, $ts );
258 function setUsername( $user ) {
259 $this->user_text
= $user;
262 function setUserIP( $ip ) {
263 $this->user_text
= $ip;
266 function setText( $text ) {
270 function setComment( $text ) {
271 $this->comment
= $text;
274 function setMinor( $minor ) {
275 $this->minor
= (bool)$minor;
278 function getTitle() {
286 function getTimestamp() {
287 return $this->timestamp
;
291 return $this->user_text
;
298 function getComment() {
299 return $this->comment
;
302 function getMinor() {
306 function importOldRevision() {
307 $fname = "WikiImporter::importOldRevision";
308 $dbw =& wfGetDB( DB_MASTER
);
310 # Sneak a single revision into place
311 $user = User
::newFromName( $this->getUser() );
313 $userId = intval( $user->getId() );
314 $userText = $user->getName();
317 $userText = $this->getUser();
320 // avoid memory leak...?
321 $linkCache =& LinkCache
::singleton();
324 $article = new Article( $this->title
);
325 $pageId = $article->getId();
327 # must create the page...
328 $pageId = $article->insertOn( $dbw );
333 $prior = Revision
::loadFromTimestamp( $dbw, $this->title
, $this->timestamp
);
334 if( !is_null( $prior ) ) {
335 // FIXME: this could fail slightly for multiple matches :P
336 wfDebug( __METHOD__
. ": skipping existing revision for [[" .
337 $this->title
->getPrefixedText() . "]], timestamp " .
338 $this->timestamp
. "\n" );
343 # FIXME: Use original rev_id optionally
344 # FIXME: blah blah blah
346 #if( $numrows > 0 ) {
347 # return wfMsg( "importhistoryconflict" );
351 $revision = new Revision( array(
353 'text' => $this->getText(),
354 'comment' => $this->getComment(),
356 'user_text' => $userText,
357 'timestamp' => $this->timestamp
,
358 'minor_edit' => $this->minor
,
360 $revId = $revision->insertOn( $dbw );
361 $changed = $article->updateIfNewerOn( $dbw, $revision );
364 wfDebug( __METHOD__
. ": running onArticleCreate\n" );
365 Article
::onArticleCreate( $this->title
);
367 wfDebug( __METHOD__
. ": running create updates\n" );
368 $article->createUpdates( $revision );
370 } elseif( $changed ) {
371 wfDebug( __METHOD__
. ": running onArticleEdit\n" );
372 Article
::onArticleEdit( $this->title
);
374 wfDebug( __METHOD__
. ": running edit updates\n" );
375 $article->editUpdates(
391 * @subpackage SpecialPage
395 var $mPageCallback = null;
396 var $mPageOutCallback = null;
397 var $mRevisionCallback = null;
398 var $mTargetNamespace = null;
401 function WikiImporter( $source ) {
402 $this->setRevisionCallback( array( &$this, "importRevision" ) );
403 $this->mSource
= $source;
406 function throwXmlError( $err ) {
407 $this->debug( "FAILURE: $err" );
408 wfDebug( "WikiImporter XML error: $err\n" );
413 function doImport() {
414 if( empty( $this->mSource
) ) {
415 return new WikiErrorMsg( "importnotext" );
418 $parser = xml_parser_create( "UTF-8" );
420 # case folding violates XML standard, turn it off
421 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING
, false );
423 xml_set_object( $parser, $this );
424 xml_set_element_handler( $parser, "in_start", "" );
426 $offset = 0; // for context extraction on error reporting
428 $chunk = $this->mSource
->readChunk();
429 if( !xml_parse( $parser, $chunk, $this->mSource
->atEnd() ) ) {
430 wfDebug( "WikiImporter::doImport encountered XML parsing error\n" );
431 return new WikiXmlError( $parser, 'XML import parse failure', $chunk, $offset );
433 $offset +
= strlen( $chunk );
434 } while( $chunk !== false && !$this->mSource
->atEnd() );
435 xml_parser_free( $parser );
440 function debug( $data ) {
441 #wfDebug( "IMPORT: $data\n" );
444 function notice( $data ) {
445 global $wgCommandLineMode;
446 if( $wgCommandLineMode ) {
450 $wgOut->addHTML( "<li>$data</li>\n" );
455 * Sets the action to perform as each new page in the stream is reached.
456 * @param callable $callback
459 function setPageCallback( $callback ) {
460 $previous = $this->mPageCallback
;
461 $this->mPageCallback
= $callback;
466 * Sets the action to perform as each page in the stream is completed.
467 * Callback accepts the page title (as a Title object), a second object
468 * with the original title form (in case it's been overridden into a
469 * local namespace), and a count of revisions.
471 * @param callable $callback
474 function setPageOutCallback( $callback ) {
475 $previous = $this->mPageOutCallback
;
476 $this->mPageOutCallback
= $callback;
481 * Sets the action to perform as each page revision is reached.
482 * @param callable $callback
485 function setRevisionCallback( $callback ) {
486 $previous = $this->mRevisionCallback
;
487 $this->mRevisionCallback
= $callback;
492 * Set a target namespace to override the defaults
494 function setTargetNamespace( $namespace ) {
495 if( is_null( $namespace ) ) {
496 // Don't override namespaces
497 $this->mTargetNamespace
= null;
498 } elseif( $namespace >= 0 ) {
499 // FIXME: Check for validity
500 $this->mTargetNamespace
= intval( $namespace );
507 * Default per-revision callback, performs the import.
508 * @param WikiRevision $revision
511 function importRevision( &$revision ) {
512 $dbw =& wfGetDB( DB_MASTER
);
513 return $dbw->deadlockLoop( array( &$revision, 'importOldRevision' ) );
517 * Alternate per-revision callback, for debugging.
518 * @param WikiRevision $revision
521 function debugRevisionHandler( &$revision ) {
522 $this->debug( "Got revision:" );
523 if( is_object( $revision->title
) ) {
524 $this->debug( "-- Title: " . $revision->title
->getPrefixedText() );
526 $this->debug( "-- Title: <invalid>" );
528 $this->debug( "-- User: " . $revision->user_text
);
529 $this->debug( "-- Timestamp: " . $revision->timestamp
);
530 $this->debug( "-- Comment: " . $revision->comment
);
531 $this->debug( "-- Text: " . $revision->text
);
535 * Notify the callback function when a new <page> is reached.
536 * @param Title $title
539 function pageCallback( $title ) {
540 if( is_callable( $this->mPageCallback
) ) {
541 call_user_func( $this->mPageCallback
, $title );
546 * Notify the callback function when a </page> is closed.
547 * @param Title $title
548 * @param Title $origTitle
549 * @param int $revisionCount
550 * @param int $successCount number of revisions for which callback returned true
553 function pageOutCallback( $title, $origTitle, $revisionCount, $successCount ) {
554 if( is_callable( $this->mPageOutCallback
) ) {
555 call_user_func( $this->mPageOutCallback
, $title, $origTitle,
556 $revisionCount, $successCount );
561 # XML parser callbacks from here out -- beware!
562 function donothing( $parser, $x, $y="" ) {
563 #$this->debug( "donothing" );
566 function in_start( $parser, $name, $attribs ) {
567 $this->debug( "in_start $name" );
568 if( $name != "mediawiki" ) {
569 return $this->throwXMLerror( "Expected <mediawiki>, got <$name>" );
571 xml_set_element_handler( $parser, "in_mediawiki", "out_mediawiki" );
574 function in_mediawiki( $parser, $name, $attribs ) {
575 $this->debug( "in_mediawiki $name" );
576 if( $name == 'siteinfo' ) {
577 xml_set_element_handler( $parser, "in_siteinfo", "out_siteinfo" );
578 } elseif( $name == 'page' ) {
579 $this->workRevisionCount
= 0;
580 $this->workSuccessCount
= 0;
581 xml_set_element_handler( $parser, "in_page", "out_page" );
583 return $this->throwXMLerror( "Expected <page>, got <$name>" );
586 function out_mediawiki( $parser, $name ) {
587 $this->debug( "out_mediawiki $name" );
588 if( $name != "mediawiki" ) {
589 return $this->throwXMLerror( "Expected </mediawiki>, got </$name>" );
591 xml_set_element_handler( $parser, "donothing", "donothing" );
595 function in_siteinfo( $parser, $name, $attribs ) {
597 $this->debug( "in_siteinfo $name" );
607 return $this->throwXMLerror( "Element <$name> not allowed in <siteinfo>." );
611 function out_siteinfo( $parser, $name ) {
612 if( $name == "siteinfo" ) {
613 xml_set_element_handler( $parser, "in_mediawiki", "out_mediawiki" );
618 function in_page( $parser, $name, $attribs ) {
619 $this->debug( "in_page $name" );
624 $this->appendfield
= $name;
625 $this->appenddata
= "";
626 $this->parenttag
= "page";
627 xml_set_element_handler( $parser, "in_nothing", "out_append" );
628 xml_set_character_data_handler( $parser, "char_append" );
631 $this->workRevision
= new WikiRevision
;
632 $this->workRevision
->setTitle( $this->pageTitle
);
633 $this->workRevisionCount++
;
634 xml_set_element_handler( $parser, "in_revision", "out_revision" );
637 return $this->throwXMLerror( "Element <$name> not allowed in a <page>." );
641 function out_page( $parser, $name ) {
642 $this->debug( "out_page $name" );
643 if( $name != "page" ) {
644 return $this->throwXMLerror( "Expected </page>, got </$name>" );
646 xml_set_element_handler( $parser, "in_mediawiki", "out_mediawiki" );
648 $this->pageOutCallback( $this->pageTitle
, $this->origTitle
,
649 $this->workRevisionCount
, $this->workSuccessCount
);
651 $this->workTitle
= null;
652 $this->workRevision
= null;
653 $this->workRevisionCount
= 0;
654 $this->workSuccessCount
= 0;
655 $this->pageTitle
= null;
656 $this->origTitle
= null;
659 function in_nothing( $parser, $name, $attribs ) {
660 $this->debug( "in_nothing $name" );
661 return $this->throwXMLerror( "No child elements allowed here; got <$name>" );
663 function char_append( $parser, $data ) {
664 $this->debug( "char_append '$data'" );
665 $this->appenddata
.= $data;
667 function out_append( $parser, $name ) {
668 $this->debug( "out_append $name" );
669 if( $name != $this->appendfield
) {
670 return $this->throwXMLerror( "Expected </{$this->appendfield}>, got </$name>" );
672 xml_set_element_handler( $parser, "in_$this->parenttag", "out_$this->parenttag" );
673 xml_set_character_data_handler( $parser, "donothing" );
675 switch( $this->appendfield
) {
677 $this->workTitle
= $this->appenddata
;
678 $this->origTitle
= Title
::newFromText( $this->workTitle
);
679 if( !is_null( $this->mTargetNamespace
) && !is_null( $this->origTitle
) ) {
680 $this->pageTitle
= Title
::makeTitle( $this->mTargetNamespace
,
681 $this->origTitle
->getDbKey() );
683 $this->pageTitle
= Title
::newFromText( $this->workTitle
);
685 $this->pageCallback( $this->workTitle
);
688 if ( $this->parenttag
== 'revision' ) {
689 $this->workRevision
->setID( $this->appenddata
);
693 $this->workRevision
->setText( $this->appenddata
);
696 $this->workRevision
->setUsername( $this->appenddata
);
699 $this->workRevision
->setUserIP( $this->appenddata
);
702 $this->workRevision
->setTimestamp( $this->appenddata
);
705 $this->workRevision
->setComment( $this->appenddata
);
708 $this->workRevision
->setMinor( true );
711 $this->debug( "Bad append: {$this->appendfield}" );
713 $this->appendfield
= "";
714 $this->appenddata
= "";
717 function in_revision( $parser, $name, $attribs ) {
718 $this->debug( "in_revision $name" );
725 $this->parenttag
= "revision";
726 $this->appendfield
= $name;
727 xml_set_element_handler( $parser, "in_nothing", "out_append" );
728 xml_set_character_data_handler( $parser, "char_append" );
731 xml_set_element_handler( $parser, "in_contributor", "out_contributor" );
734 return $this->throwXMLerror( "Element <$name> not allowed in a <revision>." );
738 function out_revision( $parser, $name ) {
739 $this->debug( "out_revision $name" );
740 if( $name != "revision" ) {
741 return $this->throwXMLerror( "Expected </revision>, got </$name>" );
743 xml_set_element_handler( $parser, "in_page", "out_page" );
745 $ok = call_user_func_array( $this->mRevisionCallback
,
746 array( &$this->workRevision
, &$this ) );
748 $this->workSuccessCount++
;
752 function in_contributor( $parser, $name, $attribs ) {
753 $this->debug( "in_contributor $name" );
758 $this->parenttag
= "contributor";
759 $this->appendfield
= $name;
760 xml_set_element_handler( $parser, "in_nothing", "out_append" );
761 xml_set_character_data_handler( $parser, "char_append" );
764 $this->throwXMLerror( "Invalid tag <$name> in <contributor>" );
768 function out_contributor( $parser, $name ) {
769 $this->debug( "out_contributor $name" );
770 if( $name != "contributor" ) {
771 return $this->throwXMLerror( "Expected </contributor>, got </$name>" );
773 xml_set_element_handler( $parser, "in_revision", "out_revision" );
778 /** @package MediaWiki */
779 class ImportStringSource
{
780 function ImportStringSource( $string ) {
781 $this->mString
= $string;
782 $this->mRead
= false;
789 function readChunk() {
790 if( $this->atEnd() ) {
794 return $this->mString
;
799 /** @package MediaWiki */
800 class ImportStreamSource
{
801 function ImportStreamSource( $handle ) {
802 $this->mHandle
= $handle;
806 return feof( $this->mHandle
);
809 function readChunk() {
810 return fread( $this->mHandle
, 32768 );
813 function newFromFile( $filename ) {
814 $file = @fopen
( $filename, 'rt' );
816 return new WikiErrorMsg( "importcantopen" );
818 return new ImportStreamSource( $file );
821 function newFromUpload( $fieldname = "xmlimport" ) {
822 $upload =& $_FILES[$fieldname];
824 if( !isset( $upload ) ||
!$upload['name'] ) {
825 return new WikiErrorMsg( 'importnofile' );
827 if( !empty( $upload['error'] ) ) {
828 return new WikiErrorMsg( 'importuploaderror', $upload['error'] );
830 $fname = $upload['tmp_name'];
831 if( is_uploaded_file( $fname ) ) {
832 return ImportStreamSource
::newFromFile( $fname );
834 return new WikiErrorMsg( 'importnofile' );
838 function newFromURL( $url ) {
839 wfDebug( __METHOD__
. ": opening $url\n" );
840 # fopen-wrappers are normally turned off for security.
841 ini_set( "allow_url_fopen", true );
842 $ret = ImportStreamSource
::newFromFile( $url );
843 ini_set( "allow_url_fopen", false );
847 function newFromInterwiki( $interwiki, $page, $history=false ) {
848 $link = Title
::newFromText( "$interwiki:Special:Export/$page" );
849 if( is_null( $link ) ||
$link->getInterwiki() == '' ) {
850 return new WikiErrorMsg( 'importbadinterwiki' );
852 $params = $history ?
'history=1' : '';
853 $url = $link->getFullUrl( $params );
854 return ImportStreamSource
::newFromURL( $url );