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, $mPageOutCallback;
38 private $mImportUploads, $mImageBasePath;
41 * Creates an ImportXMLReader drawing from the source provided
43 function __construct( $source ) {
44 $this->reader
= new XMLReader();
46 stream_wrapper_register( 'uploadsource', 'UploadSourceAdapter' );
47 $id = UploadSourceAdapter
::registerSource( $source );
48 $this->reader
->open( "uploadsource://$id" );
51 $this->setRevisionCallback( array( $this, "importRevision" ) );
52 $this->setUploadCallback( array( $this, 'importUpload' ) );
53 $this->setLogItemCallback( array( $this, 'importLogItem' ) );
54 $this->setPageOutCallback( array( $this, 'finishImportPage' ) );
57 private function throwXmlError( $err ) {
58 $this->debug( "FAILURE: $err" );
59 wfDebug( "WikiImporter XML error: $err\n" );
62 private function debug( $data ) {
64 wfDebug( "IMPORT: $data\n" );
68 private function warn( $data ) {
69 wfDebug( "IMPORT: $data\n" );
72 private function notice( $data ) {
73 global $wgCommandLineMode;
74 if( $wgCommandLineMode ) {
78 $wgOut->addHTML( "<li>" . htmlspecialchars( $data ) . "</li>\n" );
85 function setDebug( $debug ) {
86 $this->mDebug
= $debug;
90 * Sets the action to perform as each new page in the stream is reached.
91 * @param $callback callback
94 public function setPageCallback( $callback ) {
95 $previous = $this->mPageCallback
;
96 $this->mPageCallback
= $callback;
101 * Sets the action to perform as each page in the stream is completed.
102 * Callback accepts the page title (as a Title object), a second object
103 * with the original title form (in case it's been overridden into a
104 * local namespace), and a count of revisions.
106 * @param $callback callback
109 public function setPageOutCallback( $callback ) {
110 $previous = $this->mPageOutCallback
;
111 $this->mPageOutCallback
= $callback;
116 * Sets the action to perform as each page revision is reached.
117 * @param $callback callback
120 public function setRevisionCallback( $callback ) {
121 $previous = $this->mRevisionCallback
;
122 $this->mRevisionCallback
= $callback;
127 * Sets the action to perform as each file upload version is reached.
128 * @param $callback callback
131 public function setUploadCallback( $callback ) {
132 $previous = $this->mUploadCallback
;
133 $this->mUploadCallback
= $callback;
138 * Sets the action to perform as each log item reached.
139 * @param $callback callback
142 public function setLogItemCallback( $callback ) {
143 $previous = $this->mLogItemCallback
;
144 $this->mLogItemCallback
= $callback;
149 * Sets the action to perform when site info is encountered
150 * @param $callback callback
153 public function setSiteInfoCallback( $callback ) {
154 $previous = $this->mSiteInfoCallback
;
155 $this->mSiteInfoCallback
= $callback;
160 * Set a target namespace to override the defaults
162 public function setTargetNamespace( $namespace ) {
163 if( is_null( $namespace ) ) {
164 // Don't override namespaces
165 $this->mTargetNamespace
= null;
166 } elseif( $namespace >= 0 ) {
167 // FIXME: Check for validity
168 $this->mTargetNamespace
= intval( $namespace );
177 public function setImageBasePath( $dir ) {
178 $this->mImageBasePath
= $dir;
182 * Default per-revision callback, performs the import.
183 * @param $revision WikiRevision
185 public function importRevision( $revision ) {
186 $dbw = wfGetDB( DB_MASTER
);
187 return $dbw->deadlockLoop( array( $revision, 'importOldRevision' ) );
191 * Default per-revision callback, performs the import.
192 * @param $rev WikiRevision
194 public function importLogItem( $rev ) {
195 $dbw = wfGetDB( DB_MASTER
);
196 return $dbw->deadlockLoop( array( $rev, 'importLogItem' ) );
202 public function importUpload( $revision ) {
203 $dbw = wfGetDB( DB_MASTER
);
204 return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
209 * Mostly for hook use
211 public function finishImportPage( $title, $origTitle, $revCount, $sRevCount, $pageInfo ) {
212 $args = func_get_args();
213 return wfRunHooks( 'AfterImportPage', $args );
217 * Alternate per-revision callback, for debugging.
218 * @param $revision WikiRevision
220 public function debugRevisionHandler( &$revision ) {
221 $this->debug( "Got revision:" );
222 if( is_object( $revision->title
) ) {
223 $this->debug( "-- Title: " . $revision->title
->getPrefixedText() );
225 $this->debug( "-- Title: <invalid>" );
227 $this->debug( "-- User: " . $revision->user_text
);
228 $this->debug( "-- Timestamp: " . $revision->timestamp
);
229 $this->debug( "-- Comment: " . $revision->comment
);
230 $this->debug( "-- Text: " . $revision->text
);
234 * Notify the callback function when a new <page> is reached.
235 * @param $title Title
237 function pageCallback( $title ) {
238 if( isset( $this->mPageCallback
) ) {
239 call_user_func( $this->mPageCallback
, $title );
244 * Notify the callback function when a </page> is closed.
245 * @param $title Title
246 * @param $origTitle Title
247 * @param $revCount Integer
248 * @param $sucCount Int: number of revisions for which callback returned true
249 * @param $pageInfo Array: associative array of page information
251 private function pageOutCallback( $title, $origTitle, $revCount, $sucCount, $pageInfo ) {
252 if( isset( $this->mPageOutCallback
) ) {
253 $args = func_get_args();
254 call_user_func_array( $this->mPageOutCallback
, $args );
259 * Notify the callback function of a revision
260 * @param $revision A WikiRevision object
262 private function revisionCallback( $revision ) {
263 if ( isset( $this->mRevisionCallback
) ) {
264 return call_user_func_array( $this->mRevisionCallback
,
265 array( $revision, $this ) );
272 * Notify the callback function of a new log item
273 * @param $revision A WikiRevision object
275 private function logItemCallback( $revision ) {
276 if ( isset( $this->mLogItemCallback
) ) {
277 return call_user_func_array( $this->mLogItemCallback
,
278 array( $revision, $this ) );
285 * Shouldn't something like this be built-in to XMLReader?
286 * Fetches text contents of the current element, assuming
287 * no sub-elements or such scary things.
291 private function nodeContents() {
292 if( $this->reader
->isEmptyElement
) {
296 while( $this->reader
->read() ) {
297 switch( $this->reader
->nodeType
) {
298 case XmlReader
::TEXT
:
299 case XmlReader
::SIGNIFICANT_WHITESPACE
:
300 $buffer .= $this->reader
->value
;
302 case XmlReader
::END_ELEMENT
:
307 $this->reader
->close();
313 /** Left in for debugging */
314 private function dumpElement() {
315 static $lookup = null;
317 $xmlReaderConstants = array(
332 "SIGNIFICANT_WHITESPACE",
339 foreach( $xmlReaderConstants as $name ) {
340 $lookup[constant("XmlReader::$name")] = $name;
345 $lookup[$this->reader
->nodeType
],
352 * Primary entry point
354 public function doImport() {
355 $this->reader
->read();
357 if ( $this->reader
->name
!= 'mediawiki' ) {
358 throw new MWException( "Expected <mediawiki> tag, got ".
359 $this->reader
->name
);
361 $this->debug( "<mediawiki> tag is correct." );
363 $this->debug( "Starting primary dump processing loop." );
365 $keepReading = $this->reader
->read();
367 while ( $keepReading ) {
368 $tag = $this->reader
->name
;
369 $type = $this->reader
->nodeType
;
371 if ( !wfRunHooks( 'ImportHandleToplevelXMLTag', $this ) ) {
373 } elseif ( $tag == 'mediawiki' && $type == XmlReader
::END_ELEMENT
) {
375 } elseif ( $tag == 'siteinfo' ) {
376 $this->handleSiteInfo();
377 } elseif ( $tag == 'page' ) {
379 } elseif ( $tag == 'logitem' ) {
380 $this->handleLogItem();
381 } elseif ( $tag != '#text' ) {
382 $this->warn( "Unhandled top-level XML tag $tag" );
388 $keepReading = $this->reader
->next();
390 $this->debug( "Skip" );
392 $keepReading = $this->reader
->read();
399 private function handleSiteInfo() {
400 // Site info is useful, but not actually used for dump imports.
401 // Includes a quick short-circuit to save performance.
402 if ( ! $this->mSiteInfoCallback
) {
403 $this->reader
->next();
406 throw new MWException( "SiteInfo tag is not yet handled, do not set mSiteInfoCallback" );
409 private function handleLogItem() {
410 $this->debug( "Enter log item handler." );
413 // Fields that can just be stuffed in the pageInfo object
414 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
415 'logtitle', 'params' );
417 while ( $this->reader
->read() ) {
418 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
419 $this->reader
->name
== 'logitem') {
423 $tag = $this->reader
->name
;
425 if ( !wfRunHooks( 'ImportHandleLogItemXMLTag',
426 $this, $logInfo ) ) {
428 } elseif ( in_array( $tag, $normalFields ) ) {
429 $logInfo[$tag] = $this->nodeContents();
430 } elseif ( $tag == 'contributor' ) {
431 $logInfo['contributor'] = $this->handleContributor();
432 } elseif ( $tag != '#text' ) {
433 $this->warn( "Unhandled log-item XML tag $tag" );
437 $this->processLogItem( $logInfo );
440 private function processLogItem( $logInfo ) {
441 $revision = new WikiRevision
;
443 $revision->setID( $logInfo['id'] );
444 $revision->setType( $logInfo['type'] );
445 $revision->setAction( $logInfo['action'] );
446 $revision->setTimestamp( $logInfo['timestamp'] );
447 $revision->setParams( $logInfo['params'] );
448 $revision->setTitle( Title
::newFromText( $logInfo['logtitle'] ) );
450 if ( isset( $logInfo['comment'] ) ) {
451 $revision->setComment( $logInfo['comment'] );
454 if ( isset( $logInfo['contributor']['ip'] ) ) {
455 $revision->setUserIP( $logInfo['contributor']['ip'] );
457 if ( isset( $logInfo['contributor']['username'] ) ) {
458 $revision->setUserName( $logInfo['contributor']['username'] );
461 return $this->logItemCallback( $revision );
464 private function handlePage() {
466 $this->debug( "Enter page handler." );
467 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
469 // Fields that can just be stuffed in the pageInfo object
470 $normalFields = array( 'title', 'id', 'redirect', 'restrictions' );
475 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
476 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
477 $this->reader
->name
== 'page') {
481 $tag = $this->reader
->name
;
484 // The title is invalid, bail out of this page
486 } elseif ( !wfRunHooks( 'ImportHandlePageXMLTag', array( $this,
489 } elseif ( in_array( $tag, $normalFields ) ) {
490 $pageInfo[$tag] = $this->nodeContents();
491 if ( $tag == 'title' ) {
492 $title = $this->processTitle( $pageInfo['title'] );
499 $this->pageCallback( $title );
500 list( $pageInfo['_title'], $origTitle ) = $title;
502 } elseif ( $tag == 'revision' ) {
503 $this->handleRevision( $pageInfo );
504 } elseif ( $tag == 'upload' ) {
505 $this->handleUpload( $pageInfo );
506 } elseif ( $tag != '#text' ) {
507 $this->warn( "Unhandled page XML tag $tag" );
512 $this->pageOutCallback( $pageInfo['_title'], $origTitle,
513 $pageInfo['revisionCount'],
514 $pageInfo['successfulRevisionCount'],
518 private function handleRevision( &$pageInfo ) {
519 $this->debug( "Enter revision handler" );
520 $revisionInfo = array();
522 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'text' );
526 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
527 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
528 $this->reader
->name
== 'revision') {
532 $tag = $this->reader
->name
;
534 if ( !wfRunHooks( 'ImportHandleRevisionXMLTag', $this,
535 $pageInfo, $revisionInfo ) ) {
537 } elseif ( in_array( $tag, $normalFields ) ) {
538 $revisionInfo[$tag] = $this->nodeContents();
539 } elseif ( $tag == 'contributor' ) {
540 $revisionInfo['contributor'] = $this->handleContributor();
541 } elseif ( $tag != '#text' ) {
542 $this->warn( "Unhandled revision XML tag $tag" );
547 $pageInfo['revisionCount']++
;
548 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
549 $pageInfo['successfulRevisionCount']++
;
553 private function processRevision( $pageInfo, $revisionInfo ) {
554 $revision = new WikiRevision
;
556 if( isset( $revisionInfo['id'] ) ) {
557 $revision->setID( $revisionInfo['id'] );
559 if ( isset( $revisionInfo['text'] ) ) {
560 $revision->setText( $revisionInfo['text'] );
562 $revision->setTitle( $pageInfo['_title'] );
564 if ( isset( $revisionInfo['timestamp'] ) ) {
565 $revision->setTimestamp( $revisionInfo['timestamp'] );
567 $revision->setTimestamp( wfTimestampNow() );
570 if ( isset( $revisionInfo['comment'] ) ) {
571 $revision->setComment( $revisionInfo['comment'] );
574 if ( isset( $revisionInfo['minor'] ) ) {
575 $revision->setMinor( true );
577 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
578 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
580 if ( isset( $revisionInfo['contributor']['username'] ) ) {
581 $revision->setUserName( $revisionInfo['contributor']['username'] );
584 return $this->revisionCallback( $revision );
587 private function handleUpload( &$pageInfo ) {
588 $this->debug( "Enter upload handler" );
589 $uploadInfo = array();
591 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
592 'src', 'size', 'sha1base36', 'archivename', 'rel' );
596 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
597 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
598 $this->reader
->name
== 'upload') {
602 $tag = $this->reader
->name
;
604 if ( !wfRunHooks( 'ImportHandleUploadXMLTag', $this,
607 } elseif ( in_array( $tag, $normalFields ) ) {
608 $uploadInfo[$tag] = $this->nodeContents();
609 } elseif ( $tag == 'contributor' ) {
610 $uploadInfo['contributor'] = $this->handleContributor();
611 } elseif ( $tag == 'contents' ) {
612 $contents = $this->nodeContents();
613 $encoding = $this->reader
->getAttribute( 'encoding' );
614 if ( $encoding === 'base64' ) {
615 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
617 } elseif ( $tag != '#text' ) {
618 $this->warn( "Unhandled upload XML tag $tag" );
623 if ( $this->mImageBasePath
&& isset( $uploadInfo['rel'] ) ) {
624 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
625 if ( file_exists( $path ) ) {
626 $uploadInfo['fileSrc'] = $path;
630 if ( $this->mImportUploads
) {
631 return $this->processUpload( $pageInfo, $uploadInfo );
635 private function dumpTemp( $contents ) {
636 $filename = tempnam( wfTempDir(), 'importupload' );
637 file_put_contents( $filename, $contents );
642 private function processUpload( $pageInfo, $uploadInfo ) {
643 $revision = new WikiRevision
;
644 $text = isset( $uploadInfo['text'] ) ?
$uploadInfo['text'] : '';
646 $revision->setTitle( $pageInfo['_title'] );
647 $revision->setID( $pageInfo['id'] );
648 $revision->setTimestamp( $uploadInfo['timestamp'] );
649 $revision->setText( $text );
650 $revision->setFilename( $uploadInfo['filename'] );
651 if ( isset( $uploadInfo['archivename'] ) ) {
652 $revision->setArchiveName( $uploadInfo['archivename'] );
654 $revision->setSrc( $uploadInfo['src'] );
655 if ( isset( $uploadInfo['fileSrc'] ) ) {
656 $revision->setFileSrc( $uploadInfo['fileSrc'] );
658 $revision->setSize( intval( $uploadInfo['size'] ) );
659 $revision->setComment( $uploadInfo['comment'] );
661 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
662 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
664 if ( isset( $uploadInfo['contributor']['username'] ) ) {
665 $revision->setUserName( $uploadInfo['contributor']['username'] );
668 return call_user_func( $this->mUploadCallback
, $revision );
671 private function handleContributor() {
672 $fields = array( 'id', 'ip', 'username' );
675 while ( $this->reader
->read() ) {
676 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
677 $this->reader
->name
== 'contributor') {
681 $tag = $this->reader
->name
;
683 if ( in_array( $tag, $fields ) ) {
684 $info[$tag] = $this->nodeContents();
691 private function processTitle( $text ) {
693 $origTitle = Title
::newFromText( $workTitle );
695 if( !is_null( $this->mTargetNamespace
) && !is_null( $origTitle ) ) {
696 $title = Title
::makeTitle( $this->mTargetNamespace
,
697 $origTitle->getDBkey() );
699 $title = Title
::newFromText( $workTitle );
702 if( is_null( $title ) ) {
703 // Invalid page title? Ignore the page
704 $this->notice( "Skipping invalid page title '$workTitle'" );
706 } elseif( $title->getInterwiki() != '' ) {
707 $this->notice( "Skipping interwiki page title '$workTitle'" );
711 return array( $title, $origTitle );
715 /** This is a horrible hack used to keep source compatibility */
716 class UploadSourceAdapter
{
717 static $sourceRegistrations = array();
723 static function registerSource( $source ) {
724 $id = wfGenerateToken();
726 self
::$sourceRegistrations[$id] = $source;
731 function stream_open( $path, $mode, $options, &$opened_path ) {
732 $url = parse_url($path);
735 if ( !isset( self
::$sourceRegistrations[$id] ) ) {
739 $this->mSource
= self
::$sourceRegistrations[$id];
744 function stream_read( $count ) {
748 while ( !$leave && !$this->mSource
->atEnd() &&
749 strlen($this->mBuffer
) < $count ) {
750 $read = $this->mSource
->readChunk();
752 if ( !strlen($read) ) {
756 $this->mBuffer
.= $read;
759 if ( strlen($this->mBuffer
) ) {
760 $return = substr( $this->mBuffer
, 0, $count );
761 $this->mBuffer
= substr( $this->mBuffer
, $count );
764 $this->mPosition +
= strlen($return);
769 function stream_write( $data ) {
773 function stream_tell() {
774 return $this->mPosition
;
777 function stream_eof() {
778 return $this->mSource
->atEnd();
781 function url_stat() {
784 $result['dev'] = $result[0] = 0;
785 $result['ino'] = $result[1] = 0;
786 $result['mode'] = $result[2] = 0;
787 $result['nlink'] = $result[3] = 0;
788 $result['uid'] = $result[4] = 0;
789 $result['gid'] = $result[5] = 0;
790 $result['rdev'] = $result[6] = 0;
791 $result['size'] = $result[7] = 0;
792 $result['atime'] = $result[8] = 0;
793 $result['mtime'] = $result[9] = 0;
794 $result['ctime'] = $result[10] = 0;
795 $result['blksize'] = $result[11] = 0;
796 $result['blocks'] = $result[12] = 0;
802 class XMLReader2
extends XMLReader
{
803 function nodeContents() {
804 if( $this->isEmptyElement
) {
808 while( $this->read() ) {
809 switch( $this->nodeType
) {
810 case XmlReader
::TEXT
:
811 case XmlReader
::SIGNIFICANT_WHITESPACE
:
812 $buffer .= $this->value
;
814 case XmlReader
::END_ELEMENT
:
818 return $this->close();
823 * @todo document (e.g. one-sentence class description).
824 * @ingroup SpecialPage
827 var $importer = null;
830 var $timestamp = "20010115000000";
840 var $archiveName = '';
842 function setTitle( $title ) {
843 if( is_object( $title ) ) {
844 $this->title
= $title;
845 } elseif( is_null( $title ) ) {
846 throw new MWException( "WikiRevision given a null title in import. You may need to adjust \$wgLegalTitleChars." );
848 throw new MWException( "WikiRevision given non-object title in import." );
852 function setID( $id ) {
856 function setTimestamp( $ts ) {
857 # 2003-08-05T18:30:02Z
858 $this->timestamp
= wfTimestamp( TS_MW
, $ts );
861 function setUsername( $user ) {
862 $this->user_text
= $user;
865 function setUserIP( $ip ) {
866 $this->user_text
= $ip;
869 function setText( $text ) {
873 function setComment( $text ) {
874 $this->comment
= $text;
877 function setMinor( $minor ) {
878 $this->minor
= (bool)$minor;
881 function setSrc( $src ) {
884 function setFileSrc( $src ) {
885 $this->fileSrc
= $src;
888 function setFilename( $filename ) {
889 $this->filename
= $filename;
891 function setArchiveName( $archiveName ) {
892 $this->archiveName
= $archiveName;
895 function setSize( $size ) {
896 $this->size
= intval( $size );
899 function setType( $type ) {
903 function setAction( $action ) {
904 $this->action
= $action;
907 function setParams( $params ) {
908 $this->params
= $params;
911 function getTitle() {
919 function getTimestamp() {
920 return $this->timestamp
;
924 return $this->user_text
;
931 function getComment() {
932 return $this->comment
;
935 function getMinor() {
942 function getFileSrc() {
943 return $this->fileSrc
;
946 function getFilename() {
947 return $this->filename
;
949 function getArchiveName() {
950 return $this->archiveName
;
961 function getAction() {
962 return $this->action
;
965 function getParams() {
966 return $this->params
;
969 function importOldRevision() {
970 $dbw = wfGetDB( DB_MASTER
);
972 # Sneak a single revision into place
973 $user = User
::newFromName( $this->getUser() );
975 $userId = intval( $user->getId() );
976 $userText = $user->getName();
979 $userText = $this->getUser();
982 // avoid memory leak...?
983 $linkCache = LinkCache
::singleton();
986 $article = new Article( $this->title
);
987 $pageId = $article->getId();
989 # must create the page...
990 $pageId = $article->insertOn( $dbw );
995 $prior = $dbw->selectField( 'revision', '1',
996 array( 'rev_page' => $pageId,
997 'rev_timestamp' => $dbw->timestamp( $this->timestamp
),
998 'rev_user_text' => $userText,
999 'rev_comment' => $this->getComment() ),
1003 // FIXME: this could fail slightly for multiple matches :P
1004 wfDebug( __METHOD__
. ": skipping existing revision for [[" .
1005 $this->title
->getPrefixedText() . "]], timestamp " . $this->timestamp
. "\n" );
1010 # FIXME: Use original rev_id optionally (better for backups)
1012 $revision = new Revision( array(
1014 'text' => $this->getText(),
1015 'comment' => $this->getComment(),
1017 'user_text' => $userText,
1018 'timestamp' => $this->timestamp
,
1019 'minor_edit' => $this->minor
,
1021 $revId = $revision->insertOn( $dbw );
1022 $changed = $article->updateIfNewerOn( $dbw, $revision );
1024 # To be on the safe side...
1025 $tempTitle = $GLOBALS['wgTitle'];
1026 $GLOBALS['wgTitle'] = $this->title
;
1029 wfDebug( __METHOD__
. ": running onArticleCreate\n" );
1030 Article
::onArticleCreate( $this->title
);
1032 wfDebug( __METHOD__
. ": running create updates\n" );
1033 $article->createUpdates( $revision );
1035 } elseif( $changed ) {
1036 wfDebug( __METHOD__
. ": running onArticleEdit\n" );
1037 Article
::onArticleEdit( $this->title
);
1039 wfDebug( __METHOD__
. ": running edit updates\n" );
1040 $article->editUpdates(
1042 $this->getComment(),
1047 $GLOBALS['wgTitle'] = $tempTitle;
1052 function importLogItem() {
1053 $dbw = wfGetDB( DB_MASTER
);
1054 # FIXME: this will not record autoblocks
1055 if( !$this->getTitle() ) {
1056 wfDebug( __METHOD__
. ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1057 $this->timestamp
. "\n" );
1060 # Check if it exists already
1061 // FIXME: use original log ID (better for backups)
1062 $prior = $dbw->selectField( 'logging', '1',
1063 array( 'log_type' => $this->getType(),
1064 'log_action' => $this->getAction(),
1065 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1066 'log_namespace' => $this->getTitle()->getNamespace(),
1067 'log_title' => $this->getTitle()->getDBkey(),
1068 'log_comment' => $this->getComment(),
1069 #'log_user_text' => $this->user_text,
1070 'log_params' => $this->params
),
1073 // FIXME: this could fail slightly for multiple matches :P
1075 wfDebug( __METHOD__
. ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp " .
1076 $this->timestamp
. "\n" );
1079 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1081 'log_id' => $log_id,
1082 'log_type' => $this->type
,
1083 'log_action' => $this->action
,
1084 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1085 'log_user' => User
::idFromName( $this->user_text
),
1086 #'log_user_text' => $this->user_text,
1087 'log_namespace' => $this->getTitle()->getNamespace(),
1088 'log_title' => $this->getTitle()->getDBkey(),
1089 'log_comment' => $this->getComment(),
1090 'log_params' => $this->params
1092 $dbw->insert( 'logging', $data, __METHOD__
);
1095 function importUpload() {
1097 $archiveName = $this->getArchiveName();
1098 if ( $archiveName ) {
1099 wfDebug( __METHOD__
. "Importing archived file as $archiveName\n" );
1100 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1101 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1103 $file = wfLocalFile( $this->getTitle() );
1104 wfDebug( __METHOD__
. 'Importing new file as ' . $file->getName() . "\n" );
1105 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1106 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1107 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1108 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1109 wfDebug( __METHOD__
. "File already exists; importing as $archiveName\n" );
1113 wfDebug( __METHOD__
. ': Bad file for ' . $this->getTitle() . "\n" );
1117 # Get the file source or download if necessary
1118 $source = $this->getFileSrc();
1120 $source = $this->downloadSource();
1123 wfDebug( __METHOD__
. ": Could not fetch remote file.\n" );
1127 $user = User
::newFromName( $this->user_text
);
1129 # Do the actual upload
1130 if ( $archiveName ) {
1131 $status = $file->uploadOld( $source, $archiveName,
1132 $this->getTimestamp(), $this->getComment(), $user, File
::DELETE_SOURCE
);
1134 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1135 File
::DELETE_SOURCE
, false, $this->getTimestamp(), $user );
1138 if ( $status->isGood() ) {
1139 wfDebug( __METHOD__
. ": Succesful\n" );
1142 wfDebug( __METHOD__
. ': failed: ' . $status->getXml() . "\n" );
1147 function downloadSource() {
1148 global $wgEnableUploads;
1149 if( !$wgEnableUploads ) {
1153 $tempo = tempnam( wfTempDir(), 'download' );
1154 $f = fopen( $tempo, 'wb' );
1156 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1161 $src = $this->getSrc();
1162 $data = Http
::get( $src );
1164 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1170 fwrite( $f, $data );
1179 * @todo document (e.g. one-sentence class description).
1180 * @ingroup SpecialPage
1182 class ImportStringSource
{
1183 function __construct( $string ) {
1184 $this->mString
= $string;
1185 $this->mRead
= false;
1189 return $this->mRead
;
1192 function readChunk() {
1193 if( $this->atEnd() ) {
1196 $this->mRead
= true;
1197 return $this->mString
;
1203 * @todo document (e.g. one-sentence class description).
1204 * @ingroup SpecialPage
1206 class ImportStreamSource
{
1207 function __construct( $handle ) {
1208 $this->mHandle
= $handle;
1212 return feof( $this->mHandle
);
1215 function readChunk() {
1216 return fread( $this->mHandle
, 32768 );
1219 static function newFromFile( $filename ) {
1220 $file = @fopen
( $filename, 'rt' );
1222 return Status
::newFatal( "importcantopen" );
1224 return Status
::newGood( new ImportStreamSource( $file ) );
1227 static function newFromUpload( $fieldname = "xmlimport" ) {
1228 $upload =& $_FILES[$fieldname];
1230 if( !isset( $upload ) ||
!$upload['name'] ) {
1231 return Status
::newFatal( 'importnofile' );
1233 if( !empty( $upload['error'] ) ) {
1234 switch($upload['error']){
1235 case 1: # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1236 return Status
::newFatal( 'importuploaderrorsize' );
1237 case 2: # The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
1238 return Status
::newFatal( 'importuploaderrorsize' );
1239 case 3: # The uploaded file was only partially uploaded
1240 return Status
::newFatal( 'importuploaderrorpartial' );
1241 case 6: #Missing a temporary folder.
1242 return Status
::newFatal( 'importuploaderrortemp' );
1243 # case else: # Currently impossible
1247 $fname = $upload['tmp_name'];
1248 if( is_uploaded_file( $fname ) ) {
1249 return ImportStreamSource
::newFromFile( $fname );
1251 return Status
::newFatal( 'importnofile' );
1255 static function newFromURL( $url, $method = 'GET' ) {
1256 wfDebug( __METHOD__
. ": opening $url\n" );
1257 # Use the standard HTTP fetch function; it times out
1258 # quicker and sorts out user-agent problems which might
1259 # otherwise prevent importing from large sites, such
1260 # as the Wikimedia cluster, etc.
1261 $data = Http
::request( $method, $url );
1262 if( $data !== false ) {
1264 fwrite( $file, $data );
1267 return Status
::newGood( new ImportStreamSource( $file ) );
1269 return Status
::newFatal( 'importcantopen' );
1273 public static function newFromInterwiki( $interwiki, $page, $history = false, $templates = false, $pageLinkDepth = 0 ) {
1275 return Status
::newFatal( 'import-noarticle' );
1277 $link = Title
::newFromText( "$interwiki:Special:Export/$page" );
1278 if( is_null( $link ) ||
$link->getInterwiki() == '' ) {
1279 return Status
::newFatal( 'importbadinterwiki' );
1282 if ( $history ) $params['history'] = 1;
1283 if ( $templates ) $params['templates'] = 1;
1284 if ( $pageLinkDepth ) $params['pagelink-depth'] = $pageLinkDepth;
1285 $url = $link->getFullUrl( $params );
1286 # For interwikis, use POST to avoid redirects.
1287 return ImportStreamSource
::newFromURL( $url, "POST" );