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 if (defined( 'LIBXML_PARSEHUGE' ) ) {
49 $this->reader
->open( "uploadsource://$id", null, LIBXML_PARSEHUGE
);
52 $this->reader
->open( "uploadsource://$id" );
56 $this->setRevisionCallback( array( $this, "importRevision" ) );
57 $this->setUploadCallback( array( $this, 'importUpload' ) );
58 $this->setLogItemCallback( array( $this, 'importLogItem' ) );
59 $this->setPageOutCallback( array( $this, 'finishImportPage' ) );
62 private function throwXmlError( $err ) {
63 $this->debug( "FAILURE: $err" );
64 wfDebug( "WikiImporter XML error: $err\n" );
67 private function debug( $data ) {
69 wfDebug( "IMPORT: $data\n" );
73 private function warn( $data ) {
74 wfDebug( "IMPORT: $data\n" );
77 private function notice( $data ) {
78 global $wgCommandLineMode;
79 if( $wgCommandLineMode ) {
83 $wgOut->addHTML( "<li>" . htmlspecialchars( $data ) . "</li>\n" );
90 function setDebug( $debug ) {
91 $this->mDebug
= $debug;
95 * Sets the action to perform as each new page in the stream is reached.
96 * @param $callback callback
99 public function setPageCallback( $callback ) {
100 $previous = $this->mPageCallback
;
101 $this->mPageCallback
= $callback;
106 * Sets the action to perform as each page in the stream is completed.
107 * Callback accepts the page title (as a Title object), a second object
108 * with the original title form (in case it's been overridden into a
109 * local namespace), and a count of revisions.
111 * @param $callback callback
114 public function setPageOutCallback( $callback ) {
115 $previous = $this->mPageOutCallback
;
116 $this->mPageOutCallback
= $callback;
121 * Sets the action to perform as each page revision is reached.
122 * @param $callback callback
125 public function setRevisionCallback( $callback ) {
126 $previous = $this->mRevisionCallback
;
127 $this->mRevisionCallback
= $callback;
132 * Sets the action to perform as each file upload version is reached.
133 * @param $callback callback
136 public function setUploadCallback( $callback ) {
137 $previous = $this->mUploadCallback
;
138 $this->mUploadCallback
= $callback;
143 * Sets the action to perform as each log item reached.
144 * @param $callback callback
147 public function setLogItemCallback( $callback ) {
148 $previous = $this->mLogItemCallback
;
149 $this->mLogItemCallback
= $callback;
154 * Sets the action to perform when site info is encountered
155 * @param $callback callback
158 public function setSiteInfoCallback( $callback ) {
159 $previous = $this->mSiteInfoCallback
;
160 $this->mSiteInfoCallback
= $callback;
165 * Set a target namespace to override the defaults
167 public function setTargetNamespace( $namespace ) {
168 if( is_null( $namespace ) ) {
169 // Don't override namespaces
170 $this->mTargetNamespace
= null;
171 } elseif( $namespace >= 0 ) {
172 // @todo FIXME: Check for validity
173 $this->mTargetNamespace
= intval( $namespace );
182 public function setImageBasePath( $dir ) {
183 $this->mImageBasePath
= $dir;
185 public function setImportUploads( $import ) {
186 $this->mImportUploads
= $import;
190 * Default per-revision callback, performs the import.
191 * @param $revision WikiRevision
193 public function importRevision( $revision ) {
194 $dbw = wfGetDB( DB_MASTER
);
195 return $dbw->deadlockLoop( array( $revision, 'importOldRevision' ) );
199 * Default per-revision callback, performs the import.
200 * @param $rev WikiRevision
202 public function importLogItem( $rev ) {
203 $dbw = wfGetDB( DB_MASTER
);
204 return $dbw->deadlockLoop( array( $rev, 'importLogItem' ) );
210 public function importUpload( $revision ) {
211 $dbw = wfGetDB( DB_MASTER
);
212 return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
216 * Mostly for hook use
218 public function finishImportPage( $title, $origTitle, $revCount, $sRevCount, $pageInfo ) {
219 $args = func_get_args();
220 return wfRunHooks( 'AfterImportPage', $args );
224 * Alternate per-revision callback, for debugging.
225 * @param $revision WikiRevision
227 public function debugRevisionHandler( &$revision ) {
228 $this->debug( "Got revision:" );
229 if( is_object( $revision->title
) ) {
230 $this->debug( "-- Title: " . $revision->title
->getPrefixedText() );
232 $this->debug( "-- Title: <invalid>" );
234 $this->debug( "-- User: " . $revision->user_text
);
235 $this->debug( "-- Timestamp: " . $revision->timestamp
);
236 $this->debug( "-- Comment: " . $revision->comment
);
237 $this->debug( "-- Text: " . $revision->text
);
241 * Notify the callback function when a new <page> is reached.
242 * @param $title Title
244 function pageCallback( $title ) {
245 if( isset( $this->mPageCallback
) ) {
246 call_user_func( $this->mPageCallback
, $title );
251 * Notify the callback function when a </page> is closed.
252 * @param $title Title
253 * @param $origTitle Title
254 * @param $revCount Integer
255 * @param $sucCount Int: number of revisions for which callback returned true
256 * @param $pageInfo Array: associative array of page information
258 private function pageOutCallback( $title, $origTitle, $revCount, $sucCount, $pageInfo ) {
259 if( isset( $this->mPageOutCallback
) ) {
260 $args = func_get_args();
261 call_user_func_array( $this->mPageOutCallback
, $args );
266 * Notify the callback function of a revision
267 * @param $revision A WikiRevision object
269 private function revisionCallback( $revision ) {
270 if ( isset( $this->mRevisionCallback
) ) {
271 return call_user_func_array( $this->mRevisionCallback
,
272 array( $revision, $this ) );
279 * Notify the callback function of a new log item
280 * @param $revision A WikiRevision object
282 private function logItemCallback( $revision ) {
283 if ( isset( $this->mLogItemCallback
) ) {
284 return call_user_func_array( $this->mLogItemCallback
,
285 array( $revision, $this ) );
292 * Shouldn't something like this be built-in to XMLReader?
293 * Fetches text contents of the current element, assuming
294 * no sub-elements or such scary things.
298 private function nodeContents() {
299 if( $this->reader
->isEmptyElement
) {
303 while( $this->reader
->read() ) {
304 switch( $this->reader
->nodeType
) {
305 case XmlReader
::TEXT
:
306 case XmlReader
::SIGNIFICANT_WHITESPACE
:
307 $buffer .= $this->reader
->value
;
309 case XmlReader
::END_ELEMENT
:
314 $this->reader
->close();
320 /** Left in for debugging */
321 private function dumpElement() {
322 static $lookup = null;
324 $xmlReaderConstants = array(
339 "SIGNIFICANT_WHITESPACE",
346 foreach( $xmlReaderConstants as $name ) {
347 $lookup[constant("XmlReader::$name")] = $name;
352 $lookup[$this->reader
->nodeType
],
359 * Primary entry point
361 public function doImport() {
362 $this->reader
->read();
364 if ( $this->reader
->name
!= 'mediawiki' ) {
365 throw new MWException( "Expected <mediawiki> tag, got ".
366 $this->reader
->name
);
368 $this->debug( "<mediawiki> tag is correct." );
370 $this->debug( "Starting primary dump processing loop." );
372 $keepReading = $this->reader
->read();
374 while ( $keepReading ) {
375 $tag = $this->reader
->name
;
376 $type = $this->reader
->nodeType
;
378 if ( !wfRunHooks( 'ImportHandleToplevelXMLTag', $this ) ) {
380 } elseif ( $tag == 'mediawiki' && $type == XmlReader
::END_ELEMENT
) {
382 } elseif ( $tag == 'siteinfo' ) {
383 $this->handleSiteInfo();
384 } elseif ( $tag == 'page' ) {
386 } elseif ( $tag == 'logitem' ) {
387 $this->handleLogItem();
388 } elseif ( $tag != '#text' ) {
389 $this->warn( "Unhandled top-level XML tag $tag" );
395 $keepReading = $this->reader
->next();
397 $this->debug( "Skip" );
399 $keepReading = $this->reader
->read();
406 private function handleSiteInfo() {
407 // Site info is useful, but not actually used for dump imports.
408 // Includes a quick short-circuit to save performance.
409 if ( ! $this->mSiteInfoCallback
) {
410 $this->reader
->next();
413 throw new MWException( "SiteInfo tag is not yet handled, do not set mSiteInfoCallback" );
416 private function handleLogItem() {
417 $this->debug( "Enter log item handler." );
420 // Fields that can just be stuffed in the pageInfo object
421 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
422 'logtitle', 'params' );
424 while ( $this->reader
->read() ) {
425 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
426 $this->reader
->name
== 'logitem') {
430 $tag = $this->reader
->name
;
432 if ( !wfRunHooks( 'ImportHandleLogItemXMLTag',
433 $this, $logInfo ) ) {
435 } elseif ( in_array( $tag, $normalFields ) ) {
436 $logInfo[$tag] = $this->nodeContents();
437 } elseif ( $tag == 'contributor' ) {
438 $logInfo['contributor'] = $this->handleContributor();
439 } elseif ( $tag != '#text' ) {
440 $this->warn( "Unhandled log-item XML tag $tag" );
444 $this->processLogItem( $logInfo );
447 private function processLogItem( $logInfo ) {
448 $revision = new WikiRevision
;
450 $revision->setID( $logInfo['id'] );
451 $revision->setType( $logInfo['type'] );
452 $revision->setAction( $logInfo['action'] );
453 $revision->setTimestamp( $logInfo['timestamp'] );
454 $revision->setParams( $logInfo['params'] );
455 $revision->setTitle( Title
::newFromText( $logInfo['logtitle'] ) );
457 if ( isset( $logInfo['comment'] ) ) {
458 $revision->setComment( $logInfo['comment'] );
461 if ( isset( $logInfo['contributor']['ip'] ) ) {
462 $revision->setUserIP( $logInfo['contributor']['ip'] );
464 if ( isset( $logInfo['contributor']['username'] ) ) {
465 $revision->setUserName( $logInfo['contributor']['username'] );
468 return $this->logItemCallback( $revision );
471 private function handlePage() {
473 $this->debug( "Enter page handler." );
474 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
476 // Fields that can just be stuffed in the pageInfo object
477 $normalFields = array( 'title', 'id', 'redirect', 'restrictions' );
482 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
483 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
484 $this->reader
->name
== 'page') {
488 $tag = $this->reader
->name
;
491 // The title is invalid, bail out of this page
493 } elseif ( !wfRunHooks( 'ImportHandlePageXMLTag', array( $this,
496 } elseif ( in_array( $tag, $normalFields ) ) {
497 $pageInfo[$tag] = $this->nodeContents();
498 if ( $tag == 'title' ) {
499 $title = $this->processTitle( $pageInfo['title'] );
506 $this->pageCallback( $title );
507 list( $pageInfo['_title'], $origTitle ) = $title;
509 } elseif ( $tag == 'revision' ) {
510 $this->handleRevision( $pageInfo );
511 } elseif ( $tag == 'upload' ) {
512 $this->handleUpload( $pageInfo );
513 } elseif ( $tag != '#text' ) {
514 $this->warn( "Unhandled page XML tag $tag" );
519 $this->pageOutCallback( $pageInfo['_title'], $origTitle,
520 $pageInfo['revisionCount'],
521 $pageInfo['successfulRevisionCount'],
525 private function handleRevision( &$pageInfo ) {
526 $this->debug( "Enter revision handler" );
527 $revisionInfo = array();
529 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'text' );
533 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
534 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
535 $this->reader
->name
== 'revision') {
539 $tag = $this->reader
->name
;
541 if ( !wfRunHooks( 'ImportHandleRevisionXMLTag', $this,
542 $pageInfo, $revisionInfo ) ) {
544 } elseif ( in_array( $tag, $normalFields ) ) {
545 $revisionInfo[$tag] = $this->nodeContents();
546 } elseif ( $tag == 'contributor' ) {
547 $revisionInfo['contributor'] = $this->handleContributor();
548 } elseif ( $tag != '#text' ) {
549 $this->warn( "Unhandled revision XML tag $tag" );
554 $pageInfo['revisionCount']++
;
555 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
556 $pageInfo['successfulRevisionCount']++
;
560 private function processRevision( $pageInfo, $revisionInfo ) {
561 $revision = new WikiRevision
;
563 if( isset( $revisionInfo['id'] ) ) {
564 $revision->setID( $revisionInfo['id'] );
566 if ( isset( $revisionInfo['text'] ) ) {
567 $revision->setText( $revisionInfo['text'] );
569 $revision->setTitle( $pageInfo['_title'] );
571 if ( isset( $revisionInfo['timestamp'] ) ) {
572 $revision->setTimestamp( $revisionInfo['timestamp'] );
574 $revision->setTimestamp( wfTimestampNow() );
577 if ( isset( $revisionInfo['comment'] ) ) {
578 $revision->setComment( $revisionInfo['comment'] );
581 if ( isset( $revisionInfo['minor'] ) ) {
582 $revision->setMinor( true );
584 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
585 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
587 if ( isset( $revisionInfo['contributor']['username'] ) ) {
588 $revision->setUserName( $revisionInfo['contributor']['username'] );
591 return $this->revisionCallback( $revision );
594 private function handleUpload( &$pageInfo ) {
595 $this->debug( "Enter upload handler" );
596 $uploadInfo = array();
598 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
599 'src', 'size', 'sha1base36', 'archivename', 'rel' );
603 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
604 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
605 $this->reader
->name
== 'upload') {
609 $tag = $this->reader
->name
;
611 if ( !wfRunHooks( 'ImportHandleUploadXMLTag', $this,
614 } elseif ( in_array( $tag, $normalFields ) ) {
615 $uploadInfo[$tag] = $this->nodeContents();
616 } elseif ( $tag == 'contributor' ) {
617 $uploadInfo['contributor'] = $this->handleContributor();
618 } elseif ( $tag == 'contents' ) {
619 $contents = $this->nodeContents();
620 $encoding = $this->reader
->getAttribute( 'encoding' );
621 if ( $encoding === 'base64' ) {
622 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
623 $uploadInfo['isTempSrc'] = true;
625 } elseif ( $tag != '#text' ) {
626 $this->warn( "Unhandled upload XML tag $tag" );
631 if ( $this->mImageBasePath
&& isset( $uploadInfo['rel'] ) ) {
632 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
633 if ( file_exists( $path ) ) {
634 $uploadInfo['fileSrc'] = $path;
635 $uploadInfo['isTempSrc'] = false;
639 if ( $this->mImportUploads
) {
640 return $this->processUpload( $pageInfo, $uploadInfo );
644 private function dumpTemp( $contents ) {
645 $filename = tempnam( wfTempDir(), 'importupload' );
646 file_put_contents( $filename, $contents );
651 private function processUpload( $pageInfo, $uploadInfo ) {
652 $revision = new WikiRevision
;
653 $text = isset( $uploadInfo['text'] ) ?
$uploadInfo['text'] : '';
655 $revision->setTitle( $pageInfo['_title'] );
656 $revision->setID( $pageInfo['id'] );
657 $revision->setTimestamp( $uploadInfo['timestamp'] );
658 $revision->setText( $text );
659 $revision->setFilename( $uploadInfo['filename'] );
660 if ( isset( $uploadInfo['archivename'] ) ) {
661 $revision->setArchiveName( $uploadInfo['archivename'] );
663 $revision->setSrc( $uploadInfo['src'] );
664 if ( isset( $uploadInfo['fileSrc'] ) ) {
665 $revision->setFileSrc( $uploadInfo['fileSrc'],
666 !empty( $uploadInfo['isTempSrc'] ) );
668 if ( isset( $uploadInfo['sha1base36'] ) ) {
669 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
671 $revision->setSize( intval( $uploadInfo['size'] ) );
672 $revision->setComment( $uploadInfo['comment'] );
674 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
675 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
677 if ( isset( $uploadInfo['contributor']['username'] ) ) {
678 $revision->setUserName( $uploadInfo['contributor']['username'] );
681 return call_user_func( $this->mUploadCallback
, $revision );
684 private function handleContributor() {
685 $fields = array( 'id', 'ip', 'username' );
688 while ( $this->reader
->read() ) {
689 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
690 $this->reader
->name
== 'contributor') {
694 $tag = $this->reader
->name
;
696 if ( in_array( $tag, $fields ) ) {
697 $info[$tag] = $this->nodeContents();
704 private function processTitle( $text ) {
706 $origTitle = Title
::newFromText( $workTitle );
708 if( !is_null( $this->mTargetNamespace
) && !is_null( $origTitle ) ) {
709 $title = Title
::makeTitle( $this->mTargetNamespace
,
710 $origTitle->getDBkey() );
712 $title = Title
::newFromText( $workTitle );
715 if( is_null( $title ) ) {
716 // Invalid page title? Ignore the page
717 $this->notice( "Skipping invalid page title '$workTitle'" );
719 } elseif( $title->getInterwiki() != '' ) {
720 $this->notice( "Skipping interwiki page title '$workTitle'" );
724 return array( $title, $origTitle );
728 /** This is a horrible hack used to keep source compatibility */
729 class UploadSourceAdapter
{
730 static $sourceRegistrations = array();
736 static function registerSource( $source ) {
737 $id = wfGenerateToken();
739 self
::$sourceRegistrations[$id] = $source;
744 function stream_open( $path, $mode, $options, &$opened_path ) {
745 $url = parse_url($path);
748 if ( !isset( self
::$sourceRegistrations[$id] ) ) {
752 $this->mSource
= self
::$sourceRegistrations[$id];
757 function stream_read( $count ) {
761 while ( !$leave && !$this->mSource
->atEnd() &&
762 strlen($this->mBuffer
) < $count ) {
763 $read = $this->mSource
->readChunk();
765 if ( !strlen($read) ) {
769 $this->mBuffer
.= $read;
772 if ( strlen($this->mBuffer
) ) {
773 $return = substr( $this->mBuffer
, 0, $count );
774 $this->mBuffer
= substr( $this->mBuffer
, $count );
777 $this->mPosition +
= strlen($return);
782 function stream_write( $data ) {
786 function stream_tell() {
787 return $this->mPosition
;
790 function stream_eof() {
791 return $this->mSource
->atEnd();
794 function url_stat() {
797 $result['dev'] = $result[0] = 0;
798 $result['ino'] = $result[1] = 0;
799 $result['mode'] = $result[2] = 0;
800 $result['nlink'] = $result[3] = 0;
801 $result['uid'] = $result[4] = 0;
802 $result['gid'] = $result[5] = 0;
803 $result['rdev'] = $result[6] = 0;
804 $result['size'] = $result[7] = 0;
805 $result['atime'] = $result[8] = 0;
806 $result['mtime'] = $result[9] = 0;
807 $result['ctime'] = $result[10] = 0;
808 $result['blksize'] = $result[11] = 0;
809 $result['blocks'] = $result[12] = 0;
815 class XMLReader2
extends XMLReader
{
816 function nodeContents() {
817 if( $this->isEmptyElement
) {
821 while( $this->read() ) {
822 switch( $this->nodeType
) {
823 case XmlReader
::TEXT
:
824 case XmlReader
::SIGNIFICANT_WHITESPACE
:
825 $buffer .= $this->value
;
827 case XmlReader
::END_ELEMENT
:
831 return $this->close();
836 * @todo document (e.g. one-sentence class description).
837 * @ingroup SpecialPage
840 var $importer = null;
843 var $timestamp = "20010115000000";
853 var $sha1base36 = false;
855 var $archiveName = '';
857 function setTitle( $title ) {
858 if( is_object( $title ) ) {
859 $this->title
= $title;
860 } elseif( is_null( $title ) ) {
861 throw new MWException( "WikiRevision given a null title in import. You may need to adjust \$wgLegalTitleChars." );
863 throw new MWException( "WikiRevision given non-object title in import." );
867 function setID( $id ) {
871 function setTimestamp( $ts ) {
872 # 2003-08-05T18:30:02Z
873 $this->timestamp
= wfTimestamp( TS_MW
, $ts );
876 function setUsername( $user ) {
877 $this->user_text
= $user;
880 function setUserIP( $ip ) {
881 $this->user_text
= $ip;
884 function setText( $text ) {
888 function setComment( $text ) {
889 $this->comment
= $text;
892 function setMinor( $minor ) {
893 $this->minor
= (bool)$minor;
896 function setSrc( $src ) {
899 function setFileSrc( $src, $isTemp ) {
900 $this->fileSrc
= $src;
901 $this->fileIsTemp
= $isTemp;
903 function setSha1Base36( $sha1base36 ) {
904 $this->sha1base36
= $sha1base36;
907 function setFilename( $filename ) {
908 $this->filename
= $filename;
910 function setArchiveName( $archiveName ) {
911 $this->archiveName
= $archiveName;
914 function setSize( $size ) {
915 $this->size
= intval( $size );
918 function setType( $type ) {
922 function setAction( $action ) {
923 $this->action
= $action;
926 function setParams( $params ) {
927 $this->params
= $params;
933 function getTitle() {
941 function getTimestamp() {
942 return $this->timestamp
;
946 return $this->user_text
;
953 function getComment() {
954 return $this->comment
;
957 function getMinor() {
965 if ( $this->sha1base36
) {
966 return wfBaseConvert( $this->sha1base36
, 36, 16 );
970 function getFileSrc() {
971 return $this->fileSrc
;
973 function isTempSrc() {
974 return $this->isTemp
;
977 function getFilename() {
978 return $this->filename
;
980 function getArchiveName() {
981 return $this->archiveName
;
992 function getAction() {
993 return $this->action
;
996 function getParams() {
997 return $this->params
;
1000 function importOldRevision() {
1001 $dbw = wfGetDB( DB_MASTER
);
1003 # Sneak a single revision into place
1004 $user = User
::newFromName( $this->getUser() );
1006 $userId = intval( $user->getId() );
1007 $userText = $user->getName();
1011 $userText = $this->getUser();
1012 $userObj = new User
;
1015 // avoid memory leak...?
1016 $linkCache = LinkCache
::singleton();
1017 $linkCache->clear();
1019 $article = new Article( $this->title
);
1020 $pageId = $article->getId();
1021 if( $pageId == 0 ) {
1022 # must create the page...
1023 $pageId = $article->insertOn( $dbw );
1025 $oldcountable = null;
1029 $prior = $dbw->selectField( 'revision', '1',
1030 array( 'rev_page' => $pageId,
1031 'rev_timestamp' => $dbw->timestamp( $this->timestamp
),
1032 'rev_user_text' => $userText,
1033 'rev_comment' => $this->getComment() ),
1037 // @todo FIXME: This could fail slightly for multiple matches :P
1038 wfDebug( __METHOD__
. ": skipping existing revision for [[" .
1039 $this->title
->getPrefixedText() . "]], timestamp " . $this->timestamp
. "\n" );
1042 $oldcountable = $article->isCountable();
1045 # @todo FIXME: Use original rev_id optionally (better for backups)
1047 $revision = new Revision( array(
1049 'text' => $this->getText(),
1050 'comment' => $this->getComment(),
1052 'user_text' => $userText,
1053 'timestamp' => $this->timestamp
,
1054 'minor_edit' => $this->minor
,
1056 $revision->insertOn( $dbw );
1057 $changed = $article->updateIfNewerOn( $dbw, $revision );
1059 if ( $changed !== false ) {
1060 wfDebug( __METHOD__
. ": running updates\n" );
1061 $article->doEditUpdates( $revision, $userObj, array( 'created' => $created, 'oldcountable' => $oldcountable ) );
1067 function importLogItem() {
1068 $dbw = wfGetDB( DB_MASTER
);
1069 # @todo FIXME: This will not record autoblocks
1070 if( !$this->getTitle() ) {
1071 wfDebug( __METHOD__
. ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1072 $this->timestamp
. "\n" );
1075 # Check if it exists already
1076 // @todo FIXME: Use original log ID (better for backups)
1077 $prior = $dbw->selectField( 'logging', '1',
1078 array( 'log_type' => $this->getType(),
1079 'log_action' => $this->getAction(),
1080 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1081 'log_namespace' => $this->getTitle()->getNamespace(),
1082 'log_title' => $this->getTitle()->getDBkey(),
1083 'log_comment' => $this->getComment(),
1084 #'log_user_text' => $this->user_text,
1085 'log_params' => $this->params
),
1088 // @todo FIXME: This could fail slightly for multiple matches :P
1090 wfDebug( __METHOD__
. ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp " .
1091 $this->timestamp
. "\n" );
1094 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1096 'log_id' => $log_id,
1097 'log_type' => $this->type
,
1098 'log_action' => $this->action
,
1099 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1100 'log_user' => User
::idFromName( $this->user_text
),
1101 #'log_user_text' => $this->user_text,
1102 'log_namespace' => $this->getTitle()->getNamespace(),
1103 'log_title' => $this->getTitle()->getDBkey(),
1104 'log_comment' => $this->getComment(),
1105 'log_params' => $this->params
1107 $dbw->insert( 'logging', $data, __METHOD__
);
1110 function importUpload() {
1112 $archiveName = $this->getArchiveName();
1113 if ( $archiveName ) {
1114 wfDebug( __METHOD__
. "Importing archived file as $archiveName\n" );
1115 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1116 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1118 $file = wfLocalFile( $this->getTitle() );
1119 wfDebug( __METHOD__
. 'Importing new file as ' . $file->getName() . "\n" );
1120 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1121 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1122 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1123 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1124 wfDebug( __METHOD__
. "File already exists; importing as $archiveName\n" );
1128 wfDebug( __METHOD__
. ': Bad file for ' . $this->getTitle() . "\n" );
1132 # Get the file source or download if necessary
1133 $source = $this->getFileSrc();
1134 $flags = $this->isTempSrc() ? File
::DELETE_SOURCE
: 0;
1136 $source = $this->downloadSource();
1137 $flags |
= File
::DELETE_SOURCE
;
1140 wfDebug( __METHOD__
. ": Could not fetch remote file.\n" );
1143 $sha1 = $this->getSha1();
1144 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1145 if ( $flags & File
::DELETE_SOURCE
) {
1146 # Broken file; delete it if it is a temporary file
1149 wfDebug( __METHOD__
. ": Corrupt file $source.\n" );
1153 $user = User
::newFromName( $this->user_text
);
1155 # Do the actual upload
1156 if ( $archiveName ) {
1157 $status = $file->uploadOld( $source, $archiveName,
1158 $this->getTimestamp(), $this->getComment(), $user, $flags );
1160 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1161 $flags, false, $this->getTimestamp(), $user );
1164 if ( $status->isGood() ) {
1165 wfDebug( __METHOD__
. ": Succesful\n" );
1168 wfDebug( __METHOD__
. ': failed: ' . $status->getXml() . "\n" );
1173 function downloadSource() {
1174 global $wgEnableUploads;
1175 if( !$wgEnableUploads ) {
1179 $tempo = tempnam( wfTempDir(), 'download' );
1180 $f = fopen( $tempo, 'wb' );
1182 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1187 $src = $this->getSrc();
1188 $data = Http
::get( $src );
1190 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1196 fwrite( $f, $data );
1205 * @todo document (e.g. one-sentence class description).
1206 * @ingroup SpecialPage
1208 class ImportStringSource
{
1209 function __construct( $string ) {
1210 $this->mString
= $string;
1211 $this->mRead
= false;
1215 return $this->mRead
;
1218 function readChunk() {
1219 if( $this->atEnd() ) {
1222 $this->mRead
= true;
1223 return $this->mString
;
1229 * @todo document (e.g. one-sentence class description).
1230 * @ingroup SpecialPage
1232 class ImportStreamSource
{
1233 function __construct( $handle ) {
1234 $this->mHandle
= $handle;
1238 return feof( $this->mHandle
);
1241 function readChunk() {
1242 return fread( $this->mHandle
, 32768 );
1245 static function newFromFile( $filename ) {
1246 wfSuppressWarnings();
1247 $file = fopen( $filename, 'rt' );
1248 wfRestoreWarnings();
1250 return Status
::newFatal( "importcantopen" );
1252 return Status
::newGood( new ImportStreamSource( $file ) );
1255 static function newFromUpload( $fieldname = "xmlimport" ) {
1256 $upload =& $_FILES[$fieldname];
1258 if( !isset( $upload ) ||
!$upload['name'] ) {
1259 return Status
::newFatal( 'importnofile' );
1261 if( !empty( $upload['error'] ) ) {
1262 switch($upload['error']){
1263 case 1: # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1264 return Status
::newFatal( 'importuploaderrorsize' );
1265 case 2: # The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
1266 return Status
::newFatal( 'importuploaderrorsize' );
1267 case 3: # The uploaded file was only partially uploaded
1268 return Status
::newFatal( 'importuploaderrorpartial' );
1269 case 6: #Missing a temporary folder.
1270 return Status
::newFatal( 'importuploaderrortemp' );
1271 # case else: # Currently impossible
1275 $fname = $upload['tmp_name'];
1276 if( is_uploaded_file( $fname ) ) {
1277 return ImportStreamSource
::newFromFile( $fname );
1279 return Status
::newFatal( 'importnofile' );
1283 static function newFromURL( $url, $method = 'GET' ) {
1284 wfDebug( __METHOD__
. ": opening $url\n" );
1285 # Use the standard HTTP fetch function; it times out
1286 # quicker and sorts out user-agent problems which might
1287 # otherwise prevent importing from large sites, such
1288 # as the Wikimedia cluster, etc.
1289 $data = Http
::request( $method, $url );
1290 if( $data !== false ) {
1292 fwrite( $file, $data );
1295 return Status
::newGood( new ImportStreamSource( $file ) );
1297 return Status
::newFatal( 'importcantopen' );
1301 public static function newFromInterwiki( $interwiki, $page, $history = false, $templates = false, $pageLinkDepth = 0 ) {
1303 return Status
::newFatal( 'import-noarticle' );
1305 $link = Title
::newFromText( "$interwiki:Special:Export/$page" );
1306 if( is_null( $link ) ||
$link->getInterwiki() == '' ) {
1307 return Status
::newFatal( 'importbadinterwiki' );
1310 if ( $history ) $params['history'] = 1;
1311 if ( $templates ) $params['templates'] = 1;
1312 if ( $pageLinkDepth ) $params['pagelink-depth'] = $pageLinkDepth;
1313 $url = $link->getFullUrl( $params );
1314 # For interwikis, use POST to avoid redirects.
1315 return ImportStreamSource
::newFromURL( $url, "POST" );