Add a way for packagers to override some installation details
[mediawiki.git] / includes / Import.php
blob9ebc34c91b941ac7e349ef9f2c13a1ea32ba6aa6
1 <?php
2 /**
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
23 * @file
24 * @ingroup SpecialPage
27 /**
28 * XML file reader for the page data importer
30 * implements Special:Import
31 * @ingroup SpecialPage
33 class WikiImporter {
34 private $reader = null;
35 private $mLogItemCallback, $mUploadCallback, $mRevisionCallback, $mPageCallback;
36 private $mSiteInfoCallback, $mTargetNamespace, $mPageOutCallback;
37 private $mNoticeCallback, $mDebug;
38 private $mImportUploads, $mImageBasePath;
39 private $mNoUpdates = false;
41 /**
42 * Creates an ImportXMLReader drawing from the source provided
43 * @param $source
45 function __construct( $source ) {
46 $this->reader = new XMLReader();
48 stream_wrapper_register( 'uploadsource', 'UploadSourceAdapter' );
49 $id = UploadSourceAdapter::registerSource( $source );
50 if (defined( 'LIBXML_PARSEHUGE' ) ) {
51 $this->reader->open( "uploadsource://$id", null, LIBXML_PARSEHUGE );
52 } else {
53 $this->reader->open( "uploadsource://$id" );
56 // Default callbacks
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 ) {
69 if( $this->mDebug ) {
70 wfDebug( "IMPORT: $data\n" );
74 private function warn( $data ) {
75 wfDebug( "IMPORT: $data\n" );
78 private function notice( $msg /*, $param, ...*/ ) {
79 $params = func_get_args();
80 array_shift( $params );
82 if ( is_callable( $this->mNoticeCallback ) ) {
83 call_user_func( $this->mNoticeCallback, $msg, $params );
84 } else { # No ImportReporter -> CLI
85 echo wfMessage( $msg, $params )->text() . "\n";
89 /**
90 * Set debug mode...
91 * @param $debug bool
93 function setDebug( $debug ) {
94 $this->mDebug = $debug;
97 /**
98 * Set 'no updates' mode. In this mode, the link tables will not be updated by the importer
99 * @param $noupdates bool
101 function setNoUpdates( $noupdates ) {
102 $this->mNoUpdates = $noupdates;
106 * Set a callback that displays notice messages
108 * @param $callback callback
109 * @return callback
111 public function setNoticeCallback( $callback ) {
112 return wfSetVar( $this->mNoticeCallback, $callback );
116 * Sets the action to perform as each new page in the stream is reached.
117 * @param $callback callback
118 * @return callback
120 public function setPageCallback( $callback ) {
121 $previous = $this->mPageCallback;
122 $this->mPageCallback = $callback;
123 return $previous;
127 * Sets the action to perform as each page in the stream is completed.
128 * Callback accepts the page title (as a Title object), a second object
129 * with the original title form (in case it's been overridden into a
130 * local namespace), and a count of revisions.
132 * @param $callback callback
133 * @return callback
135 public function setPageOutCallback( $callback ) {
136 $previous = $this->mPageOutCallback;
137 $this->mPageOutCallback = $callback;
138 return $previous;
142 * Sets the action to perform as each page revision is reached.
143 * @param $callback callback
144 * @return callback
146 public function setRevisionCallback( $callback ) {
147 $previous = $this->mRevisionCallback;
148 $this->mRevisionCallback = $callback;
149 return $previous;
153 * Sets the action to perform as each file upload version is reached.
154 * @param $callback callback
155 * @return callback
157 public function setUploadCallback( $callback ) {
158 $previous = $this->mUploadCallback;
159 $this->mUploadCallback = $callback;
160 return $previous;
164 * Sets the action to perform as each log item reached.
165 * @param $callback callback
166 * @return callback
168 public function setLogItemCallback( $callback ) {
169 $previous = $this->mLogItemCallback;
170 $this->mLogItemCallback = $callback;
171 return $previous;
175 * Sets the action to perform when site info is encountered
176 * @param $callback callback
177 * @return callback
179 public function setSiteInfoCallback( $callback ) {
180 $previous = $this->mSiteInfoCallback;
181 $this->mSiteInfoCallback = $callback;
182 return $previous;
186 * Set a target namespace to override the defaults
187 * @param $namespace
188 * @return bool
190 public function setTargetNamespace( $namespace ) {
191 if( is_null( $namespace ) ) {
192 // Don't override namespaces
193 $this->mTargetNamespace = null;
194 } elseif( $namespace >= 0 ) {
195 // @todo FIXME: Check for validity
196 $this->mTargetNamespace = intval( $namespace );
197 } else {
198 return false;
203 * @param $dir
205 public function setImageBasePath( $dir ) {
206 $this->mImageBasePath = $dir;
210 * @param $import
212 public function setImportUploads( $import ) {
213 $this->mImportUploads = $import;
217 * Default per-revision callback, performs the import.
218 * @param $revision WikiRevision
219 * @return bool
221 public function importRevision( $revision ) {
222 $dbw = wfGetDB( DB_MASTER );
223 return $dbw->deadlockLoop( array( $revision, 'importOldRevision' ) );
227 * Default per-revision callback, performs the import.
228 * @param $rev WikiRevision
229 * @return bool
231 public function importLogItem( $rev ) {
232 $dbw = wfGetDB( DB_MASTER );
233 return $dbw->deadlockLoop( array( $rev, 'importLogItem' ) );
237 * Dummy for now...
238 * @param $revision
239 * @return bool
241 public function importUpload( $revision ) {
242 $dbw = wfGetDB( DB_MASTER );
243 return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
247 * Mostly for hook use
248 * @param $title
249 * @param $origTitle
250 * @param $revCount
251 * @param $sRevCount
252 * @param $pageInfo
253 * @return
255 public function finishImportPage( $title, $origTitle, $revCount, $sRevCount, $pageInfo ) {
256 $args = func_get_args();
257 return wfRunHooks( 'AfterImportPage', $args );
261 * Alternate per-revision callback, for debugging.
262 * @param $revision WikiRevision
264 public function debugRevisionHandler( &$revision ) {
265 $this->debug( "Got revision:" );
266 if( is_object( $revision->title ) ) {
267 $this->debug( "-- Title: " . $revision->title->getPrefixedText() );
268 } else {
269 $this->debug( "-- Title: <invalid>" );
271 $this->debug( "-- User: " . $revision->user_text );
272 $this->debug( "-- Timestamp: " . $revision->timestamp );
273 $this->debug( "-- Comment: " . $revision->comment );
274 $this->debug( "-- Text: " . $revision->text );
278 * Notify the callback function when a new <page> is reached.
279 * @param $title Title
281 function pageCallback( $title ) {
282 if( isset( $this->mPageCallback ) ) {
283 call_user_func( $this->mPageCallback, $title );
288 * Notify the callback function when a </page> is closed.
289 * @param $title Title
290 * @param $origTitle Title
291 * @param $revCount Integer
292 * @param $sucCount Int: number of revisions for which callback returned true
293 * @param $pageInfo Array: associative array of page information
295 private function pageOutCallback( $title, $origTitle, $revCount, $sucCount, $pageInfo ) {
296 if( isset( $this->mPageOutCallback ) ) {
297 $args = func_get_args();
298 call_user_func_array( $this->mPageOutCallback, $args );
303 * Notify the callback function of a revision
304 * @param $revision WikiRevision object
305 * @return bool|mixed
307 private function revisionCallback( $revision ) {
308 if ( isset( $this->mRevisionCallback ) ) {
309 return call_user_func_array( $this->mRevisionCallback,
310 array( $revision, $this ) );
311 } else {
312 return false;
317 * Notify the callback function of a new log item
318 * @param $revision WikiRevision object
319 * @return bool|mixed
321 private function logItemCallback( $revision ) {
322 if ( isset( $this->mLogItemCallback ) ) {
323 return call_user_func_array( $this->mLogItemCallback,
324 array( $revision, $this ) );
325 } else {
326 return false;
331 * Shouldn't something like this be built-in to XMLReader?
332 * Fetches text contents of the current element, assuming
333 * no sub-elements or such scary things.
334 * @return string
335 * @access private
337 private function nodeContents() {
338 if( $this->reader->isEmptyElement ) {
339 return "";
341 $buffer = "";
342 while( $this->reader->read() ) {
343 switch( $this->reader->nodeType ) {
344 case XmlReader::TEXT:
345 case XmlReader::SIGNIFICANT_WHITESPACE:
346 $buffer .= $this->reader->value;
347 break;
348 case XmlReader::END_ELEMENT:
349 return $buffer;
353 $this->reader->close();
354 return '';
357 # --------------
359 /** Left in for debugging */
360 private function dumpElement() {
361 static $lookup = null;
362 if (!$lookup) {
363 $xmlReaderConstants = array(
364 "NONE",
365 "ELEMENT",
366 "ATTRIBUTE",
367 "TEXT",
368 "CDATA",
369 "ENTITY_REF",
370 "ENTITY",
371 "PI",
372 "COMMENT",
373 "DOC",
374 "DOC_TYPE",
375 "DOC_FRAGMENT",
376 "NOTATION",
377 "WHITESPACE",
378 "SIGNIFICANT_WHITESPACE",
379 "END_ELEMENT",
380 "END_ENTITY",
381 "XML_DECLARATION",
383 $lookup = array();
385 foreach( $xmlReaderConstants as $name ) {
386 $lookup[constant("XmlReader::$name")] = $name;
390 print( var_dump(
391 $lookup[$this->reader->nodeType],
392 $this->reader->name,
393 $this->reader->value
394 )."\n\n" );
398 * Primary entry point
399 * @return bool
401 public function doImport() {
402 $this->reader->read();
404 if ( $this->reader->name != 'mediawiki' ) {
405 throw new MWException( "Expected <mediawiki> tag, got ".
406 $this->reader->name );
408 $this->debug( "<mediawiki> tag is correct." );
410 $this->debug( "Starting primary dump processing loop." );
412 $keepReading = $this->reader->read();
413 $skip = false;
414 while ( $keepReading ) {
415 $tag = $this->reader->name;
416 $type = $this->reader->nodeType;
418 if ( !wfRunHooks( 'ImportHandleToplevelXMLTag', $this ) ) {
419 // Do nothing
420 } elseif ( $tag == 'mediawiki' && $type == XmlReader::END_ELEMENT ) {
421 break;
422 } elseif ( $tag == 'siteinfo' ) {
423 $this->handleSiteInfo();
424 } elseif ( $tag == 'page' ) {
425 $this->handlePage();
426 } elseif ( $tag == 'logitem' ) {
427 $this->handleLogItem();
428 } elseif ( $tag != '#text' ) {
429 $this->warn( "Unhandled top-level XML tag $tag" );
431 $skip = true;
434 if ($skip) {
435 $keepReading = $this->reader->next();
436 $skip = false;
437 $this->debug( "Skip" );
438 } else {
439 $keepReading = $this->reader->read();
443 return true;
447 * @return bool
448 * @throws MWException
450 private function handleSiteInfo() {
451 // Site info is useful, but not actually used for dump imports.
452 // Includes a quick short-circuit to save performance.
453 if ( ! $this->mSiteInfoCallback ) {
454 $this->reader->next();
455 return true;
457 throw new MWException( "SiteInfo tag is not yet handled, do not set mSiteInfoCallback" );
460 private function handleLogItem() {
461 $this->debug( "Enter log item handler." );
462 $logInfo = array();
464 // Fields that can just be stuffed in the pageInfo object
465 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
466 'logtitle', 'params' );
468 while ( $this->reader->read() ) {
469 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
470 $this->reader->name == 'logitem') {
471 break;
474 $tag = $this->reader->name;
476 if ( !wfRunHooks( 'ImportHandleLogItemXMLTag',
477 $this, $logInfo ) ) {
478 // Do nothing
479 } elseif ( in_array( $tag, $normalFields ) ) {
480 $logInfo[$tag] = $this->nodeContents();
481 } elseif ( $tag == 'contributor' ) {
482 $logInfo['contributor'] = $this->handleContributor();
483 } elseif ( $tag != '#text' ) {
484 $this->warn( "Unhandled log-item XML tag $tag" );
488 $this->processLogItem( $logInfo );
492 * @param $logInfo
493 * @return bool|mixed
495 private function processLogItem( $logInfo ) {
496 $revision = new WikiRevision;
498 $revision->setID( $logInfo['id'] );
499 $revision->setType( $logInfo['type'] );
500 $revision->setAction( $logInfo['action'] );
501 $revision->setTimestamp( $logInfo['timestamp'] );
502 $revision->setParams( $logInfo['params'] );
503 $revision->setTitle( Title::newFromText( $logInfo['logtitle'] ) );
504 $revision->setNoUpdates( $this->mNoUpdates );
506 if ( isset( $logInfo['comment'] ) ) {
507 $revision->setComment( $logInfo['comment'] );
510 if ( isset( $logInfo['contributor']['ip'] ) ) {
511 $revision->setUserIP( $logInfo['contributor']['ip'] );
513 if ( isset( $logInfo['contributor']['username'] ) ) {
514 $revision->setUserName( $logInfo['contributor']['username'] );
517 return $this->logItemCallback( $revision );
520 private function handlePage() {
521 // Handle page data.
522 $this->debug( "Enter page handler." );
523 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
525 // Fields that can just be stuffed in the pageInfo object
526 $normalFields = array( 'title', 'id', 'redirect', 'restrictions' );
528 $skip = false;
529 $badTitle = false;
531 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
532 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
533 $this->reader->name == 'page') {
534 break;
537 $tag = $this->reader->name;
539 if ( $badTitle ) {
540 // The title is invalid, bail out of this page
541 $skip = true;
542 } elseif ( !wfRunHooks( 'ImportHandlePageXMLTag', array( $this,
543 &$pageInfo ) ) ) {
544 // Do nothing
545 } elseif ( in_array( $tag, $normalFields ) ) {
546 $pageInfo[$tag] = $this->nodeContents();
547 if ( $tag == 'title' ) {
548 $title = $this->processTitle( $pageInfo['title'] );
550 if ( !$title ) {
551 $badTitle = true;
552 $skip = true;
555 $this->pageCallback( $title );
556 list( $pageInfo['_title'], $origTitle ) = $title;
558 } elseif ( $tag == 'revision' ) {
559 $this->handleRevision( $pageInfo );
560 } elseif ( $tag == 'upload' ) {
561 $this->handleUpload( $pageInfo );
562 } elseif ( $tag != '#text' ) {
563 $this->warn( "Unhandled page XML tag $tag" );
564 $skip = true;
568 $this->pageOutCallback( $pageInfo['_title'], $origTitle,
569 $pageInfo['revisionCount'],
570 $pageInfo['successfulRevisionCount'],
571 $pageInfo );
575 * @param $pageInfo array
577 private function handleRevision( &$pageInfo ) {
578 $this->debug( "Enter revision handler" );
579 $revisionInfo = array();
581 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'text' );
583 $skip = false;
585 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
586 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
587 $this->reader->name == 'revision') {
588 break;
591 $tag = $this->reader->name;
593 if ( !wfRunHooks( 'ImportHandleRevisionXMLTag', $this,
594 $pageInfo, $revisionInfo ) ) {
595 // Do nothing
596 } elseif ( in_array( $tag, $normalFields ) ) {
597 $revisionInfo[$tag] = $this->nodeContents();
598 } elseif ( $tag == 'contributor' ) {
599 $revisionInfo['contributor'] = $this->handleContributor();
600 } elseif ( $tag != '#text' ) {
601 $this->warn( "Unhandled revision XML tag $tag" );
602 $skip = true;
606 $pageInfo['revisionCount']++;
607 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
608 $pageInfo['successfulRevisionCount']++;
613 * @param $pageInfo
614 * @param $revisionInfo
615 * @return bool|mixed
617 private function processRevision( $pageInfo, $revisionInfo ) {
618 $revision = new WikiRevision;
620 if( isset( $revisionInfo['id'] ) ) {
621 $revision->setID( $revisionInfo['id'] );
623 if ( isset( $revisionInfo['text'] ) ) {
624 $revision->setText( $revisionInfo['text'] );
626 $revision->setTitle( $pageInfo['_title'] );
628 if ( isset( $revisionInfo['timestamp'] ) ) {
629 $revision->setTimestamp( $revisionInfo['timestamp'] );
630 } else {
631 $revision->setTimestamp( wfTimestampNow() );
634 if ( isset( $revisionInfo['comment'] ) ) {
635 $revision->setComment( $revisionInfo['comment'] );
638 if ( isset( $revisionInfo['minor'] ) ) {
639 $revision->setMinor( true );
641 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
642 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
644 if ( isset( $revisionInfo['contributor']['username'] ) ) {
645 $revision->setUserName( $revisionInfo['contributor']['username'] );
647 $revision->setNoUpdates( $this->mNoUpdates );
649 return $this->revisionCallback( $revision );
653 * @param $pageInfo
654 * @return mixed
656 private function handleUpload( &$pageInfo ) {
657 $this->debug( "Enter upload handler" );
658 $uploadInfo = array();
660 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
661 'src', 'size', 'sha1base36', 'archivename', 'rel' );
663 $skip = false;
665 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
666 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
667 $this->reader->name == 'upload') {
668 break;
671 $tag = $this->reader->name;
673 if ( !wfRunHooks( 'ImportHandleUploadXMLTag', $this,
674 $pageInfo ) ) {
675 // Do nothing
676 } elseif ( in_array( $tag, $normalFields ) ) {
677 $uploadInfo[$tag] = $this->nodeContents();
678 } elseif ( $tag == 'contributor' ) {
679 $uploadInfo['contributor'] = $this->handleContributor();
680 } elseif ( $tag == 'contents' ) {
681 $contents = $this->nodeContents();
682 $encoding = $this->reader->getAttribute( 'encoding' );
683 if ( $encoding === 'base64' ) {
684 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
685 $uploadInfo['isTempSrc'] = true;
687 } elseif ( $tag != '#text' ) {
688 $this->warn( "Unhandled upload XML tag $tag" );
689 $skip = true;
693 if ( $this->mImageBasePath && isset( $uploadInfo['rel'] ) ) {
694 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
695 if ( file_exists( $path ) ) {
696 $uploadInfo['fileSrc'] = $path;
697 $uploadInfo['isTempSrc'] = false;
701 if ( $this->mImportUploads ) {
702 return $this->processUpload( $pageInfo, $uploadInfo );
707 * @param $contents
708 * @return string
710 private function dumpTemp( $contents ) {
711 $filename = tempnam( wfTempDir(), 'importupload' );
712 file_put_contents( $filename, $contents );
713 return $filename;
717 * @param $pageInfo
718 * @param $uploadInfo
719 * @return mixed
721 private function processUpload( $pageInfo, $uploadInfo ) {
722 $revision = new WikiRevision;
723 $text = isset( $uploadInfo['text'] ) ? $uploadInfo['text'] : '';
725 $revision->setTitle( $pageInfo['_title'] );
726 $revision->setID( $pageInfo['id'] );
727 $revision->setTimestamp( $uploadInfo['timestamp'] );
728 $revision->setText( $text );
729 $revision->setFilename( $uploadInfo['filename'] );
730 if ( isset( $uploadInfo['archivename'] ) ) {
731 $revision->setArchiveName( $uploadInfo['archivename'] );
733 $revision->setSrc( $uploadInfo['src'] );
734 if ( isset( $uploadInfo['fileSrc'] ) ) {
735 $revision->setFileSrc( $uploadInfo['fileSrc'],
736 !empty( $uploadInfo['isTempSrc'] ) );
738 if ( isset( $uploadInfo['sha1base36'] ) ) {
739 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
741 $revision->setSize( intval( $uploadInfo['size'] ) );
742 $revision->setComment( $uploadInfo['comment'] );
744 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
745 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
747 if ( isset( $uploadInfo['contributor']['username'] ) ) {
748 $revision->setUserName( $uploadInfo['contributor']['username'] );
750 $revision->setNoUpdates( $this->mNoUpdates );
752 return call_user_func( $this->mUploadCallback, $revision );
756 * @return array
758 private function handleContributor() {
759 $fields = array( 'id', 'ip', 'username' );
760 $info = array();
762 while ( $this->reader->read() ) {
763 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
764 $this->reader->name == 'contributor') {
765 break;
768 $tag = $this->reader->name;
770 if ( in_array( $tag, $fields ) ) {
771 $info[$tag] = $this->nodeContents();
775 return $info;
779 * @param $text string
780 * @return Array or false
782 private function processTitle( $text ) {
783 global $wgCommandLineMode;
785 $workTitle = $text;
786 $origTitle = Title::newFromText( $workTitle );
788 if( !is_null( $this->mTargetNamespace ) && !is_null( $origTitle ) ) {
789 # makeTitleSafe, because $origTitle can have a interwiki (different setting of interwiki map)
790 # and than dbKey can begin with a lowercase char
791 $title = Title::makeTitleSafe( $this->mTargetNamespace,
792 $origTitle->getDBkey() );
793 } else {
794 $title = Title::newFromText( $workTitle );
797 if( is_null( $title ) ) {
798 # Invalid page title? Ignore the page
799 $this->notice( 'import-error-invalid', $workTitle );
800 return false;
801 } elseif( $title->isExternal() ) {
802 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
803 return false;
804 } elseif( !$title->canExist() ) {
805 $this->notice( 'import-error-special', $title->getPrefixedText() );
806 return false;
807 } elseif( !$title->userCan( 'edit' ) && !$wgCommandLineMode ) {
808 # Do not import if the importing wiki user cannot edit this page
809 $this->notice( 'import-error-edit', $title->getPrefixedText() );
810 return false;
811 } elseif( !$title->exists() && !$title->userCan( 'create' ) && !$wgCommandLineMode ) {
812 # Do not import if the importing wiki user cannot create this page
813 $this->notice( 'import-error-create', $title->getPrefixedText() );
814 return false;
817 return array( $title, $origTitle );
821 /** This is a horrible hack used to keep source compatibility */
822 class UploadSourceAdapter {
823 static $sourceRegistrations = array();
825 private $mSource;
826 private $mBuffer;
827 private $mPosition;
830 * @param $source
831 * @return string
833 static function registerSource( $source ) {
834 $id = wfRandomString();
836 self::$sourceRegistrations[$id] = $source;
838 return $id;
842 * @param $path
843 * @param $mode
844 * @param $options
845 * @param $opened_path
846 * @return bool
848 function stream_open( $path, $mode, $options, &$opened_path ) {
849 $url = parse_url($path);
850 $id = $url['host'];
852 if ( !isset( self::$sourceRegistrations[$id] ) ) {
853 return false;
856 $this->mSource = self::$sourceRegistrations[$id];
858 return true;
862 * @param $count
863 * @return string
865 function stream_read( $count ) {
866 $return = '';
867 $leave = false;
869 while ( !$leave && !$this->mSource->atEnd() &&
870 strlen($this->mBuffer) < $count ) {
871 $read = $this->mSource->readChunk();
873 if ( !strlen($read) ) {
874 $leave = true;
877 $this->mBuffer .= $read;
880 if ( strlen($this->mBuffer) ) {
881 $return = substr( $this->mBuffer, 0, $count );
882 $this->mBuffer = substr( $this->mBuffer, $count );
885 $this->mPosition += strlen($return);
887 return $return;
891 * @param $data
892 * @return bool
894 function stream_write( $data ) {
895 return false;
899 * @return mixed
901 function stream_tell() {
902 return $this->mPosition;
906 * @return bool
908 function stream_eof() {
909 return $this->mSource->atEnd();
913 * @return array
915 function url_stat() {
916 $result = array();
918 $result['dev'] = $result[0] = 0;
919 $result['ino'] = $result[1] = 0;
920 $result['mode'] = $result[2] = 0;
921 $result['nlink'] = $result[3] = 0;
922 $result['uid'] = $result[4] = 0;
923 $result['gid'] = $result[5] = 0;
924 $result['rdev'] = $result[6] = 0;
925 $result['size'] = $result[7] = 0;
926 $result['atime'] = $result[8] = 0;
927 $result['mtime'] = $result[9] = 0;
928 $result['ctime'] = $result[10] = 0;
929 $result['blksize'] = $result[11] = 0;
930 $result['blocks'] = $result[12] = 0;
932 return $result;
936 class XMLReader2 extends XMLReader {
939 * @return bool|string
941 function nodeContents() {
942 if( $this->isEmptyElement ) {
943 return "";
945 $buffer = "";
946 while( $this->read() ) {
947 switch( $this->nodeType ) {
948 case XmlReader::TEXT:
949 case XmlReader::SIGNIFICANT_WHITESPACE:
950 $buffer .= $this->value;
951 break;
952 case XmlReader::END_ELEMENT:
953 return $buffer;
956 return $this->close();
961 * @todo document (e.g. one-sentence class description).
962 * @ingroup SpecialPage
964 class WikiRevision {
965 var $importer = null;
968 * @var Title
970 var $title = null;
971 var $id = 0;
972 var $timestamp = "20010115000000";
973 var $user = 0;
974 var $user_text = "";
975 var $text = "";
976 var $comment = "";
977 var $minor = false;
978 var $type = "";
979 var $action = "";
980 var $params = "";
981 var $fileSrc = '';
982 var $sha1base36 = false;
983 var $isTemp = false;
984 var $archiveName = '';
985 var $fileIsTemp;
986 private $mNoUpdates = false;
989 * @param $title
990 * @throws MWException
992 function setTitle( $title ) {
993 if( is_object( $title ) ) {
994 $this->title = $title;
995 } elseif( is_null( $title ) ) {
996 throw new MWException( "WikiRevision given a null title in import. You may need to adjust \$wgLegalTitleChars." );
997 } else {
998 throw new MWException( "WikiRevision given non-object title in import." );
1003 * @param $id
1005 function setID( $id ) {
1006 $this->id = $id;
1010 * @param $ts
1012 function setTimestamp( $ts ) {
1013 # 2003-08-05T18:30:02Z
1014 $this->timestamp = wfTimestamp( TS_MW, $ts );
1018 * @param $user
1020 function setUsername( $user ) {
1021 $this->user_text = $user;
1025 * @param $ip
1027 function setUserIP( $ip ) {
1028 $this->user_text = $ip;
1032 * @param $text
1034 function setText( $text ) {
1035 $this->text = $text;
1039 * @param $text
1041 function setComment( $text ) {
1042 $this->comment = $text;
1046 * @param $minor
1048 function setMinor( $minor ) {
1049 $this->minor = (bool)$minor;
1053 * @param $src
1055 function setSrc( $src ) {
1056 $this->src = $src;
1060 * @param $src
1061 * @param $isTemp
1063 function setFileSrc( $src, $isTemp ) {
1064 $this->fileSrc = $src;
1065 $this->fileIsTemp = $isTemp;
1069 * @param $sha1base36
1071 function setSha1Base36( $sha1base36 ) {
1072 $this->sha1base36 = $sha1base36;
1076 * @param $filename
1078 function setFilename( $filename ) {
1079 $this->filename = $filename;
1083 * @param $archiveName
1085 function setArchiveName( $archiveName ) {
1086 $this->archiveName = $archiveName;
1090 * @param $size
1092 function setSize( $size ) {
1093 $this->size = intval( $size );
1097 * @param $type
1099 function setType( $type ) {
1100 $this->type = $type;
1104 * @param $action
1106 function setAction( $action ) {
1107 $this->action = $action;
1111 * @param $params
1113 function setParams( $params ) {
1114 $this->params = $params;
1118 * @param $noupdates
1120 public function setNoUpdates( $noupdates ) {
1121 $this->mNoUpdates = $noupdates;
1125 * @return Title
1127 function getTitle() {
1128 return $this->title;
1132 * @return int
1134 function getID() {
1135 return $this->id;
1139 * @return string
1141 function getTimestamp() {
1142 return $this->timestamp;
1146 * @return string
1148 function getUser() {
1149 return $this->user_text;
1153 * @return string
1155 function getText() {
1156 return $this->text;
1160 * @return string
1162 function getComment() {
1163 return $this->comment;
1167 * @return bool
1169 function getMinor() {
1170 return $this->minor;
1174 * @return mixed
1176 function getSrc() {
1177 return $this->src;
1181 * @return bool|String
1183 function getSha1() {
1184 if ( $this->sha1base36 ) {
1185 return wfBaseConvert( $this->sha1base36, 36, 16 );
1187 return false;
1191 * @return string
1193 function getFileSrc() {
1194 return $this->fileSrc;
1198 * @return bool
1200 function isTempSrc() {
1201 return $this->isTemp;
1205 * @return mixed
1207 function getFilename() {
1208 return $this->filename;
1212 * @return string
1214 function getArchiveName() {
1215 return $this->archiveName;
1219 * @return mixed
1221 function getSize() {
1222 return $this->size;
1226 * @return string
1228 function getType() {
1229 return $this->type;
1233 * @return string
1235 function getAction() {
1236 return $this->action;
1240 * @return string
1242 function getParams() {
1243 return $this->params;
1247 * @return bool
1249 function importOldRevision() {
1250 $dbw = wfGetDB( DB_MASTER );
1252 # Sneak a single revision into place
1253 $user = User::newFromName( $this->getUser() );
1254 if( $user ) {
1255 $userId = intval( $user->getId() );
1256 $userText = $user->getName();
1257 $userObj = $user;
1258 } else {
1259 $userId = 0;
1260 $userText = $this->getUser();
1261 $userObj = new User;
1264 // avoid memory leak...?
1265 $linkCache = LinkCache::singleton();
1266 $linkCache->clear();
1268 $page = WikiPage::factory( $this->title );
1269 if( !$page->exists() ) {
1270 # must create the page...
1271 $pageId = $page->insertOn( $dbw );
1272 $created = true;
1273 $oldcountable = null;
1274 } else {
1275 $pageId = $page->getId();
1276 $created = false;
1278 $prior = $dbw->selectField( 'revision', '1',
1279 array( 'rev_page' => $pageId,
1280 'rev_timestamp' => $dbw->timestamp( $this->timestamp ),
1281 'rev_user_text' => $userText,
1282 'rev_comment' => $this->getComment() ),
1283 __METHOD__
1285 if( $prior ) {
1286 // @todo FIXME: This could fail slightly for multiple matches :P
1287 wfDebug( __METHOD__ . ": skipping existing revision for [[" .
1288 $this->title->getPrefixedText() . "]], timestamp " . $this->timestamp . "\n" );
1289 return false;
1291 $oldcountable = $page->isCountable();
1294 # @todo FIXME: Use original rev_id optionally (better for backups)
1295 # Insert the row
1296 $revision = new Revision( array(
1297 'page' => $pageId,
1298 'text' => $this->getText(),
1299 'comment' => $this->getComment(),
1300 'user' => $userId,
1301 'user_text' => $userText,
1302 'timestamp' => $this->timestamp,
1303 'minor_edit' => $this->minor,
1304 ) );
1305 $revision->insertOn( $dbw );
1306 $changed = $page->updateIfNewerOn( $dbw, $revision );
1308 if ( $changed !== false && !$this->mNoUpdates ) {
1309 wfDebug( __METHOD__ . ": running updates\n" );
1310 $page->doEditUpdates( $revision, $userObj, array( 'created' => $created, 'oldcountable' => $oldcountable ) );
1313 return true;
1317 * @return mixed
1319 function importLogItem() {
1320 $dbw = wfGetDB( DB_MASTER );
1321 # @todo FIXME: This will not record autoblocks
1322 if( !$this->getTitle() ) {
1323 wfDebug( __METHOD__ . ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1324 $this->timestamp . "\n" );
1325 return;
1327 # Check if it exists already
1328 // @todo FIXME: Use original log ID (better for backups)
1329 $prior = $dbw->selectField( 'logging', '1',
1330 array( 'log_type' => $this->getType(),
1331 'log_action' => $this->getAction(),
1332 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
1333 'log_namespace' => $this->getTitle()->getNamespace(),
1334 'log_title' => $this->getTitle()->getDBkey(),
1335 'log_comment' => $this->getComment(),
1336 #'log_user_text' => $this->user_text,
1337 'log_params' => $this->params ),
1338 __METHOD__
1340 // @todo FIXME: This could fail slightly for multiple matches :P
1341 if( $prior ) {
1342 wfDebug( __METHOD__ . ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp " .
1343 $this->timestamp . "\n" );
1344 return;
1346 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1347 $data = array(
1348 'log_id' => $log_id,
1349 'log_type' => $this->type,
1350 'log_action' => $this->action,
1351 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
1352 'log_user' => User::idFromName( $this->user_text ),
1353 #'log_user_text' => $this->user_text,
1354 'log_namespace' => $this->getTitle()->getNamespace(),
1355 'log_title' => $this->getTitle()->getDBkey(),
1356 'log_comment' => $this->getComment(),
1357 'log_params' => $this->params
1359 $dbw->insert( 'logging', $data, __METHOD__ );
1363 * @return bool
1365 function importUpload() {
1366 # Construct a file
1367 $archiveName = $this->getArchiveName();
1368 if ( $archiveName ) {
1369 wfDebug( __METHOD__ . "Importing archived file as $archiveName\n" );
1370 $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
1371 RepoGroup::singleton()->getLocalRepo(), $archiveName );
1372 } else {
1373 $file = wfLocalFile( $this->getTitle() );
1374 wfDebug( __METHOD__ . 'Importing new file as ' . $file->getName() . "\n" );
1375 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1376 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1377 $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
1378 RepoGroup::singleton()->getLocalRepo(), $archiveName );
1379 wfDebug( __METHOD__ . "File already exists; importing as $archiveName\n" );
1382 if( !$file ) {
1383 wfDebug( __METHOD__ . ': Bad file for ' . $this->getTitle() . "\n" );
1384 return false;
1387 # Get the file source or download if necessary
1388 $source = $this->getFileSrc();
1389 $flags = $this->isTempSrc() ? File::DELETE_SOURCE : 0;
1390 if ( !$source ) {
1391 $source = $this->downloadSource();
1392 $flags |= File::DELETE_SOURCE;
1394 if( !$source ) {
1395 wfDebug( __METHOD__ . ": Could not fetch remote file.\n" );
1396 return false;
1398 $sha1 = $this->getSha1();
1399 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1400 if ( $flags & File::DELETE_SOURCE ) {
1401 # Broken file; delete it if it is a temporary file
1402 unlink( $source );
1404 wfDebug( __METHOD__ . ": Corrupt file $source.\n" );
1405 return false;
1408 $user = User::newFromName( $this->user_text );
1410 # Do the actual upload
1411 if ( $archiveName ) {
1412 $status = $file->uploadOld( $source, $archiveName,
1413 $this->getTimestamp(), $this->getComment(), $user, $flags );
1414 } else {
1415 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1416 $flags, false, $this->getTimestamp(), $user );
1419 if ( $status->isGood() ) {
1420 wfDebug( __METHOD__ . ": Succesful\n" );
1421 return true;
1422 } else {
1423 wfDebug( __METHOD__ . ': failed: ' . $status->getXml() . "\n" );
1424 return false;
1429 * @return bool|string
1431 function downloadSource() {
1432 global $wgEnableUploads;
1433 if( !$wgEnableUploads ) {
1434 return false;
1437 $tempo = tempnam( wfTempDir(), 'download' );
1438 $f = fopen( $tempo, 'wb' );
1439 if( !$f ) {
1440 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1441 return false;
1444 // @todo FIXME!
1445 $src = $this->getSrc();
1446 $data = Http::get( $src );
1447 if( !$data ) {
1448 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1449 fclose( $f );
1450 unlink( $tempo );
1451 return false;
1454 fwrite( $f, $data );
1455 fclose( $f );
1457 return $tempo;
1463 * @todo document (e.g. one-sentence class description).
1464 * @ingroup SpecialPage
1466 class ImportStringSource {
1467 function __construct( $string ) {
1468 $this->mString = $string;
1469 $this->mRead = false;
1473 * @return bool
1475 function atEnd() {
1476 return $this->mRead;
1480 * @return bool|string
1482 function readChunk() {
1483 if( $this->atEnd() ) {
1484 return false;
1486 $this->mRead = true;
1487 return $this->mString;
1492 * @todo document (e.g. one-sentence class description).
1493 * @ingroup SpecialPage
1495 class ImportStreamSource {
1496 function __construct( $handle ) {
1497 $this->mHandle = $handle;
1501 * @return bool
1503 function atEnd() {
1504 return feof( $this->mHandle );
1508 * @return string
1510 function readChunk() {
1511 return fread( $this->mHandle, 32768 );
1515 * @param $filename string
1516 * @return Status
1518 static function newFromFile( $filename ) {
1519 wfSuppressWarnings();
1520 $file = fopen( $filename, 'rt' );
1521 wfRestoreWarnings();
1522 if( !$file ) {
1523 return Status::newFatal( "importcantopen" );
1525 return Status::newGood( new ImportStreamSource( $file ) );
1529 * @param $fieldname string
1530 * @return Status
1532 static function newFromUpload( $fieldname = "xmlimport" ) {
1533 $upload =& $_FILES[$fieldname];
1535 if( !isset( $upload ) || !$upload['name'] ) {
1536 return Status::newFatal( 'importnofile' );
1538 if( !empty( $upload['error'] ) ) {
1539 switch($upload['error']){
1540 case 1: # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1541 return Status::newFatal( 'importuploaderrorsize' );
1542 case 2: # The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
1543 return Status::newFatal( 'importuploaderrorsize' );
1544 case 3: # The uploaded file was only partially uploaded
1545 return Status::newFatal( 'importuploaderrorpartial' );
1546 case 6: #Missing a temporary folder.
1547 return Status::newFatal( 'importuploaderrortemp' );
1548 # case else: # Currently impossible
1552 $fname = $upload['tmp_name'];
1553 if( is_uploaded_file( $fname ) ) {
1554 return ImportStreamSource::newFromFile( $fname );
1555 } else {
1556 return Status::newFatal( 'importnofile' );
1561 * @param $url
1562 * @param $method string
1563 * @return Status
1565 static function newFromURL( $url, $method = 'GET' ) {
1566 wfDebug( __METHOD__ . ": opening $url\n" );
1567 # Use the standard HTTP fetch function; it times out
1568 # quicker and sorts out user-agent problems which might
1569 # otherwise prevent importing from large sites, such
1570 # as the Wikimedia cluster, etc.
1571 $data = Http::request( $method, $url, array( 'followRedirects' => true ) );
1572 if( $data !== false ) {
1573 $file = tmpfile();
1574 fwrite( $file, $data );
1575 fflush( $file );
1576 fseek( $file, 0 );
1577 return Status::newGood( new ImportStreamSource( $file ) );
1578 } else {
1579 return Status::newFatal( 'importcantopen' );
1584 * @param $interwiki
1585 * @param $page
1586 * @param $history bool
1587 * @param $templates bool
1588 * @param $pageLinkDepth int
1589 * @return Status
1591 public static function newFromInterwiki( $interwiki, $page, $history = false, $templates = false, $pageLinkDepth = 0 ) {
1592 if( $page == '' ) {
1593 return Status::newFatal( 'import-noarticle' );
1595 $link = Title::newFromText( "$interwiki:Special:Export/$page" );
1596 if( is_null( $link ) || $link->getInterwiki() == '' ) {
1597 return Status::newFatal( 'importbadinterwiki' );
1598 } else {
1599 $params = array();
1600 if ( $history ) $params['history'] = 1;
1601 if ( $templates ) $params['templates'] = 1;
1602 if ( $pageLinkDepth ) $params['pagelink-depth'] = $pageLinkDepth;
1603 $url = $link->getFullUrl( $params );
1604 # For interwikis, use POST to avoid redirects.
1605 return ImportStreamSource::newFromURL( $url, "POST" );