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->getLocalUrl( '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='file' name='xmlimport' value='' size='30' />
99 <input type='submit' value=\"" . wfMsgHtml( "uploadbtn" ) . "\" />
104 if( empty( $wgImportSources ) ) {
105 $wgOut->addWikiText( wfMsg( 'importnosources' ) );
109 if( !empty( $wgImportSources ) ) {
112 <legend>" . wfMsgHtml('importinterwiki') . "</legend>
113 <form method='post' action=\"$action\">" .
114 $wgOut->parse( wfMsg( 'import-interwiki-text' ) ) . "
115 <input type='hidden' name='action' value='submit' />
116 <input type='hidden' name='source' value='interwiki' />
120 <select name='interwiki'>" );
121 foreach( $wgImportSources as $prefix ) {
122 $iw = htmlspecialchars( $prefix );
123 $selected = ($interwiki === $prefix) ?
' selected="selected"' : '';
124 $wgOut->addHTML( "<option value=\"$iw\"$selected>$iw</option>\n" );
130 wfInput( 'frompage', 50, $frompage ) .
136 wfCheckLabel( wfMsg( 'import-interwiki-history' ),
137 'interwikiHistory', 'interwikiHistory', $history ) .
143 " . wfMsgHtml( 'import-interwiki-namespace' ) . " " .
144 HTMLnamespaceselector( $namespace, '' ) . "
150 wfSubmitButton( wfMsg( 'import-interwiki-submit' ) ) .
162 * @addtogroup SpecialPage
164 class ImportReporter
{
165 function __construct( $importer, $upload, $interwiki ) {
166 $importer->setPageOutCallback( array( $this, 'reportPage' ) );
167 $this->mPageCount
= 0;
168 $this->mIsUpload
= $upload;
169 $this->mInterwiki
= $interwiki;
174 $wgOut->addHtml( "<ul>\n" );
177 function reportPage( $title, $origTitle, $revisionCount, $successCount ) {
178 global $wgOut, $wgUser, $wgLang, $wgContLang;
180 $skin = $wgUser->getSkin();
184 $localCount = $wgLang->formatNum( $successCount );
185 $contentCount = $wgContLang->formatNum( $successCount );
187 $wgOut->addHtml( "<li>" . $skin->makeKnownLinkObj( $title ) .
189 wfMsgExt( 'import-revision-count', array( 'parsemag', 'escape' ), $localCount ) .
192 if( $successCount > 0 ) {
193 $log = new LogPage( 'import' );
194 if( $this->mIsUpload
) {
195 $detail = wfMsgExt( 'import-logentry-upload-detail', array( 'content', 'parsemag' ),
197 $log->addEntry( 'upload', $title, $detail );
199 $interwiki = '[[:' . $this->mInterwiki
. ':' .
200 $origTitle->getPrefixedText() . ']]';
201 $detail = wfMsgExt( 'import-logentry-interwiki-detail', array( 'content', 'parsemag' ),
202 $contentCount, $interwiki );
203 $log->addEntry( 'interwiki', $title, $detail );
206 $comment = $detail; // quick
207 $dbw = wfGetDB( DB_MASTER
);
208 $nullRevision = Revision
::newNullRevision(
209 $dbw, $title->getArticleId(), $comment, true );
210 $nullRevision->insertOn( $dbw );
212 $article = new Article( $title );
213 $article->updateRevisionOn( $dbw, $nullRevision );
219 if( $this->mPageCount
== 0 ) {
220 $wgOut->addHtml( "<li>" . wfMsgHtml( 'importnopages' ) . "</li>\n" );
222 $wgOut->addHtml( "</ul>\n" );
228 * @addtogroup SpecialPage
233 var $timestamp = "20010115000000";
240 function setTitle( $title ) {
241 if( is_object( $title ) ) {
242 $this->title
= $title;
243 } elseif( is_null( $title ) ) {
244 throw new MWException( "WikiRevision given a null title in import. You may need to adjust \$wgLegalTitleChars." );
246 throw new MWException( "WikiRevision given non-object title in import." );
250 function setID( $id ) {
254 function setTimestamp( $ts ) {
255 # 2003-08-05T18:30:02Z
256 $this->timestamp
= wfTimestamp( TS_MW
, $ts );
259 function setUsername( $user ) {
260 $this->user_text
= $user;
263 function setUserIP( $ip ) {
264 $this->user_text
= $ip;
267 function setText( $text ) {
271 function setComment( $text ) {
272 $this->comment
= $text;
275 function setMinor( $minor ) {
276 $this->minor
= (bool)$minor;
279 function getTitle() {
287 function getTimestamp() {
288 return $this->timestamp
;
292 return $this->user_text
;
299 function getComment() {
300 return $this->comment
;
303 function getMinor() {
307 function 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(
389 * implements Special:Import
390 * @addtogroup 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>" . htmlspecialchars( $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 if( is_object( $this->pageTitle
) ) {
631 $this->workRevision
= new WikiRevision
;
632 $this->workRevision
->setTitle( $this->pageTitle
);
633 $this->workRevisionCount++
;
635 // Skipping items due to invalid page title
636 $this->workRevision
= null;
638 xml_set_element_handler( $parser, "in_revision", "out_revision" );
641 return $this->throwXMLerror( "Element <$name> not allowed in a <page>." );
645 function out_page( $parser, $name ) {
646 $this->debug( "out_page $name" );
647 if( $name != "page" ) {
648 return $this->throwXMLerror( "Expected </page>, got </$name>" );
650 xml_set_element_handler( $parser, "in_mediawiki", "out_mediawiki" );
652 $this->pageOutCallback( $this->pageTitle
, $this->origTitle
,
653 $this->workRevisionCount
, $this->workSuccessCount
);
655 $this->workTitle
= null;
656 $this->workRevision
= null;
657 $this->workRevisionCount
= 0;
658 $this->workSuccessCount
= 0;
659 $this->pageTitle
= null;
660 $this->origTitle
= null;
663 function in_nothing( $parser, $name, $attribs ) {
664 $this->debug( "in_nothing $name" );
665 return $this->throwXMLerror( "No child elements allowed here; got <$name>" );
667 function char_append( $parser, $data ) {
668 $this->debug( "char_append '$data'" );
669 $this->appenddata
.= $data;
671 function out_append( $parser, $name ) {
672 $this->debug( "out_append $name" );
673 if( $name != $this->appendfield
) {
674 return $this->throwXMLerror( "Expected </{$this->appendfield}>, got </$name>" );
676 xml_set_element_handler( $parser, "in_$this->parenttag", "out_$this->parenttag" );
677 xml_set_character_data_handler( $parser, "donothing" );
679 switch( $this->appendfield
) {
681 $this->workTitle
= $this->appenddata
;
682 $this->origTitle
= Title
::newFromText( $this->workTitle
);
683 if( !is_null( $this->mTargetNamespace
) && !is_null( $this->origTitle
) ) {
684 $this->pageTitle
= Title
::makeTitle( $this->mTargetNamespace
,
685 $this->origTitle
->getDBkey() );
687 $this->pageTitle
= Title
::newFromText( $this->workTitle
);
689 if( is_null( $this->pageTitle
) ) {
690 // Invalid page title? Ignore the page
691 $this->notice( "Skipping invalid page title '$this->workTitle'" );
693 $this->pageCallback( $this->workTitle
);
697 if ( $this->parenttag
== 'revision' ) {
698 if( $this->workRevision
)
699 $this->workRevision
->setID( $this->appenddata
);
703 if( $this->workRevision
)
704 $this->workRevision
->setText( $this->appenddata
);
707 if( $this->workRevision
)
708 $this->workRevision
->setUsername( $this->appenddata
);
711 if( $this->workRevision
)
712 $this->workRevision
->setUserIP( $this->appenddata
);
715 if( $this->workRevision
)
716 $this->workRevision
->setTimestamp( $this->appenddata
);
719 if( $this->workRevision
)
720 $this->workRevision
->setComment( $this->appenddata
);
723 if( $this->workRevision
)
724 $this->workRevision
->setMinor( true );
727 $this->debug( "Bad append: {$this->appendfield}" );
729 $this->appendfield
= "";
730 $this->appenddata
= "";
733 function in_revision( $parser, $name, $attribs ) {
734 $this->debug( "in_revision $name" );
741 $this->parenttag
= "revision";
742 $this->appendfield
= $name;
743 xml_set_element_handler( $parser, "in_nothing", "out_append" );
744 xml_set_character_data_handler( $parser, "char_append" );
747 xml_set_element_handler( $parser, "in_contributor", "out_contributor" );
750 return $this->throwXMLerror( "Element <$name> not allowed in a <revision>." );
754 function out_revision( $parser, $name ) {
755 $this->debug( "out_revision $name" );
756 if( $name != "revision" ) {
757 return $this->throwXMLerror( "Expected </revision>, got </$name>" );
759 xml_set_element_handler( $parser, "in_page", "out_page" );
761 if( $this->workRevision
) {
762 $ok = call_user_func_array( $this->mRevisionCallback
,
763 array( &$this->workRevision
, &$this ) );
765 $this->workSuccessCount++
;
770 function in_contributor( $parser, $name, $attribs ) {
771 $this->debug( "in_contributor $name" );
776 $this->parenttag
= "contributor";
777 $this->appendfield
= $name;
778 xml_set_element_handler( $parser, "in_nothing", "out_append" );
779 xml_set_character_data_handler( $parser, "char_append" );
782 $this->throwXMLerror( "Invalid tag <$name> in <contributor>" );
786 function out_contributor( $parser, $name ) {
787 $this->debug( "out_contributor $name" );
788 if( $name != "contributor" ) {
789 return $this->throwXMLerror( "Expected </contributor>, got </$name>" );
791 xml_set_element_handler( $parser, "in_revision", "out_revision" );
797 * @todo document (e.g. one-sentence class description).
798 * @addtogroup SpecialPage
800 class ImportStringSource
{
801 function ImportStringSource( $string ) {
802 $this->mString
= $string;
803 $this->mRead
= false;
810 function readChunk() {
811 if( $this->atEnd() ) {
815 return $this->mString
;
821 * @todo document (e.g. one-sentence class description).
822 * @addtogroup SpecialPage
824 class ImportStreamSource
{
825 function ImportStreamSource( $handle ) {
826 $this->mHandle
= $handle;
830 return feof( $this->mHandle
);
833 function readChunk() {
834 return fread( $this->mHandle
, 32768 );
837 static function newFromFile( $filename ) {
838 $file = @fopen
( $filename, 'rt' );
840 return new WikiErrorMsg( "importcantopen" );
842 return new ImportStreamSource( $file );
845 static function newFromUpload( $fieldname = "xmlimport" ) {
846 $upload =& $_FILES[$fieldname];
848 if( !isset( $upload ) ||
!$upload['name'] ) {
849 return new WikiErrorMsg( 'importnofile' );
851 if( !empty( $upload['error'] ) ) {
852 switch($upload['error']){
853 case 1: # The uploaded file exceeds the upload_max_filesize directive in php.ini.
854 return new WikiErrorMsg( 'importuploaderrorsize' );
855 case 2: # The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
856 return new WikiErrorMsg( 'importuploaderrorsize' );
857 case 3: # The uploaded file was only partially uploaded
858 return new WikiErrorMsg( 'importuploaderrorpartial' );
859 case 6: #Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.
860 return new WikiErrorMsg( 'importuploaderrortemp' );
861 # case else: # Currently impossible
865 $fname = $upload['tmp_name'];
866 if( is_uploaded_file( $fname ) ) {
867 return ImportStreamSource
::newFromFile( $fname );
869 return new WikiErrorMsg( 'importnofile' );
873 function newFromURL( $url, $method = 'GET' ) {
874 wfDebug( __METHOD__
. ": opening $url\n" );
875 # Use the standard HTTP fetch function; it times out
876 # quicker and sorts out user-agent problems which might
877 # otherwise prevent importing from large sites, such
878 # as the Wikimedia cluster, etc.
879 $data = Http
::request( $method, $url );
880 if( $data !== false ) {
882 fwrite( $file, $data );
885 return new ImportStreamSource( $file );
887 return new WikiErrorMsg( 'importcantopen' );
891 public static function newFromInterwiki( $interwiki, $page, $history=false ) {
892 $link = Title
::newFromText( "$interwiki:Special:Export/$page" );
893 if( is_null( $link ) ||
$link->getInterwiki() == '' ) {
894 return new WikiErrorMsg( 'importbadinterwiki' );
896 $params = $history ?
'history=1' : '';
897 $url = $link->getFullUrl( $params );
898 # For interwikis, use POST to avoid redirects.
899 return ImportStreamSource
::newFromURL( $url, "POST" );