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 $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 $dbw =& wfGetDB( DB_MASTER
);
309 # Sneak a single revision into place
310 $user = User
::newFromName( $this->getUser() );
312 $userId = intval( $user->getId() );
313 $userText = $user->getName();
316 $userText = $this->getUser();
319 // avoid memory leak...?
320 $linkCache =& LinkCache
::singleton();
323 $article = new Article( $this->title
);
324 $pageId = $article->getId();
326 # must create the page...
327 $pageId = $article->insertOn( $dbw );
332 $prior = Revision
::loadFromTimestamp( $dbw, $this->title
, $this->timestamp
);
333 if( !is_null( $prior ) ) {
334 // FIXME: this could fail slightly for multiple matches :P
335 wfDebug( __METHOD__
. ": skipping existing revision for [[" .
336 $this->title
->getPrefixedText() . "]], timestamp " .
337 $this->timestamp
. "\n" );
342 # FIXME: Use original rev_id optionally
343 # FIXME: blah blah blah
345 #if( $numrows > 0 ) {
346 # return wfMsg( "importhistoryconflict" );
350 $revision = new Revision( array(
352 'text' => $this->getText(),
353 'comment' => $this->getComment(),
355 'user_text' => $userText,
356 'timestamp' => $this->timestamp
,
357 'minor_edit' => $this->minor
,
359 $revId = $revision->insertOn( $dbw );
360 $changed = $article->updateIfNewerOn( $dbw, $revision );
363 wfDebug( __METHOD__
. ": running onArticleCreate\n" );
364 Article
::onArticleCreate( $this->title
);
366 wfDebug( __METHOD__
. ": running create updates\n" );
367 $article->createUpdates( $revision );
369 } elseif( $changed ) {
370 wfDebug( __METHOD__
. ": running onArticleEdit\n" );
371 Article
::onArticleEdit( $this->title
);
373 wfDebug( __METHOD__
. ": running edit updates\n" );
374 $article->editUpdates(
390 * @subpackage SpecialPage
394 var $mPageCallback = null;
395 var $mPageOutCallback = null;
396 var $mRevisionCallback = null;
397 var $mTargetNamespace = null;
400 function WikiImporter( $source ) {
401 $this->setRevisionCallback( array( &$this, "importRevision" ) );
402 $this->mSource
= $source;
405 function throwXmlError( $err ) {
406 $this->debug( "FAILURE: $err" );
407 wfDebug( "WikiImporter XML error: $err\n" );
412 function doImport() {
413 if( empty( $this->mSource
) ) {
414 return new WikiErrorMsg( "importnotext" );
417 $parser = xml_parser_create( "UTF-8" );
419 # case folding violates XML standard, turn it off
420 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING
, false );
422 xml_set_object( $parser, $this );
423 xml_set_element_handler( $parser, "in_start", "" );
425 $offset = 0; // for context extraction on error reporting
427 $chunk = $this->mSource
->readChunk();
428 if( !xml_parse( $parser, $chunk, $this->mSource
->atEnd() ) ) {
429 wfDebug( "WikiImporter::doImport encountered XML parsing error\n" );
430 return new WikiXmlError( $parser, 'XML import parse failure', $chunk, $offset );
432 $offset +
= strlen( $chunk );
433 } while( $chunk !== false && !$this->mSource
->atEnd() );
434 xml_parser_free( $parser );
439 function debug( $data ) {
440 #wfDebug( "IMPORT: $data\n" );
443 function notice( $data ) {
444 global $wgCommandLineMode;
445 if( $wgCommandLineMode ) {
449 $wgOut->addHTML( "<li>$data</li>\n" );
454 * Sets the action to perform as each new page in the stream is reached.
455 * @param callable $callback
458 function setPageCallback( $callback ) {
459 $previous = $this->mPageCallback
;
460 $this->mPageCallback
= $callback;
465 * Sets the action to perform as each page in the stream is completed.
466 * Callback accepts the page title (as a Title object), a second object
467 * with the original title form (in case it's been overridden into a
468 * local namespace), and a count of revisions.
470 * @param callable $callback
473 function setPageOutCallback( $callback ) {
474 $previous = $this->mPageOutCallback
;
475 $this->mPageOutCallback
= $callback;
480 * Sets the action to perform as each page revision is reached.
481 * @param callable $callback
484 function setRevisionCallback( $callback ) {
485 $previous = $this->mRevisionCallback
;
486 $this->mRevisionCallback
= $callback;
491 * Set a target namespace to override the defaults
493 function setTargetNamespace( $namespace ) {
494 if( is_null( $namespace ) ) {
495 // Don't override namespaces
496 $this->mTargetNamespace
= null;
497 } elseif( $namespace >= 0 ) {
498 // FIXME: Check for validity
499 $this->mTargetNamespace
= intval( $namespace );
506 * Default per-revision callback, performs the import.
507 * @param WikiRevision $revision
510 function importRevision( &$revision ) {
511 $dbw =& wfGetDB( DB_MASTER
);
512 return $dbw->deadlockLoop( array( &$revision, 'importOldRevision' ) );
516 * Alternate per-revision callback, for debugging.
517 * @param WikiRevision $revision
520 function debugRevisionHandler( &$revision ) {
521 $this->debug( "Got revision:" );
522 if( is_object( $revision->title
) ) {
523 $this->debug( "-- Title: " . $revision->title
->getPrefixedText() );
525 $this->debug( "-- Title: <invalid>" );
527 $this->debug( "-- User: " . $revision->user_text
);
528 $this->debug( "-- Timestamp: " . $revision->timestamp
);
529 $this->debug( "-- Comment: " . $revision->comment
);
530 $this->debug( "-- Text: " . $revision->text
);
534 * Notify the callback function when a new <page> is reached.
535 * @param Title $title
538 function pageCallback( $title ) {
539 if( is_callable( $this->mPageCallback
) ) {
540 call_user_func( $this->mPageCallback
, $title );
545 * Notify the callback function when a </page> is closed.
546 * @param Title $title
547 * @param Title $origTitle
548 * @param int $revisionCount
549 * @param int $successCount number of revisions for which callback returned true
552 function pageOutCallback( $title, $origTitle, $revisionCount, $successCount ) {
553 if( is_callable( $this->mPageOutCallback
) ) {
554 call_user_func( $this->mPageOutCallback
, $title, $origTitle,
555 $revisionCount, $successCount );
560 # XML parser callbacks from here out -- beware!
561 function donothing( $parser, $x, $y="" ) {
562 #$this->debug( "donothing" );
565 function in_start( $parser, $name, $attribs ) {
566 $this->debug( "in_start $name" );
567 if( $name != "mediawiki" ) {
568 return $this->throwXMLerror( "Expected <mediawiki>, got <$name>" );
570 xml_set_element_handler( $parser, "in_mediawiki", "out_mediawiki" );
573 function in_mediawiki( $parser, $name, $attribs ) {
574 $this->debug( "in_mediawiki $name" );
575 if( $name == 'siteinfo' ) {
576 xml_set_element_handler( $parser, "in_siteinfo", "out_siteinfo" );
577 } elseif( $name == 'page' ) {
578 $this->workRevisionCount
= 0;
579 $this->workSuccessCount
= 0;
580 xml_set_element_handler( $parser, "in_page", "out_page" );
582 return $this->throwXMLerror( "Expected <page>, got <$name>" );
585 function out_mediawiki( $parser, $name ) {
586 $this->debug( "out_mediawiki $name" );
587 if( $name != "mediawiki" ) {
588 return $this->throwXMLerror( "Expected </mediawiki>, got </$name>" );
590 xml_set_element_handler( $parser, "donothing", "donothing" );
594 function in_siteinfo( $parser, $name, $attribs ) {
596 $this->debug( "in_siteinfo $name" );
606 return $this->throwXMLerror( "Element <$name> not allowed in <siteinfo>." );
610 function out_siteinfo( $parser, $name ) {
611 if( $name == "siteinfo" ) {
612 xml_set_element_handler( $parser, "in_mediawiki", "out_mediawiki" );
617 function in_page( $parser, $name, $attribs ) {
618 $this->debug( "in_page $name" );
623 $this->appendfield
= $name;
624 $this->appenddata
= "";
625 $this->parenttag
= "page";
626 xml_set_element_handler( $parser, "in_nothing", "out_append" );
627 xml_set_character_data_handler( $parser, "char_append" );
630 $this->workRevision
= new WikiRevision
;
631 $this->workRevision
->setTitle( $this->pageTitle
);
632 $this->workRevisionCount++
;
633 xml_set_element_handler( $parser, "in_revision", "out_revision" );
636 return $this->throwXMLerror( "Element <$name> not allowed in a <page>." );
640 function out_page( $parser, $name ) {
641 $this->debug( "out_page $name" );
642 if( $name != "page" ) {
643 return $this->throwXMLerror( "Expected </page>, got </$name>" );
645 xml_set_element_handler( $parser, "in_mediawiki", "out_mediawiki" );
647 $this->pageOutCallback( $this->pageTitle
, $this->origTitle
,
648 $this->workRevisionCount
, $this->workSuccessCount
);
650 $this->workTitle
= null;
651 $this->workRevision
= null;
652 $this->workRevisionCount
= 0;
653 $this->workSuccessCount
= 0;
654 $this->pageTitle
= null;
655 $this->origTitle
= null;
658 function in_nothing( $parser, $name, $attribs ) {
659 $this->debug( "in_nothing $name" );
660 return $this->throwXMLerror( "No child elements allowed here; got <$name>" );
662 function char_append( $parser, $data ) {
663 $this->debug( "char_append '$data'" );
664 $this->appenddata
.= $data;
666 function out_append( $parser, $name ) {
667 $this->debug( "out_append $name" );
668 if( $name != $this->appendfield
) {
669 return $this->throwXMLerror( "Expected </{$this->appendfield}>, got </$name>" );
671 xml_set_element_handler( $parser, "in_$this->parenttag", "out_$this->parenttag" );
672 xml_set_character_data_handler( $parser, "donothing" );
674 switch( $this->appendfield
) {
676 $this->workTitle
= $this->appenddata
;
677 $this->origTitle
= Title
::newFromText( $this->workTitle
);
678 if( !is_null( $this->mTargetNamespace
) && !is_null( $this->origTitle
) ) {
679 $this->pageTitle
= Title
::makeTitle( $this->mTargetNamespace
,
680 $this->origTitle
->getDbKey() );
682 $this->pageTitle
= Title
::newFromText( $this->workTitle
);
684 $this->pageCallback( $this->workTitle
);
687 if ( $this->parenttag
== 'revision' ) {
688 $this->workRevision
->setID( $this->appenddata
);
692 $this->workRevision
->setText( $this->appenddata
);
695 $this->workRevision
->setUsername( $this->appenddata
);
698 $this->workRevision
->setUserIP( $this->appenddata
);
701 $this->workRevision
->setTimestamp( $this->appenddata
);
704 $this->workRevision
->setComment( $this->appenddata
);
707 $this->workRevision
->setMinor( true );
710 $this->debug( "Bad append: {$this->appendfield}" );
712 $this->appendfield
= "";
713 $this->appenddata
= "";
716 function in_revision( $parser, $name, $attribs ) {
717 $this->debug( "in_revision $name" );
724 $this->parenttag
= "revision";
725 $this->appendfield
= $name;
726 xml_set_element_handler( $parser, "in_nothing", "out_append" );
727 xml_set_character_data_handler( $parser, "char_append" );
730 xml_set_element_handler( $parser, "in_contributor", "out_contributor" );
733 return $this->throwXMLerror( "Element <$name> not allowed in a <revision>." );
737 function out_revision( $parser, $name ) {
738 $this->debug( "out_revision $name" );
739 if( $name != "revision" ) {
740 return $this->throwXMLerror( "Expected </revision>, got </$name>" );
742 xml_set_element_handler( $parser, "in_page", "out_page" );
744 $ok = call_user_func_array( $this->mRevisionCallback
,
745 array( &$this->workRevision
, &$this ) );
747 $this->workSuccessCount++
;
751 function in_contributor( $parser, $name, $attribs ) {
752 $this->debug( "in_contributor $name" );
757 $this->parenttag
= "contributor";
758 $this->appendfield
= $name;
759 xml_set_element_handler( $parser, "in_nothing", "out_append" );
760 xml_set_character_data_handler( $parser, "char_append" );
763 $this->throwXMLerror( "Invalid tag <$name> in <contributor>" );
767 function out_contributor( $parser, $name ) {
768 $this->debug( "out_contributor $name" );
769 if( $name != "contributor" ) {
770 return $this->throwXMLerror( "Expected </contributor>, got </$name>" );
772 xml_set_element_handler( $parser, "in_revision", "out_revision" );
777 /** @package MediaWiki */
778 class ImportStringSource
{
779 function ImportStringSource( $string ) {
780 $this->mString
= $string;
781 $this->mRead
= false;
788 function readChunk() {
789 if( $this->atEnd() ) {
793 return $this->mString
;
798 /** @package MediaWiki */
799 class ImportStreamSource
{
800 function ImportStreamSource( $handle ) {
801 $this->mHandle
= $handle;
805 return feof( $this->mHandle
);
808 function readChunk() {
809 return fread( $this->mHandle
, 32768 );
812 function newFromFile( $filename ) {
813 $file = @fopen
( $filename, 'rt' );
815 return new WikiErrorMsg( "importcantopen" );
817 return new ImportStreamSource( $file );
820 static function newFromUpload( $fieldname = "xmlimport" ) {
821 $upload =& $_FILES[$fieldname];
823 if( !isset( $upload ) ||
!$upload['name'] ) {
824 return new WikiErrorMsg( 'importnofile' );
826 if( !empty( $upload['error'] ) ) {
827 return new WikiErrorMsg( 'importuploaderror', $upload['error'] );
829 $fname = $upload['tmp_name'];
830 if( is_uploaded_file( $fname ) ) {
831 return ImportStreamSource
::newFromFile( $fname );
833 return new WikiErrorMsg( 'importnofile' );
837 function newFromURL( $url ) {
838 wfDebug( __METHOD__
. ": opening $url\n" );
839 # fopen-wrappers are normally turned off for security.
840 ini_set( "allow_url_fopen", true );
841 $ret = ImportStreamSource
::newFromFile( $url );
842 ini_set( "allow_url_fopen", false );
846 public static function newFromInterwiki( $interwiki, $page, $history=false ) {
847 $link = Title
::newFromText( "$interwiki:Special:Export/$page" );
848 if( is_null( $link ) ||
$link->getInterwiki() == '' ) {
849 return new WikiErrorMsg( 'importbadinterwiki' );
851 $params = $history ?
'history=1' : '';
852 $url = $link->getFullUrl( $params );
853 return ImportStreamSource
::newFromURL( $url );