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' ) );
208 * Mostly for hook use
210 public function finishImportPage( $title, $origTitle, $revCount, $sRevCount, $pageInfo ) {
211 $args = func_get_args();
212 return wfRunHooks( 'AfterImportPage', $args );
216 * Alternate per-revision callback, for debugging.
217 * @param $revision WikiRevision
219 public function debugRevisionHandler( &$revision ) {
220 $this->debug( "Got revision:" );
221 if( is_object( $revision->title
) ) {
222 $this->debug( "-- Title: " . $revision->title
->getPrefixedText() );
224 $this->debug( "-- Title: <invalid>" );
226 $this->debug( "-- User: " . $revision->user_text
);
227 $this->debug( "-- Timestamp: " . $revision->timestamp
);
228 $this->debug( "-- Comment: " . $revision->comment
);
229 $this->debug( "-- Text: " . $revision->text
);
233 * Notify the callback function when a new <page> is reached.
234 * @param $title Title
236 function pageCallback( $title ) {
237 if( isset( $this->mPageCallback
) ) {
238 call_user_func( $this->mPageCallback
, $title );
243 * Notify the callback function when a </page> is closed.
244 * @param $title Title
245 * @param $origTitle Title
246 * @param $revCount Integer
247 * @param $sucCount Int: number of revisions for which callback returned true
248 * @param $pageInfo Array: associative array of page information
250 private function pageOutCallback( $title, $origTitle, $revCount, $sucCount, $pageInfo ) {
251 if( isset( $this->mPageOutCallback
) ) {
252 $args = func_get_args();
253 call_user_func_array( $this->mPageOutCallback
, $args );
258 * Notify the callback function of a revision
259 * @param $revision A WikiRevision object
261 private function revisionCallback( $revision ) {
262 if ( isset( $this->mRevisionCallback
) ) {
263 return call_user_func_array( $this->mRevisionCallback
,
264 array( $revision, $this ) );
271 * Notify the callback function of a new log item
272 * @param $revision A WikiRevision object
274 private function logItemCallback( $revision ) {
275 if ( isset( $this->mLogItemCallback
) ) {
276 return call_user_func_array( $this->mLogItemCallback
,
277 array( $revision, $this ) );
284 * Shouldn't something like this be built-in to XMLReader?
285 * Fetches text contents of the current element, assuming
286 * no sub-elements or such scary things.
290 private function nodeContents() {
291 if( $this->reader
->isEmptyElement
) {
295 while( $this->reader
->read() ) {
296 switch( $this->reader
->nodeType
) {
297 case XmlReader
::TEXT
:
298 case XmlReader
::SIGNIFICANT_WHITESPACE
:
299 $buffer .= $this->reader
->value
;
301 case XmlReader
::END_ELEMENT
:
306 $this->reader
->close();
312 /** Left in for debugging */
313 private function dumpElement() {
314 static $lookup = null;
316 $xmlReaderConstants = array(
331 "SIGNIFICANT_WHITESPACE",
338 foreach( $xmlReaderConstants as $name ) {
339 $lookup[constant("XmlReader::$name")] = $name;
344 $lookup[$this->reader
->nodeType
],
351 * Primary entry point
353 public function doImport() {
354 $this->reader
->read();
356 if ( $this->reader
->name
!= 'mediawiki' ) {
357 throw new MWException( "Expected <mediawiki> tag, got ".
358 $this->reader
->name
);
360 $this->debug( "<mediawiki> tag is correct." );
362 $this->debug( "Starting primary dump processing loop." );
364 $keepReading = $this->reader
->read();
366 while ( $keepReading ) {
367 $tag = $this->reader
->name
;
368 $type = $this->reader
->nodeType
;
370 if ( !wfRunHooks( 'ImportHandleToplevelXMLTag', $this ) ) {
372 } elseif ( $tag == 'mediawiki' && $type == XmlReader
::END_ELEMENT
) {
374 } elseif ( $tag == 'siteinfo' ) {
375 $this->handleSiteInfo();
376 } elseif ( $tag == 'page' ) {
378 } elseif ( $tag == 'logitem' ) {
379 $this->handleLogItem();
380 } elseif ( $tag != '#text' ) {
381 $this->warn( "Unhandled top-level XML tag $tag" );
387 $keepReading = $this->reader
->next();
389 $this->debug( "Skip" );
391 $keepReading = $this->reader
->read();
398 private function handleSiteInfo() {
399 // Site info is useful, but not actually used for dump imports.
400 // Includes a quick short-circuit to save performance.
401 if ( ! $this->mSiteInfoCallback
) {
402 $this->reader
->next();
405 throw new MWException( "SiteInfo tag is not yet handled, do not set mSiteInfoCallback" );
408 private function handleLogItem() {
409 $this->debug( "Enter log item handler." );
412 // Fields that can just be stuffed in the pageInfo object
413 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
414 'logtitle', 'params' );
416 while ( $this->reader
->read() ) {
417 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
418 $this->reader
->name
== 'logitem') {
422 $tag = $this->reader
->name
;
424 if ( !wfRunHooks( 'ImportHandleLogItemXMLTag',
425 $this, $logInfo ) ) {
427 } elseif ( in_array( $tag, $normalFields ) ) {
428 $logInfo[$tag] = $this->nodeContents();
429 } elseif ( $tag == 'contributor' ) {
430 $logInfo['contributor'] = $this->handleContributor();
431 } elseif ( $tag != '#text' ) {
432 $this->warn( "Unhandled log-item XML tag $tag" );
436 $this->processLogItem( $logInfo );
439 private function processLogItem( $logInfo ) {
440 $revision = new WikiRevision
;
442 $revision->setID( $logInfo['id'] );
443 $revision->setType( $logInfo['type'] );
444 $revision->setAction( $logInfo['action'] );
445 $revision->setTimestamp( $logInfo['timestamp'] );
446 $revision->setParams( $logInfo['params'] );
447 $revision->setTitle( Title
::newFromText( $logInfo['logtitle'] ) );
449 if ( isset( $logInfo['comment'] ) ) {
450 $revision->setComment( $logInfo['comment'] );
453 if ( isset( $logInfo['contributor']['ip'] ) ) {
454 $revision->setUserIP( $logInfo['contributor']['ip'] );
456 if ( isset( $logInfo['contributor']['username'] ) ) {
457 $revision->setUserName( $logInfo['contributor']['username'] );
460 return $this->logItemCallback( $revision );
463 private function handlePage() {
465 $this->debug( "Enter page handler." );
466 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
468 // Fields that can just be stuffed in the pageInfo object
469 $normalFields = array( 'title', 'id', 'redirect', 'restrictions' );
474 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
475 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
476 $this->reader
->name
== 'page') {
480 $tag = $this->reader
->name
;
483 // The title is invalid, bail out of this page
485 } elseif ( !wfRunHooks( 'ImportHandlePageXMLTag', array( $this,
488 } elseif ( in_array( $tag, $normalFields ) ) {
489 $pageInfo[$tag] = $this->nodeContents();
490 if ( $tag == 'title' ) {
491 $title = $this->processTitle( $pageInfo['title'] );
498 $this->pageCallback( $title );
499 list( $pageInfo['_title'], $origTitle ) = $title;
501 } elseif ( $tag == 'revision' ) {
502 $this->handleRevision( $pageInfo );
503 } elseif ( $tag == 'upload' ) {
504 $this->handleUpload( $pageInfo );
505 } elseif ( $tag != '#text' ) {
506 $this->warn( "Unhandled page XML tag $tag" );
511 $this->pageOutCallback( $pageInfo['_title'], $origTitle,
512 $pageInfo['revisionCount'],
513 $pageInfo['successfulRevisionCount'],
517 private function handleRevision( &$pageInfo ) {
518 $this->debug( "Enter revision handler" );
519 $revisionInfo = array();
521 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'text' );
525 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
526 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
527 $this->reader
->name
== 'revision') {
531 $tag = $this->reader
->name
;
533 if ( !wfRunHooks( 'ImportHandleRevisionXMLTag', $this,
534 $pageInfo, $revisionInfo ) ) {
536 } elseif ( in_array( $tag, $normalFields ) ) {
537 $revisionInfo[$tag] = $this->nodeContents();
538 } elseif ( $tag == 'contributor' ) {
539 $revisionInfo['contributor'] = $this->handleContributor();
540 } elseif ( $tag != '#text' ) {
541 $this->warn( "Unhandled revision XML tag $tag" );
546 $pageInfo['revisionCount']++
;
547 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
548 $pageInfo['successfulRevisionCount']++
;
552 private function processRevision( $pageInfo, $revisionInfo ) {
553 $revision = new WikiRevision
;
555 if( isset( $revisionInfo['id'] ) ) {
556 $revision->setID( $revisionInfo['id'] );
558 if ( isset( $revisionInfo['text'] ) ) {
559 $revision->setText( $revisionInfo['text'] );
561 $revision->setTitle( $pageInfo['_title'] );
563 if ( isset( $revisionInfo['timestamp'] ) ) {
564 $revision->setTimestamp( $revisionInfo['timestamp'] );
566 $revision->setTimestamp( wfTimestampNow() );
569 if ( isset( $revisionInfo['comment'] ) ) {
570 $revision->setComment( $revisionInfo['comment'] );
573 if ( isset( $revisionInfo['minor'] ) ) {
574 $revision->setMinor( true );
576 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
577 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
579 if ( isset( $revisionInfo['contributor']['username'] ) ) {
580 $revision->setUserName( $revisionInfo['contributor']['username'] );
583 return $this->revisionCallback( $revision );
586 private function handleUpload( &$pageInfo ) {
587 $this->debug( "Enter upload handler" );
588 $uploadInfo = array();
590 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
591 'src', 'size', 'sha1base36', 'archivename', 'rel' );
595 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
596 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
597 $this->reader
->name
== 'upload') {
601 $tag = $this->reader
->name
;
603 if ( !wfRunHooks( 'ImportHandleUploadXMLTag', $this,
606 } elseif ( in_array( $tag, $normalFields ) ) {
607 $uploadInfo[$tag] = $this->nodeContents();
608 } elseif ( $tag == 'contributor' ) {
609 $uploadInfo['contributor'] = $this->handleContributor();
610 } elseif ( $tag == 'contents' ) {
611 $contents = $this->nodeContents();
612 $encoding = $this->reader
->getAttribute( 'encoding' );
613 if ( $encoding === 'base64' ) {
614 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
616 } elseif ( $tag != '#text' ) {
617 $this->warn( "Unhandled upload XML tag $tag" );
622 if ( $this->mImageBasePath
&& isset( $uploadInfo['rel'] ) ) {
623 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
624 if ( file_exists( $path ) ) {
625 $uploadInfo['fileSrc'] = $path;
629 if ( $this->mImportUploads
) {
630 return $this->processUpload( $pageInfo, $uploadInfo );
634 private function dumpTemp( $contents ) {
635 $filename = tempnam( wfTempDir(), 'importupload' );
636 file_put_contents( $filename, $contents );
641 private function processUpload( $pageInfo, $uploadInfo ) {
642 $revision = new WikiRevision
;
643 $text = isset( $uploadInfo['text'] ) ?
$uploadInfo['text'] : '';
645 $revision->setTitle( $pageInfo['_title'] );
646 $revision->setID( $pageInfo['id'] );
647 $revision->setTimestamp( $uploadInfo['timestamp'] );
648 $revision->setText( $text );
649 $revision->setFilename( $uploadInfo['filename'] );
650 if ( isset( $uploadInfo['archivename'] ) ) {
651 $revision->setArchiveName( $uploadInfo['archivename'] );
653 $revision->setSrc( $uploadInfo['src'] );
654 if ( isset( $uploadInfo['fileSrc'] ) ) {
655 $revision->setFileSrc( $uploadInfo['fileSrc'] );
657 $revision->setSize( intval( $uploadInfo['size'] ) );
658 $revision->setComment( $uploadInfo['comment'] );
660 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
661 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
663 if ( isset( $uploadInfo['contributor']['username'] ) ) {
664 $revision->setUserName( $uploadInfo['contributor']['username'] );
667 return call_user_func( $this->mUploadCallback
, $revision );
670 private function handleContributor() {
671 $fields = array( 'id', 'ip', 'username' );
674 while ( $this->reader
->read() ) {
675 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
676 $this->reader
->name
== 'contributor') {
680 $tag = $this->reader
->name
;
682 if ( in_array( $tag, $fields ) ) {
683 $info[$tag] = $this->nodeContents();
690 private function processTitle( $text ) {
692 $origTitle = Title
::newFromText( $workTitle );
694 if( !is_null( $this->mTargetNamespace
) && !is_null( $origTitle ) ) {
695 $title = Title
::makeTitle( $this->mTargetNamespace
,
696 $origTitle->getDBkey() );
698 $title = Title
::newFromText( $workTitle );
701 if( is_null( $title ) ) {
702 // Invalid page title? Ignore the page
703 $this->notice( "Skipping invalid page title '$workTitle'" );
705 } elseif( $title->getInterwiki() != '' ) {
706 $this->notice( "Skipping interwiki page title '$workTitle'" );
710 return array( $title, $origTitle );
714 /** This is a horrible hack used to keep source compatibility */
715 class UploadSourceAdapter
{
716 static $sourceRegistrations = array();
722 static function registerSource( $source ) {
723 $id = wfGenerateToken();
725 self
::$sourceRegistrations[$id] = $source;
730 function stream_open( $path, $mode, $options, &$opened_path ) {
731 $url = parse_url($path);
734 if ( !isset( self
::$sourceRegistrations[$id] ) ) {
738 $this->mSource
= self
::$sourceRegistrations[$id];
743 function stream_read( $count ) {
747 while ( !$leave && !$this->mSource
->atEnd() &&
748 strlen($this->mBuffer
) < $count ) {
749 $read = $this->mSource
->readChunk();
751 if ( !strlen($read) ) {
755 $this->mBuffer
.= $read;
758 if ( strlen($this->mBuffer
) ) {
759 $return = substr( $this->mBuffer
, 0, $count );
760 $this->mBuffer
= substr( $this->mBuffer
, $count );
763 $this->mPosition +
= strlen($return);
768 function stream_write( $data ) {
772 function stream_tell() {
773 return $this->mPosition
;
776 function stream_eof() {
777 return $this->mSource
->atEnd();
780 function url_stat() {
783 $result['dev'] = $result[0] = 0;
784 $result['ino'] = $result[1] = 0;
785 $result['mode'] = $result[2] = 0;
786 $result['nlink'] = $result[3] = 0;
787 $result['uid'] = $result[4] = 0;
788 $result['gid'] = $result[5] = 0;
789 $result['rdev'] = $result[6] = 0;
790 $result['size'] = $result[7] = 0;
791 $result['atime'] = $result[8] = 0;
792 $result['mtime'] = $result[9] = 0;
793 $result['ctime'] = $result[10] = 0;
794 $result['blksize'] = $result[11] = 0;
795 $result['blocks'] = $result[12] = 0;
801 class XMLReader2
extends XMLReader
{
802 function nodeContents() {
803 if( $this->isEmptyElement
) {
807 while( $this->read() ) {
808 switch( $this->nodeType
) {
809 case XmlReader
::TEXT
:
810 case XmlReader
::SIGNIFICANT_WHITESPACE
:
811 $buffer .= $this->value
;
813 case XmlReader
::END_ELEMENT
:
817 return $this->close();
822 * @todo document (e.g. one-sentence class description).
823 * @ingroup SpecialPage
826 var $importer = null;
829 var $timestamp = "20010115000000";
839 var $archiveName = '';
841 function setTitle( $title ) {
842 if( is_object( $title ) ) {
843 $this->title
= $title;
844 } elseif( is_null( $title ) ) {
845 throw new MWException( "WikiRevision given a null title in import. You may need to adjust \$wgLegalTitleChars." );
847 throw new MWException( "WikiRevision given non-object title in import." );
851 function setID( $id ) {
855 function setTimestamp( $ts ) {
856 # 2003-08-05T18:30:02Z
857 $this->timestamp
= wfTimestamp( TS_MW
, $ts );
860 function setUsername( $user ) {
861 $this->user_text
= $user;
864 function setUserIP( $ip ) {
865 $this->user_text
= $ip;
868 function setText( $text ) {
872 function setComment( $text ) {
873 $this->comment
= $text;
876 function setMinor( $minor ) {
877 $this->minor
= (bool)$minor;
880 function setSrc( $src ) {
883 function setFileSrc( $src ) {
884 $this->fileSrc
= $src;
887 function setFilename( $filename ) {
888 $this->filename
= $filename;
890 function setArchiveName( $archiveName ) {
891 $this->archiveName
= $archiveName;
894 function setSize( $size ) {
895 $this->size
= intval( $size );
898 function setType( $type ) {
902 function setAction( $action ) {
903 $this->action
= $action;
906 function setParams( $params ) {
907 $this->params
= $params;
913 function getTitle() {
921 function getTimestamp() {
922 return $this->timestamp
;
926 return $this->user_text
;
933 function getComment() {
934 return $this->comment
;
937 function getMinor() {
944 function getFileSrc() {
945 return $this->fileSrc
;
948 function getFilename() {
949 return $this->filename
;
951 function getArchiveName() {
952 return $this->archiveName
;
963 function getAction() {
964 return $this->action
;
967 function getParams() {
968 return $this->params
;
971 function importOldRevision() {
972 $dbw = wfGetDB( DB_MASTER
);
974 # Sneak a single revision into place
975 $user = User
::newFromName( $this->getUser() );
977 $userId = intval( $user->getId() );
978 $userText = $user->getName();
981 $userText = $this->getUser();
984 // avoid memory leak...?
985 $linkCache = LinkCache
::singleton();
988 $article = new Article( $this->title
);
989 $pageId = $article->getId();
991 # must create the page...
992 $pageId = $article->insertOn( $dbw );
997 $prior = $dbw->selectField( 'revision', '1',
998 array( 'rev_page' => $pageId,
999 'rev_timestamp' => $dbw->timestamp( $this->timestamp
),
1000 'rev_user_text' => $userText,
1001 'rev_comment' => $this->getComment() ),
1005 // FIXME: this could fail slightly for multiple matches :P
1006 wfDebug( __METHOD__
. ": skipping existing revision for [[" .
1007 $this->title
->getPrefixedText() . "]], timestamp " . $this->timestamp
. "\n" );
1012 # FIXME: Use original rev_id optionally (better for backups)
1014 $revision = new Revision( array(
1016 'text' => $this->getText(),
1017 'comment' => $this->getComment(),
1019 'user_text' => $userText,
1020 'timestamp' => $this->timestamp
,
1021 'minor_edit' => $this->minor
,
1023 $revId = $revision->insertOn( $dbw );
1024 $changed = $article->updateIfNewerOn( $dbw, $revision );
1026 # To be on the safe side...
1027 $tempTitle = $GLOBALS['wgTitle'];
1028 $GLOBALS['wgTitle'] = $this->title
;
1031 wfDebug( __METHOD__
. ": running onArticleCreate\n" );
1032 Article
::onArticleCreate( $this->title
);
1034 wfDebug( __METHOD__
. ": running create updates\n" );
1035 $article->createUpdates( $revision );
1037 } elseif( $changed ) {
1038 wfDebug( __METHOD__
. ": running onArticleEdit\n" );
1039 Article
::onArticleEdit( $this->title
);
1041 wfDebug( __METHOD__
. ": running edit updates\n" );
1042 $article->editUpdates(
1044 $this->getComment(),
1049 $GLOBALS['wgTitle'] = $tempTitle;
1054 function importLogItem() {
1055 $dbw = wfGetDB( DB_MASTER
);
1056 # FIXME: this will not record autoblocks
1057 if( !$this->getTitle() ) {
1058 wfDebug( __METHOD__
. ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1059 $this->timestamp
. "\n" );
1062 # Check if it exists already
1063 // FIXME: use original log ID (better for backups)
1064 $prior = $dbw->selectField( 'logging', '1',
1065 array( 'log_type' => $this->getType(),
1066 'log_action' => $this->getAction(),
1067 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1068 'log_namespace' => $this->getTitle()->getNamespace(),
1069 'log_title' => $this->getTitle()->getDBkey(),
1070 'log_comment' => $this->getComment(),
1071 #'log_user_text' => $this->user_text,
1072 'log_params' => $this->params
),
1075 // FIXME: this could fail slightly for multiple matches :P
1077 wfDebug( __METHOD__
. ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp " .
1078 $this->timestamp
. "\n" );
1081 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1083 'log_id' => $log_id,
1084 'log_type' => $this->type
,
1085 'log_action' => $this->action
,
1086 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1087 'log_user' => User
::idFromName( $this->user_text
),
1088 #'log_user_text' => $this->user_text,
1089 'log_namespace' => $this->getTitle()->getNamespace(),
1090 'log_title' => $this->getTitle()->getDBkey(),
1091 'log_comment' => $this->getComment(),
1092 'log_params' => $this->params
1094 $dbw->insert( 'logging', $data, __METHOD__
);
1097 function importUpload() {
1099 $archiveName = $this->getArchiveName();
1100 if ( $archiveName ) {
1101 wfDebug( __METHOD__
. "Importing archived file as $archiveName\n" );
1102 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1103 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1105 $file = wfLocalFile( $this->getTitle() );
1106 wfDebug( __METHOD__
. 'Importing new file as ' . $file->getName() . "\n" );
1107 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1108 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1109 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1110 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1111 wfDebug( __METHOD__
. "File already exists; importing as $archiveName\n" );
1115 wfDebug( __METHOD__
. ': Bad file for ' . $this->getTitle() . "\n" );
1119 # Get the file source or download if necessary
1120 $source = $this->getFileSrc();
1122 $source = $this->downloadSource();
1125 wfDebug( __METHOD__
. ": Could not fetch remote file.\n" );
1129 $user = User
::newFromName( $this->user_text
);
1131 # Do the actual upload
1132 if ( $archiveName ) {
1133 $status = $file->uploadOld( $source, $archiveName,
1134 $this->getTimestamp(), $this->getComment(), $user, File
::DELETE_SOURCE
);
1136 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1137 File
::DELETE_SOURCE
, false, $this->getTimestamp(), $user );
1140 if ( $status->isGood() ) {
1141 wfDebug( __METHOD__
. ": Succesful\n" );
1144 wfDebug( __METHOD__
. ': failed: ' . $status->getXml() . "\n" );
1149 function downloadSource() {
1150 global $wgEnableUploads;
1151 if( !$wgEnableUploads ) {
1155 $tempo = tempnam( wfTempDir(), 'download' );
1156 $f = fopen( $tempo, 'wb' );
1158 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1163 $src = $this->getSrc();
1164 $data = Http
::get( $src );
1166 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1172 fwrite( $f, $data );
1181 * @todo document (e.g. one-sentence class description).
1182 * @ingroup SpecialPage
1184 class ImportStringSource
{
1185 function __construct( $string ) {
1186 $this->mString
= $string;
1187 $this->mRead
= false;
1191 return $this->mRead
;
1194 function readChunk() {
1195 if( $this->atEnd() ) {
1198 $this->mRead
= true;
1199 return $this->mString
;
1205 * @todo document (e.g. one-sentence class description).
1206 * @ingroup SpecialPage
1208 class ImportStreamSource
{
1209 function __construct( $handle ) {
1210 $this->mHandle
= $handle;
1214 return feof( $this->mHandle
);
1217 function readChunk() {
1218 return fread( $this->mHandle
, 32768 );
1221 static function newFromFile( $filename ) {
1222 $file = @fopen
( $filename, 'rt' );
1224 return Status
::newFatal( "importcantopen" );
1226 return Status
::newGood( new ImportStreamSource( $file ) );
1229 static function newFromUpload( $fieldname = "xmlimport" ) {
1230 $upload =& $_FILES[$fieldname];
1232 if( !isset( $upload ) ||
!$upload['name'] ) {
1233 return Status
::newFatal( 'importnofile' );
1235 if( !empty( $upload['error'] ) ) {
1236 switch($upload['error']){
1237 case 1: # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1238 return Status
::newFatal( 'importuploaderrorsize' );
1239 case 2: # The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
1240 return Status
::newFatal( 'importuploaderrorsize' );
1241 case 3: # The uploaded file was only partially uploaded
1242 return Status
::newFatal( 'importuploaderrorpartial' );
1243 case 6: #Missing a temporary folder.
1244 return Status
::newFatal( 'importuploaderrortemp' );
1245 # case else: # Currently impossible
1249 $fname = $upload['tmp_name'];
1250 if( is_uploaded_file( $fname ) ) {
1251 return ImportStreamSource
::newFromFile( $fname );
1253 return Status
::newFatal( 'importnofile' );
1257 static function newFromURL( $url, $method = 'GET' ) {
1258 wfDebug( __METHOD__
. ": opening $url\n" );
1259 # Use the standard HTTP fetch function; it times out
1260 # quicker and sorts out user-agent problems which might
1261 # otherwise prevent importing from large sites, such
1262 # as the Wikimedia cluster, etc.
1263 $data = Http
::request( $method, $url );
1264 if( $data !== false ) {
1266 fwrite( $file, $data );
1269 return Status
::newGood( new ImportStreamSource( $file ) );
1271 return Status
::newFatal( 'importcantopen' );
1275 public static function newFromInterwiki( $interwiki, $page, $history = false, $templates = false, $pageLinkDepth = 0 ) {
1277 return Status
::newFatal( 'import-noarticle' );
1279 $link = Title
::newFromText( "$interwiki:Special:Export/$page" );
1280 if( is_null( $link ) ||
$link->getInterwiki() == '' ) {
1281 return Status
::newFatal( 'importbadinterwiki' );
1284 if ( $history ) $params['history'] = 1;
1285 if ( $templates ) $params['templates'] = 1;
1286 if ( $pageLinkDepth ) $params['pagelink-depth'] = $pageLinkDepth;
1287 $url = $link->getFullUrl( $params );
1288 # For interwikis, use POST to avoid redirects.
1289 return ImportStreamSource
::newFromURL( $url, "POST" );