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;
39 private $mNoUpdates = false;
42 * Creates an ImportXMLReader drawing from the source provided
44 function __construct( $source ) {
45 $this->reader
= new XMLReader();
47 stream_wrapper_register( 'uploadsource', 'UploadSourceAdapter' );
48 $id = UploadSourceAdapter
::registerSource( $source );
49 if (defined( 'LIBXML_PARSEHUGE' ) ) {
50 $this->reader
->open( "uploadsource://$id", null, LIBXML_PARSEHUGE
);
53 $this->reader
->open( "uploadsource://$id" );
57 $this->setRevisionCallback( array( $this, "importRevision" ) );
58 $this->setUploadCallback( array( $this, 'importUpload' ) );
59 $this->setLogItemCallback( array( $this, 'importLogItem' ) );
60 $this->setPageOutCallback( array( $this, 'finishImportPage' ) );
63 private function throwXmlError( $err ) {
64 $this->debug( "FAILURE: $err" );
65 wfDebug( "WikiImporter XML error: $err\n" );
68 private function debug( $data ) {
70 wfDebug( "IMPORT: $data\n" );
74 private function warn( $data ) {
75 wfDebug( "IMPORT: $data\n" );
78 private function notice( $data ) {
79 global $wgCommandLineMode;
80 if( $wgCommandLineMode ) {
84 $wgOut->addHTML( "<li>" . htmlspecialchars( $data ) . "</li>\n" );
91 function setDebug( $debug ) {
92 $this->mDebug
= $debug;
96 * Set 'no updates' mode. In this mode, the link tables will not be updated by the importer
98 function setNoUpdates( $noupdates ) {
99 $this->mNoUpdates
= $noupdates;
103 * Sets the action to perform as each new page in the stream is reached.
104 * @param $callback callback
107 public function setPageCallback( $callback ) {
108 $previous = $this->mPageCallback
;
109 $this->mPageCallback
= $callback;
114 * Sets the action to perform as each page in the stream is completed.
115 * Callback accepts the page title (as a Title object), a second object
116 * with the original title form (in case it's been overridden into a
117 * local namespace), and a count of revisions.
119 * @param $callback callback
122 public function setPageOutCallback( $callback ) {
123 $previous = $this->mPageOutCallback
;
124 $this->mPageOutCallback
= $callback;
129 * Sets the action to perform as each page revision is reached.
130 * @param $callback callback
133 public function setRevisionCallback( $callback ) {
134 $previous = $this->mRevisionCallback
;
135 $this->mRevisionCallback
= $callback;
140 * Sets the action to perform as each file upload version is reached.
141 * @param $callback callback
144 public function setUploadCallback( $callback ) {
145 $previous = $this->mUploadCallback
;
146 $this->mUploadCallback
= $callback;
151 * Sets the action to perform as each log item reached.
152 * @param $callback callback
155 public function setLogItemCallback( $callback ) {
156 $previous = $this->mLogItemCallback
;
157 $this->mLogItemCallback
= $callback;
162 * Sets the action to perform when site info is encountered
163 * @param $callback callback
166 public function setSiteInfoCallback( $callback ) {
167 $previous = $this->mSiteInfoCallback
;
168 $this->mSiteInfoCallback
= $callback;
173 * Set a target namespace to override the defaults
175 public function setTargetNamespace( $namespace ) {
176 if( is_null( $namespace ) ) {
177 // Don't override namespaces
178 $this->mTargetNamespace
= null;
179 } elseif( $namespace >= 0 ) {
180 // @todo FIXME: Check for validity
181 $this->mTargetNamespace
= intval( $namespace );
190 public function setImageBasePath( $dir ) {
191 $this->mImageBasePath
= $dir;
197 public function setImportUploads( $import ) {
198 $this->mImportUploads
= $import;
202 * Default per-revision callback, performs the import.
203 * @param $revision WikiRevision
205 public function importRevision( $revision ) {
206 $dbw = wfGetDB( DB_MASTER
);
207 return $dbw->deadlockLoop( array( $revision, 'importOldRevision' ) );
211 * Default per-revision callback, performs the import.
212 * @param $rev WikiRevision
214 public function importLogItem( $rev ) {
215 $dbw = wfGetDB( DB_MASTER
);
216 return $dbw->deadlockLoop( array( $rev, 'importLogItem' ) );
222 public function importUpload( $revision ) {
223 $dbw = wfGetDB( DB_MASTER
);
224 return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
228 * Mostly for hook use
230 public function finishImportPage( $title, $origTitle, $revCount, $sRevCount, $pageInfo ) {
231 $args = func_get_args();
232 return wfRunHooks( 'AfterImportPage', $args );
236 * Alternate per-revision callback, for debugging.
237 * @param $revision WikiRevision
239 public function debugRevisionHandler( &$revision ) {
240 $this->debug( "Got revision:" );
241 if( is_object( $revision->title
) ) {
242 $this->debug( "-- Title: " . $revision->title
->getPrefixedText() );
244 $this->debug( "-- Title: <invalid>" );
246 $this->debug( "-- User: " . $revision->user_text
);
247 $this->debug( "-- Timestamp: " . $revision->timestamp
);
248 $this->debug( "-- Comment: " . $revision->comment
);
249 $this->debug( "-- Text: " . $revision->text
);
253 * Notify the callback function when a new <page> is reached.
254 * @param $title Title
256 function pageCallback( $title ) {
257 if( isset( $this->mPageCallback
) ) {
258 call_user_func( $this->mPageCallback
, $title );
263 * Notify the callback function when a </page> is closed.
264 * @param $title Title
265 * @param $origTitle Title
266 * @param $revCount Integer
267 * @param $sucCount Int: number of revisions for which callback returned true
268 * @param $pageInfo Array: associative array of page information
270 private function pageOutCallback( $title, $origTitle, $revCount, $sucCount, $pageInfo ) {
271 if( isset( $this->mPageOutCallback
) ) {
272 $args = func_get_args();
273 call_user_func_array( $this->mPageOutCallback
, $args );
278 * Notify the callback function of a revision
279 * @param $revision A WikiRevision object
281 private function revisionCallback( $revision ) {
282 if ( isset( $this->mRevisionCallback
) ) {
283 return call_user_func_array( $this->mRevisionCallback
,
284 array( $revision, $this ) );
291 * Notify the callback function of a new log item
292 * @param $revision A WikiRevision object
294 private function logItemCallback( $revision ) {
295 if ( isset( $this->mLogItemCallback
) ) {
296 return call_user_func_array( $this->mLogItemCallback
,
297 array( $revision, $this ) );
304 * Shouldn't something like this be built-in to XMLReader?
305 * Fetches text contents of the current element, assuming
306 * no sub-elements or such scary things.
310 private function nodeContents() {
311 if( $this->reader
->isEmptyElement
) {
315 while( $this->reader
->read() ) {
316 switch( $this->reader
->nodeType
) {
317 case XmlReader
::TEXT
:
318 case XmlReader
::SIGNIFICANT_WHITESPACE
:
319 $buffer .= $this->reader
->value
;
321 case XmlReader
::END_ELEMENT
:
326 $this->reader
->close();
332 /** Left in for debugging */
333 private function dumpElement() {
334 static $lookup = null;
336 $xmlReaderConstants = array(
351 "SIGNIFICANT_WHITESPACE",
358 foreach( $xmlReaderConstants as $name ) {
359 $lookup[constant("XmlReader::$name")] = $name;
364 $lookup[$this->reader
->nodeType
],
371 * Primary entry point
373 public function doImport() {
374 $this->reader
->read();
376 if ( $this->reader
->name
!= 'mediawiki' ) {
377 throw new MWException( "Expected <mediawiki> tag, got ".
378 $this->reader
->name
);
380 $this->debug( "<mediawiki> tag is correct." );
382 $this->debug( "Starting primary dump processing loop." );
384 $keepReading = $this->reader
->read();
386 while ( $keepReading ) {
387 $tag = $this->reader
->name
;
388 $type = $this->reader
->nodeType
;
390 if ( !wfRunHooks( 'ImportHandleToplevelXMLTag', $this ) ) {
392 } elseif ( $tag == 'mediawiki' && $type == XmlReader
::END_ELEMENT
) {
394 } elseif ( $tag == 'siteinfo' ) {
395 $this->handleSiteInfo();
396 } elseif ( $tag == 'page' ) {
398 } elseif ( $tag == 'logitem' ) {
399 $this->handleLogItem();
400 } elseif ( $tag != '#text' ) {
401 $this->warn( "Unhandled top-level XML tag $tag" );
407 $keepReading = $this->reader
->next();
409 $this->debug( "Skip" );
411 $keepReading = $this->reader
->read();
420 * @throws MWException
422 private function handleSiteInfo() {
423 // Site info is useful, but not actually used for dump imports.
424 // Includes a quick short-circuit to save performance.
425 if ( ! $this->mSiteInfoCallback
) {
426 $this->reader
->next();
429 throw new MWException( "SiteInfo tag is not yet handled, do not set mSiteInfoCallback" );
432 private function handleLogItem() {
433 $this->debug( "Enter log item handler." );
436 // Fields that can just be stuffed in the pageInfo object
437 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
438 'logtitle', 'params' );
440 while ( $this->reader
->read() ) {
441 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
442 $this->reader
->name
== 'logitem') {
446 $tag = $this->reader
->name
;
448 if ( !wfRunHooks( 'ImportHandleLogItemXMLTag',
449 $this, $logInfo ) ) {
451 } elseif ( in_array( $tag, $normalFields ) ) {
452 $logInfo[$tag] = $this->nodeContents();
453 } elseif ( $tag == 'contributor' ) {
454 $logInfo['contributor'] = $this->handleContributor();
455 } elseif ( $tag != '#text' ) {
456 $this->warn( "Unhandled log-item XML tag $tag" );
460 $this->processLogItem( $logInfo );
467 private function processLogItem( $logInfo ) {
468 $revision = new WikiRevision
;
470 $revision->setID( $logInfo['id'] );
471 $revision->setType( $logInfo['type'] );
472 $revision->setAction( $logInfo['action'] );
473 $revision->setTimestamp( $logInfo['timestamp'] );
474 $revision->setParams( $logInfo['params'] );
475 $revision->setTitle( Title
::newFromText( $logInfo['logtitle'] ) );
476 $revision->setNoUpdates( $this->mNoUpdates
);
478 if ( isset( $logInfo['comment'] ) ) {
479 $revision->setComment( $logInfo['comment'] );
482 if ( isset( $logInfo['contributor']['ip'] ) ) {
483 $revision->setUserIP( $logInfo['contributor']['ip'] );
485 if ( isset( $logInfo['contributor']['username'] ) ) {
486 $revision->setUserName( $logInfo['contributor']['username'] );
489 return $this->logItemCallback( $revision );
492 private function handlePage() {
494 $this->debug( "Enter page handler." );
495 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
497 // Fields that can just be stuffed in the pageInfo object
498 $normalFields = array( 'title', 'id', 'redirect', 'restrictions' );
503 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
504 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
505 $this->reader
->name
== 'page') {
509 $tag = $this->reader
->name
;
512 // The title is invalid, bail out of this page
514 } elseif ( !wfRunHooks( 'ImportHandlePageXMLTag', array( $this,
517 } elseif ( in_array( $tag, $normalFields ) ) {
518 $pageInfo[$tag] = $this->nodeContents();
519 if ( $tag == 'title' ) {
520 $title = $this->processTitle( $pageInfo['title'] );
527 $this->pageCallback( $title );
528 list( $pageInfo['_title'], $origTitle ) = $title;
530 } elseif ( $tag == 'revision' ) {
531 $this->handleRevision( $pageInfo );
532 } elseif ( $tag == 'upload' ) {
533 $this->handleUpload( $pageInfo );
534 } elseif ( $tag != '#text' ) {
535 $this->warn( "Unhandled page XML tag $tag" );
540 $this->pageOutCallback( $pageInfo['_title'], $origTitle,
541 $pageInfo['revisionCount'],
542 $pageInfo['successfulRevisionCount'],
549 private function handleRevision( &$pageInfo ) {
550 $this->debug( "Enter revision handler" );
551 $revisionInfo = array();
553 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'text' );
557 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
558 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
559 $this->reader
->name
== 'revision') {
563 $tag = $this->reader
->name
;
565 if ( !wfRunHooks( 'ImportHandleRevisionXMLTag', $this,
566 $pageInfo, $revisionInfo ) ) {
568 } elseif ( in_array( $tag, $normalFields ) ) {
569 $revisionInfo[$tag] = $this->nodeContents();
570 } elseif ( $tag == 'contributor' ) {
571 $revisionInfo['contributor'] = $this->handleContributor();
572 } elseif ( $tag != '#text' ) {
573 $this->warn( "Unhandled revision XML tag $tag" );
578 $pageInfo['revisionCount']++
;
579 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
580 $pageInfo['successfulRevisionCount']++
;
586 * @param $revisionInfo
589 private function processRevision( $pageInfo, $revisionInfo ) {
590 $revision = new WikiRevision
;
592 if( isset( $revisionInfo['id'] ) ) {
593 $revision->setID( $revisionInfo['id'] );
595 if ( isset( $revisionInfo['text'] ) ) {
596 $revision->setText( $revisionInfo['text'] );
598 $revision->setTitle( $pageInfo['_title'] );
600 if ( isset( $revisionInfo['timestamp'] ) ) {
601 $revision->setTimestamp( $revisionInfo['timestamp'] );
603 $revision->setTimestamp( wfTimestampNow() );
606 if ( isset( $revisionInfo['comment'] ) ) {
607 $revision->setComment( $revisionInfo['comment'] );
610 if ( isset( $revisionInfo['minor'] ) ) {
611 $revision->setMinor( true );
613 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
614 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
616 if ( isset( $revisionInfo['contributor']['username'] ) ) {
617 $revision->setUserName( $revisionInfo['contributor']['username'] );
619 $revision->setNoUpdates( $this->mNoUpdates
);
621 return $this->revisionCallback( $revision );
628 private function handleUpload( &$pageInfo ) {
629 $this->debug( "Enter upload handler" );
630 $uploadInfo = array();
632 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
633 'src', 'size', 'sha1base36', 'archivename', 'rel' );
637 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
638 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
639 $this->reader
->name
== 'upload') {
643 $tag = $this->reader
->name
;
645 if ( !wfRunHooks( 'ImportHandleUploadXMLTag', $this,
648 } elseif ( in_array( $tag, $normalFields ) ) {
649 $uploadInfo[$tag] = $this->nodeContents();
650 } elseif ( $tag == 'contributor' ) {
651 $uploadInfo['contributor'] = $this->handleContributor();
652 } elseif ( $tag == 'contents' ) {
653 $contents = $this->nodeContents();
654 $encoding = $this->reader
->getAttribute( 'encoding' );
655 if ( $encoding === 'base64' ) {
656 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
657 $uploadInfo['isTempSrc'] = true;
659 } elseif ( $tag != '#text' ) {
660 $this->warn( "Unhandled upload XML tag $tag" );
665 if ( $this->mImageBasePath
&& isset( $uploadInfo['rel'] ) ) {
666 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
667 if ( file_exists( $path ) ) {
668 $uploadInfo['fileSrc'] = $path;
669 $uploadInfo['isTempSrc'] = false;
673 if ( $this->mImportUploads
) {
674 return $this->processUpload( $pageInfo, $uploadInfo );
682 private function dumpTemp( $contents ) {
683 $filename = tempnam( wfTempDir(), 'importupload' );
684 file_put_contents( $filename, $contents );
693 private function processUpload( $pageInfo, $uploadInfo ) {
694 $revision = new WikiRevision
;
695 $text = isset( $uploadInfo['text'] ) ?
$uploadInfo['text'] : '';
697 $revision->setTitle( $pageInfo['_title'] );
698 $revision->setID( $pageInfo['id'] );
699 $revision->setTimestamp( $uploadInfo['timestamp'] );
700 $revision->setText( $text );
701 $revision->setFilename( $uploadInfo['filename'] );
702 if ( isset( $uploadInfo['archivename'] ) ) {
703 $revision->setArchiveName( $uploadInfo['archivename'] );
705 $revision->setSrc( $uploadInfo['src'] );
706 if ( isset( $uploadInfo['fileSrc'] ) ) {
707 $revision->setFileSrc( $uploadInfo['fileSrc'],
708 !empty( $uploadInfo['isTempSrc'] ) );
710 if ( isset( $uploadInfo['sha1base36'] ) ) {
711 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
713 $revision->setSize( intval( $uploadInfo['size'] ) );
714 $revision->setComment( $uploadInfo['comment'] );
716 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
717 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
719 if ( isset( $uploadInfo['contributor']['username'] ) ) {
720 $revision->setUserName( $uploadInfo['contributor']['username'] );
722 $revision->setNoUpdates( $this->mNoUpdates
);
724 return call_user_func( $this->mUploadCallback
, $revision );
730 private function handleContributor() {
731 $fields = array( 'id', 'ip', 'username' );
734 while ( $this->reader
->read() ) {
735 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
736 $this->reader
->name
== 'contributor') {
740 $tag = $this->reader
->name
;
742 if ( in_array( $tag, $fields ) ) {
743 $info[$tag] = $this->nodeContents();
751 * @param $text string
752 * @return Array or false
754 private function processTitle( $text ) {
755 global $wgCommandLineMode;
758 $origTitle = Title
::newFromText( $workTitle );
760 if( !is_null( $this->mTargetNamespace
) && !is_null( $origTitle ) ) {
761 $title = Title
::makeTitle( $this->mTargetNamespace
,
762 $origTitle->getDBkey() );
764 $title = Title
::newFromText( $workTitle );
767 if( is_null( $title ) ) {
768 # Invalid page title? Ignore the page
769 $this->notice( "Skipping invalid page title '$workTitle'" );
771 } elseif( $title->getInterwiki() != '' ) {
772 $this->notice( "Skipping interwiki page title '$workTitle'" );
774 } elseif( !$title->userCan( 'edit' ) && !$wgCommandLineMode ) {
775 # Do not import if the importing wiki user cannot edit this page
776 $this->notice( wfMessage( 'import-error-edit', $title->getText() )->text() );
778 } elseif( !$title->exists() && !$title->userCan( 'create' ) && !$wgCommandLineMode ) {
779 # Do not import if the importing wiki user cannot create this page
780 $this->notice( wfMessage( 'import-error-create', $title->getText() )->text() );
784 return array( $title, $origTitle );
788 /** This is a horrible hack used to keep source compatibility */
789 class UploadSourceAdapter
{
790 static $sourceRegistrations = array();
800 static function registerSource( $source ) {
801 $id = wfGenerateToken();
803 self
::$sourceRegistrations[$id] = $source;
812 * @param $opened_path
815 function stream_open( $path, $mode, $options, &$opened_path ) {
816 $url = parse_url($path);
819 if ( !isset( self
::$sourceRegistrations[$id] ) ) {
823 $this->mSource
= self
::$sourceRegistrations[$id];
832 function stream_read( $count ) {
836 while ( !$leave && !$this->mSource
->atEnd() &&
837 strlen($this->mBuffer
) < $count ) {
838 $read = $this->mSource
->readChunk();
840 if ( !strlen($read) ) {
844 $this->mBuffer
.= $read;
847 if ( strlen($this->mBuffer
) ) {
848 $return = substr( $this->mBuffer
, 0, $count );
849 $this->mBuffer
= substr( $this->mBuffer
, $count );
852 $this->mPosition +
= strlen($return);
861 function stream_write( $data ) {
868 function stream_tell() {
869 return $this->mPosition
;
875 function stream_eof() {
876 return $this->mSource
->atEnd();
882 function url_stat() {
885 $result['dev'] = $result[0] = 0;
886 $result['ino'] = $result[1] = 0;
887 $result['mode'] = $result[2] = 0;
888 $result['nlink'] = $result[3] = 0;
889 $result['uid'] = $result[4] = 0;
890 $result['gid'] = $result[5] = 0;
891 $result['rdev'] = $result[6] = 0;
892 $result['size'] = $result[7] = 0;
893 $result['atime'] = $result[8] = 0;
894 $result['mtime'] = $result[9] = 0;
895 $result['ctime'] = $result[10] = 0;
896 $result['blksize'] = $result[11] = 0;
897 $result['blocks'] = $result[12] = 0;
903 class XMLReader2
extends XMLReader
{
906 * @return bool|string
908 function nodeContents() {
909 if( $this->isEmptyElement
) {
913 while( $this->read() ) {
914 switch( $this->nodeType
) {
915 case XmlReader
::TEXT
:
916 case XmlReader
::SIGNIFICANT_WHITESPACE
:
917 $buffer .= $this->value
;
919 case XmlReader
::END_ELEMENT
:
923 return $this->close();
928 * @todo document (e.g. one-sentence class description).
929 * @ingroup SpecialPage
932 var $importer = null;
935 var $timestamp = "20010115000000";
945 var $sha1base36 = false;
947 var $archiveName = '';
948 private $mNoUpdates = false;
952 * @throws MWException
954 function setTitle( $title ) {
955 if( is_object( $title ) ) {
956 $this->title
= $title;
957 } elseif( is_null( $title ) ) {
958 throw new MWException( "WikiRevision given a null title in import. You may need to adjust \$wgLegalTitleChars." );
960 throw new MWException( "WikiRevision given non-object title in import." );
967 function setID( $id ) {
974 function setTimestamp( $ts ) {
975 # 2003-08-05T18:30:02Z
976 $this->timestamp
= wfTimestamp( TS_MW
, $ts );
982 function setUsername( $user ) {
983 $this->user_text
= $user;
989 function setUserIP( $ip ) {
990 $this->user_text
= $ip;
996 function setText( $text ) {
1003 function setComment( $text ) {
1004 $this->comment
= $text;
1010 function setMinor( $minor ) {
1011 $this->minor
= (bool)$minor;
1017 function setSrc( $src ) {
1025 function setFileSrc( $src, $isTemp ) {
1026 $this->fileSrc
= $src;
1027 $this->fileIsTemp
= $isTemp;
1031 * @param $sha1base36
1033 function setSha1Base36( $sha1base36 ) {
1034 $this->sha1base36
= $sha1base36;
1040 function setFilename( $filename ) {
1041 $this->filename
= $filename;
1045 * @param $archiveName
1047 function setArchiveName( $archiveName ) {
1048 $this->archiveName
= $archiveName;
1054 function setSize( $size ) {
1055 $this->size
= intval( $size );
1061 function setType( $type ) {
1062 $this->type
= $type;
1065 function setAction( $action ) {
1066 $this->action
= $action;
1072 function setParams( $params ) {
1073 $this->params
= $params;
1079 public function setNoUpdates( $noupdates ) {
1080 $this->mNoUpdates
= $noupdates;
1086 function getTitle() {
1087 return $this->title
;
1100 function getTimestamp() {
1101 return $this->timestamp
;
1107 function getUser() {
1108 return $this->user_text
;
1114 function getText() {
1121 function getComment() {
1122 return $this->comment
;
1128 function getMinor() {
1129 return $this->minor
;
1140 * @return bool|String
1142 function getSha1() {
1143 if ( $this->sha1base36
) {
1144 return wfBaseConvert( $this->sha1base36
, 36, 16 );
1152 function getFileSrc() {
1153 return $this->fileSrc
;
1159 function isTempSrc() {
1160 return $this->isTemp
;
1166 function getFilename() {
1167 return $this->filename
;
1173 function getArchiveName() {
1174 return $this->archiveName
;
1180 function getSize() {
1187 function getType() {
1194 function getAction() {
1195 return $this->action
;
1201 function getParams() {
1202 return $this->params
;
1208 function importOldRevision() {
1209 $dbw = wfGetDB( DB_MASTER
);
1211 # Sneak a single revision into place
1212 $user = User
::newFromName( $this->getUser() );
1214 $userId = intval( $user->getId() );
1215 $userText = $user->getName();
1219 $userText = $this->getUser();
1220 $userObj = new User
;
1223 // avoid memory leak...?
1224 $linkCache = LinkCache
::singleton();
1225 $linkCache->clear();
1227 $article = new Article( $this->title
);
1228 $pageId = $article->getId();
1229 if( $pageId == 0 ) {
1230 # must create the page...
1231 $pageId = $article->insertOn( $dbw );
1233 $oldcountable = null;
1237 $prior = $dbw->selectField( 'revision', '1',
1238 array( 'rev_page' => $pageId,
1239 'rev_timestamp' => $dbw->timestamp( $this->timestamp
),
1240 'rev_user_text' => $userText,
1241 'rev_comment' => $this->getComment() ),
1245 // @todo FIXME: This could fail slightly for multiple matches :P
1246 wfDebug( __METHOD__
. ": skipping existing revision for [[" .
1247 $this->title
->getPrefixedText() . "]], timestamp " . $this->timestamp
. "\n" );
1250 $oldcountable = $article->isCountable();
1253 # @todo FIXME: Use original rev_id optionally (better for backups)
1255 $revision = new Revision( array(
1257 'text' => $this->getText(),
1258 'comment' => $this->getComment(),
1260 'user_text' => $userText,
1261 'timestamp' => $this->timestamp
,
1262 'minor_edit' => $this->minor
,
1264 $revision->insertOn( $dbw );
1265 $changed = $article->updateIfNewerOn( $dbw, $revision );
1267 if ( $changed !== false && !$this->mNoUpdates
) {
1268 wfDebug( __METHOD__
. ": running updates\n" );
1269 $article->doEditUpdates( $revision, $userObj, array( 'created' => $created, 'oldcountable' => $oldcountable ) );
1278 function importLogItem() {
1279 $dbw = wfGetDB( DB_MASTER
);
1280 # @todo FIXME: This will not record autoblocks
1281 if( !$this->getTitle() ) {
1282 wfDebug( __METHOD__
. ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1283 $this->timestamp
. "\n" );
1286 # Check if it exists already
1287 // @todo FIXME: Use original log ID (better for backups)
1288 $prior = $dbw->selectField( 'logging', '1',
1289 array( 'log_type' => $this->getType(),
1290 'log_action' => $this->getAction(),
1291 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1292 'log_namespace' => $this->getTitle()->getNamespace(),
1293 'log_title' => $this->getTitle()->getDBkey(),
1294 'log_comment' => $this->getComment(),
1295 #'log_user_text' => $this->user_text,
1296 'log_params' => $this->params
),
1299 // @todo FIXME: This could fail slightly for multiple matches :P
1301 wfDebug( __METHOD__
. ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp " .
1302 $this->timestamp
. "\n" );
1305 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1307 'log_id' => $log_id,
1308 'log_type' => $this->type
,
1309 'log_action' => $this->action
,
1310 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1311 'log_user' => User
::idFromName( $this->user_text
),
1312 #'log_user_text' => $this->user_text,
1313 'log_namespace' => $this->getTitle()->getNamespace(),
1314 'log_title' => $this->getTitle()->getDBkey(),
1315 'log_comment' => $this->getComment(),
1316 'log_params' => $this->params
1318 $dbw->insert( 'logging', $data, __METHOD__
);
1324 function importUpload() {
1326 $archiveName = $this->getArchiveName();
1327 if ( $archiveName ) {
1328 wfDebug( __METHOD__
. "Importing archived file as $archiveName\n" );
1329 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1330 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1332 $file = wfLocalFile( $this->getTitle() );
1333 wfDebug( __METHOD__
. 'Importing new file as ' . $file->getName() . "\n" );
1334 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1335 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1336 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1337 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1338 wfDebug( __METHOD__
. "File already exists; importing as $archiveName\n" );
1342 wfDebug( __METHOD__
. ': Bad file for ' . $this->getTitle() . "\n" );
1346 # Get the file source or download if necessary
1347 $source = $this->getFileSrc();
1348 $flags = $this->isTempSrc() ? File
::DELETE_SOURCE
: 0;
1350 $source = $this->downloadSource();
1351 $flags |
= File
::DELETE_SOURCE
;
1354 wfDebug( __METHOD__
. ": Could not fetch remote file.\n" );
1357 $sha1 = $this->getSha1();
1358 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1359 if ( $flags & File
::DELETE_SOURCE
) {
1360 # Broken file; delete it if it is a temporary file
1363 wfDebug( __METHOD__
. ": Corrupt file $source.\n" );
1367 $user = User
::newFromName( $this->user_text
);
1369 # Do the actual upload
1370 if ( $archiveName ) {
1371 $status = $file->uploadOld( $source, $archiveName,
1372 $this->getTimestamp(), $this->getComment(), $user, $flags );
1374 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1375 $flags, false, $this->getTimestamp(), $user );
1378 if ( $status->isGood() ) {
1379 wfDebug( __METHOD__
. ": Succesful\n" );
1382 wfDebug( __METHOD__
. ': failed: ' . $status->getXml() . "\n" );
1388 * @return bool|string
1390 function downloadSource() {
1391 global $wgEnableUploads;
1392 if( !$wgEnableUploads ) {
1396 $tempo = tempnam( wfTempDir(), 'download' );
1397 $f = fopen( $tempo, 'wb' );
1399 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1404 $src = $this->getSrc();
1405 $data = Http
::get( $src );
1407 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1413 fwrite( $f, $data );
1422 * @todo document (e.g. one-sentence class description).
1423 * @ingroup SpecialPage
1425 class ImportStringSource
{
1426 function __construct( $string ) {
1427 $this->mString
= $string;
1428 $this->mRead
= false;
1432 return $this->mRead
;
1435 function readChunk() {
1436 if( $this->atEnd() ) {
1439 $this->mRead
= true;
1440 return $this->mString
;
1445 * @todo document (e.g. one-sentence class description).
1446 * @ingroup SpecialPage
1448 class ImportStreamSource
{
1449 function __construct( $handle ) {
1450 $this->mHandle
= $handle;
1457 return feof( $this->mHandle
);
1460 function readChunk() {
1461 return fread( $this->mHandle
, 32768 );
1465 * @param $filename string
1468 static function newFromFile( $filename ) {
1469 wfSuppressWarnings();
1470 $file = fopen( $filename, 'rt' );
1471 wfRestoreWarnings();
1473 return Status
::newFatal( "importcantopen" );
1475 return Status
::newGood( new ImportStreamSource( $file ) );
1479 * @param $fieldname string
1482 static function newFromUpload( $fieldname = "xmlimport" ) {
1483 $upload =& $_FILES[$fieldname];
1485 if( !isset( $upload ) ||
!$upload['name'] ) {
1486 return Status
::newFatal( 'importnofile' );
1488 if( !empty( $upload['error'] ) ) {
1489 switch($upload['error']){
1490 case 1: # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1491 return Status
::newFatal( 'importuploaderrorsize' );
1492 case 2: # The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
1493 return Status
::newFatal( 'importuploaderrorsize' );
1494 case 3: # The uploaded file was only partially uploaded
1495 return Status
::newFatal( 'importuploaderrorpartial' );
1496 case 6: #Missing a temporary folder.
1497 return Status
::newFatal( 'importuploaderrortemp' );
1498 # case else: # Currently impossible
1502 $fname = $upload['tmp_name'];
1503 if( is_uploaded_file( $fname ) ) {
1504 return ImportStreamSource
::newFromFile( $fname );
1506 return Status
::newFatal( 'importnofile' );
1512 * @param $method string
1515 static function newFromURL( $url, $method = 'GET' ) {
1516 wfDebug( __METHOD__
. ": opening $url\n" );
1517 # Use the standard HTTP fetch function; it times out
1518 # quicker and sorts out user-agent problems which might
1519 # otherwise prevent importing from large sites, such
1520 # as the Wikimedia cluster, etc.
1521 $data = Http
::request( $method, $url );
1522 if( $data !== false ) {
1524 fwrite( $file, $data );
1527 return Status
::newGood( new ImportStreamSource( $file ) );
1529 return Status
::newFatal( 'importcantopen' );
1536 * @param $history bool
1537 * @param $templates bool
1538 * @param $pageLinkDepth int
1541 public static function newFromInterwiki( $interwiki, $page, $history = false, $templates = false, $pageLinkDepth = 0 ) {
1543 return Status
::newFatal( 'import-noarticle' );
1545 $link = Title
::newFromText( "$interwiki:Special:Export/$page" );
1546 if( is_null( $link ) ||
$link->getInterwiki() == '' ) {
1547 return Status
::newFatal( 'importbadinterwiki' );
1550 if ( $history ) $params['history'] = 1;
1551 if ( $templates ) $params['templates'] = 1;
1552 if ( $pageLinkDepth ) $params['pagelink-depth'] = $pageLinkDepth;
1553 $url = $link->getFullUrl( $params );
1554 # For interwikis, use POST to avoid redirects.
1555 return ImportStreamSource
::newFromURL( $url, "POST" );