Don't display multiple language links to the same language
[mediawiki.git] / includes / Import.php
blob11f379522db2d040e8b1aa27a4ae252153966cda
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, $mTargetRootPage, $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 * Set a target root page under which all pages are imported
204 * @param $rootpage
205 * @return status object
207 public function setTargetRootPage( $rootpage ) {
208 $status = Status::newGood();
209 if( is_null( $rootpage ) ) {
210 // No rootpage
211 $this->mTargetRootPage = null;
212 } elseif( $rootpage !== '' ) {
213 $rootpage = rtrim( $rootpage, '/' ); //avoid double slashes
214 $title = Title::newFromText( $rootpage, !is_null( $this->mTargetNamespace ) ? $this->mTargetNamespace : NS_MAIN );
215 if( !$title || $title->isExternal() ) {
216 $status->fatal( 'import-rootpage-invalid' );
217 } else {
218 if( !MWNamespace::hasSubpages( $title->getNamespace() ) ) {
219 global $wgContLang;
221 $displayNSText = $title->getNamespace() == NS_MAIN
222 ? wfMessage( 'blanknamespace' )->text()
223 : $wgContLang->getNsText( $title->getNamespace() );
224 $status->fatal( 'import-rootpage-nosubpage', $displayNSText );
225 } else {
226 // set namespace to 'all', so the namespace check in processTitle() can passed
227 $this->setTargetNamespace( null );
228 $this->mTargetRootPage = $title->getPrefixedDBKey();
232 return $status;
236 * @param $dir
238 public function setImageBasePath( $dir ) {
239 $this->mImageBasePath = $dir;
243 * @param $import
245 public function setImportUploads( $import ) {
246 $this->mImportUploads = $import;
250 * Default per-revision callback, performs the import.
251 * @param $revision WikiRevision
252 * @return bool
254 public function importRevision( $revision ) {
255 $dbw = wfGetDB( DB_MASTER );
256 return $dbw->deadlockLoop( array( $revision, 'importOldRevision' ) );
260 * Default per-revision callback, performs the import.
261 * @param $rev WikiRevision
262 * @return bool
264 public function importLogItem( $rev ) {
265 $dbw = wfGetDB( DB_MASTER );
266 return $dbw->deadlockLoop( array( $rev, 'importLogItem' ) );
270 * Dummy for now...
271 * @param $revision
272 * @return bool
274 public function importUpload( $revision ) {
275 $dbw = wfGetDB( DB_MASTER );
276 return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
280 * Mostly for hook use
281 * @param $title
282 * @param $origTitle
283 * @param $revCount
284 * @param $sRevCount
285 * @param $pageInfo
286 * @return
288 public function finishImportPage( $title, $origTitle, $revCount, $sRevCount, $pageInfo ) {
289 $args = func_get_args();
290 return wfRunHooks( 'AfterImportPage', $args );
294 * Alternate per-revision callback, for debugging.
295 * @param $revision WikiRevision
297 public function debugRevisionHandler( &$revision ) {
298 $this->debug( "Got revision:" );
299 if( is_object( $revision->title ) ) {
300 $this->debug( "-- Title: " . $revision->title->getPrefixedText() );
301 } else {
302 $this->debug( "-- Title: <invalid>" );
304 $this->debug( "-- User: " . $revision->user_text );
305 $this->debug( "-- Timestamp: " . $revision->timestamp );
306 $this->debug( "-- Comment: " . $revision->comment );
307 $this->debug( "-- Text: " . $revision->text );
311 * Notify the callback function when a new "<page>" is reached.
312 * @param $title Title
314 function pageCallback( $title ) {
315 if( isset( $this->mPageCallback ) ) {
316 call_user_func( $this->mPageCallback, $title );
321 * Notify the callback function when a "</page>" is closed.
322 * @param $title Title
323 * @param $origTitle Title
324 * @param $revCount Integer
325 * @param $sucCount Int: number of revisions for which callback returned true
326 * @param $pageInfo Array: associative array of page information
328 private function pageOutCallback( $title, $origTitle, $revCount, $sucCount, $pageInfo ) {
329 if( isset( $this->mPageOutCallback ) ) {
330 $args = func_get_args();
331 call_user_func_array( $this->mPageOutCallback, $args );
336 * Notify the callback function of a revision
337 * @param $revision WikiRevision object
338 * @return bool|mixed
340 private function revisionCallback( $revision ) {
341 if ( isset( $this->mRevisionCallback ) ) {
342 return call_user_func_array( $this->mRevisionCallback,
343 array( $revision, $this ) );
344 } else {
345 return false;
350 * Notify the callback function of a new log item
351 * @param $revision WikiRevision object
352 * @return bool|mixed
354 private function logItemCallback( $revision ) {
355 if ( isset( $this->mLogItemCallback ) ) {
356 return call_user_func_array( $this->mLogItemCallback,
357 array( $revision, $this ) );
358 } else {
359 return false;
364 * Shouldn't something like this be built-in to XMLReader?
365 * Fetches text contents of the current element, assuming
366 * no sub-elements or such scary things.
367 * @return string
368 * @access private
370 private function nodeContents() {
371 if( $this->reader->isEmptyElement ) {
372 return "";
374 $buffer = "";
375 while( $this->reader->read() ) {
376 switch( $this->reader->nodeType ) {
377 case XmlReader::TEXT:
378 case XmlReader::SIGNIFICANT_WHITESPACE:
379 $buffer .= $this->reader->value;
380 break;
381 case XmlReader::END_ELEMENT:
382 return $buffer;
386 $this->reader->close();
387 return '';
390 # --------------
392 /** Left in for debugging */
393 private function dumpElement() {
394 static $lookup = null;
395 if (!$lookup) {
396 $xmlReaderConstants = array(
397 "NONE",
398 "ELEMENT",
399 "ATTRIBUTE",
400 "TEXT",
401 "CDATA",
402 "ENTITY_REF",
403 "ENTITY",
404 "PI",
405 "COMMENT",
406 "DOC",
407 "DOC_TYPE",
408 "DOC_FRAGMENT",
409 "NOTATION",
410 "WHITESPACE",
411 "SIGNIFICANT_WHITESPACE",
412 "END_ELEMENT",
413 "END_ENTITY",
414 "XML_DECLARATION",
416 $lookup = array();
418 foreach( $xmlReaderConstants as $name ) {
419 $lookup[constant("XmlReader::$name")] = $name;
423 print( var_dump(
424 $lookup[$this->reader->nodeType],
425 $this->reader->name,
426 $this->reader->value
427 )."\n\n" );
431 * Primary entry point
432 * @return bool
434 public function doImport() {
435 $this->reader->read();
437 if ( $this->reader->name != 'mediawiki' ) {
438 throw new MWException( "Expected <mediawiki> tag, got ".
439 $this->reader->name );
441 $this->debug( "<mediawiki> tag is correct." );
443 $this->debug( "Starting primary dump processing loop." );
445 $keepReading = $this->reader->read();
446 $skip = false;
447 while ( $keepReading ) {
448 $tag = $this->reader->name;
449 $type = $this->reader->nodeType;
451 if ( !wfRunHooks( 'ImportHandleToplevelXMLTag', $this ) ) {
452 // Do nothing
453 } elseif ( $tag == 'mediawiki' && $type == XmlReader::END_ELEMENT ) {
454 break;
455 } elseif ( $tag == 'siteinfo' ) {
456 $this->handleSiteInfo();
457 } elseif ( $tag == 'page' ) {
458 $this->handlePage();
459 } elseif ( $tag == 'logitem' ) {
460 $this->handleLogItem();
461 } elseif ( $tag != '#text' ) {
462 $this->warn( "Unhandled top-level XML tag $tag" );
464 $skip = true;
467 if ($skip) {
468 $keepReading = $this->reader->next();
469 $skip = false;
470 $this->debug( "Skip" );
471 } else {
472 $keepReading = $this->reader->read();
476 return true;
480 * @return bool
481 * @throws MWException
483 private function handleSiteInfo() {
484 // Site info is useful, but not actually used for dump imports.
485 // Includes a quick short-circuit to save performance.
486 if ( ! $this->mSiteInfoCallback ) {
487 $this->reader->next();
488 return true;
490 throw new MWException( "SiteInfo tag is not yet handled, do not set mSiteInfoCallback" );
493 private function handleLogItem() {
494 $this->debug( "Enter log item handler." );
495 $logInfo = array();
497 // Fields that can just be stuffed in the pageInfo object
498 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
499 'logtitle', 'params' );
501 while ( $this->reader->read() ) {
502 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
503 $this->reader->name == 'logitem') {
504 break;
507 $tag = $this->reader->name;
509 if ( !wfRunHooks( 'ImportHandleLogItemXMLTag',
510 $this, $logInfo ) ) {
511 // Do nothing
512 } elseif ( in_array( $tag, $normalFields ) ) {
513 $logInfo[$tag] = $this->nodeContents();
514 } elseif ( $tag == 'contributor' ) {
515 $logInfo['contributor'] = $this->handleContributor();
516 } elseif ( $tag != '#text' ) {
517 $this->warn( "Unhandled log-item XML tag $tag" );
521 $this->processLogItem( $logInfo );
525 * @param $logInfo
526 * @return bool|mixed
528 private function processLogItem( $logInfo ) {
529 $revision = new WikiRevision;
531 $revision->setID( $logInfo['id'] );
532 $revision->setType( $logInfo['type'] );
533 $revision->setAction( $logInfo['action'] );
534 $revision->setTimestamp( $logInfo['timestamp'] );
535 $revision->setParams( $logInfo['params'] );
536 $revision->setTitle( Title::newFromText( $logInfo['logtitle'] ) );
537 $revision->setNoUpdates( $this->mNoUpdates );
539 if ( isset( $logInfo['comment'] ) ) {
540 $revision->setComment( $logInfo['comment'] );
543 if ( isset( $logInfo['contributor']['ip'] ) ) {
544 $revision->setUserIP( $logInfo['contributor']['ip'] );
546 if ( isset( $logInfo['contributor']['username'] ) ) {
547 $revision->setUserName( $logInfo['contributor']['username'] );
550 return $this->logItemCallback( $revision );
553 private function handlePage() {
554 // Handle page data.
555 $this->debug( "Enter page handler." );
556 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
558 // Fields that can just be stuffed in the pageInfo object
559 $normalFields = array( 'title', 'id', 'redirect', 'restrictions' );
561 $skip = false;
562 $badTitle = false;
564 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
565 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
566 $this->reader->name == 'page') {
567 break;
570 $tag = $this->reader->name;
572 if ( $badTitle ) {
573 // The title is invalid, bail out of this page
574 $skip = true;
575 } elseif ( !wfRunHooks( 'ImportHandlePageXMLTag', array( $this,
576 &$pageInfo ) ) ) {
577 // Do nothing
578 } elseif ( in_array( $tag, $normalFields ) ) {
579 $pageInfo[$tag] = $this->nodeContents();
580 if ( $tag == 'title' ) {
581 $title = $this->processTitle( $pageInfo['title'] );
583 if ( !$title ) {
584 $badTitle = true;
585 $skip = true;
588 $this->pageCallback( $title );
589 list( $pageInfo['_title'], $origTitle ) = $title;
591 } elseif ( $tag == 'revision' ) {
592 $this->handleRevision( $pageInfo );
593 } elseif ( $tag == 'upload' ) {
594 $this->handleUpload( $pageInfo );
595 } elseif ( $tag != '#text' ) {
596 $this->warn( "Unhandled page XML tag $tag" );
597 $skip = true;
601 $this->pageOutCallback( $pageInfo['_title'], $origTitle,
602 $pageInfo['revisionCount'],
603 $pageInfo['successfulRevisionCount'],
604 $pageInfo );
608 * @param $pageInfo array
610 private function handleRevision( &$pageInfo ) {
611 $this->debug( "Enter revision handler" );
612 $revisionInfo = array();
614 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'text' );
616 $skip = false;
618 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
619 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
620 $this->reader->name == 'revision') {
621 break;
624 $tag = $this->reader->name;
626 if ( !wfRunHooks( 'ImportHandleRevisionXMLTag', $this,
627 $pageInfo, $revisionInfo ) ) {
628 // Do nothing
629 } elseif ( in_array( $tag, $normalFields ) ) {
630 $revisionInfo[$tag] = $this->nodeContents();
631 } elseif ( $tag == 'contributor' ) {
632 $revisionInfo['contributor'] = $this->handleContributor();
633 } elseif ( $tag != '#text' ) {
634 $this->warn( "Unhandled revision XML tag $tag" );
635 $skip = true;
639 $pageInfo['revisionCount']++;
640 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
641 $pageInfo['successfulRevisionCount']++;
646 * @param $pageInfo
647 * @param $revisionInfo
648 * @return bool|mixed
650 private function processRevision( $pageInfo, $revisionInfo ) {
651 $revision = new WikiRevision;
653 if( isset( $revisionInfo['id'] ) ) {
654 $revision->setID( $revisionInfo['id'] );
656 if ( isset( $revisionInfo['text'] ) ) {
657 $revision->setText( $revisionInfo['text'] );
659 $revision->setTitle( $pageInfo['_title'] );
661 if ( isset( $revisionInfo['timestamp'] ) ) {
662 $revision->setTimestamp( $revisionInfo['timestamp'] );
663 } else {
664 $revision->setTimestamp( wfTimestampNow() );
667 if ( isset( $revisionInfo['comment'] ) ) {
668 $revision->setComment( $revisionInfo['comment'] );
671 if ( isset( $revisionInfo['minor'] ) ) {
672 $revision->setMinor( true );
674 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
675 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
677 if ( isset( $revisionInfo['contributor']['username'] ) ) {
678 $revision->setUserName( $revisionInfo['contributor']['username'] );
680 $revision->setNoUpdates( $this->mNoUpdates );
682 return $this->revisionCallback( $revision );
686 * @param $pageInfo
687 * @return mixed
689 private function handleUpload( &$pageInfo ) {
690 $this->debug( "Enter upload handler" );
691 $uploadInfo = array();
693 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
694 'src', 'size', 'sha1base36', 'archivename', 'rel' );
696 $skip = false;
698 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
699 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
700 $this->reader->name == 'upload') {
701 break;
704 $tag = $this->reader->name;
706 if ( !wfRunHooks( 'ImportHandleUploadXMLTag', $this,
707 $pageInfo ) ) {
708 // Do nothing
709 } elseif ( in_array( $tag, $normalFields ) ) {
710 $uploadInfo[$tag] = $this->nodeContents();
711 } elseif ( $tag == 'contributor' ) {
712 $uploadInfo['contributor'] = $this->handleContributor();
713 } elseif ( $tag == 'contents' ) {
714 $contents = $this->nodeContents();
715 $encoding = $this->reader->getAttribute( 'encoding' );
716 if ( $encoding === 'base64' ) {
717 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
718 $uploadInfo['isTempSrc'] = true;
720 } elseif ( $tag != '#text' ) {
721 $this->warn( "Unhandled upload XML tag $tag" );
722 $skip = true;
726 if ( $this->mImageBasePath && isset( $uploadInfo['rel'] ) ) {
727 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
728 if ( file_exists( $path ) ) {
729 $uploadInfo['fileSrc'] = $path;
730 $uploadInfo['isTempSrc'] = false;
734 if ( $this->mImportUploads ) {
735 return $this->processUpload( $pageInfo, $uploadInfo );
740 * @param $contents
741 * @return string
743 private function dumpTemp( $contents ) {
744 $filename = tempnam( wfTempDir(), 'importupload' );
745 file_put_contents( $filename, $contents );
746 return $filename;
750 * @param $pageInfo
751 * @param $uploadInfo
752 * @return mixed
754 private function processUpload( $pageInfo, $uploadInfo ) {
755 $revision = new WikiRevision;
756 $text = isset( $uploadInfo['text'] ) ? $uploadInfo['text'] : '';
758 $revision->setTitle( $pageInfo['_title'] );
759 $revision->setID( $pageInfo['id'] );
760 $revision->setTimestamp( $uploadInfo['timestamp'] );
761 $revision->setText( $text );
762 $revision->setFilename( $uploadInfo['filename'] );
763 if ( isset( $uploadInfo['archivename'] ) ) {
764 $revision->setArchiveName( $uploadInfo['archivename'] );
766 $revision->setSrc( $uploadInfo['src'] );
767 if ( isset( $uploadInfo['fileSrc'] ) ) {
768 $revision->setFileSrc( $uploadInfo['fileSrc'],
769 !empty( $uploadInfo['isTempSrc'] ) );
771 if ( isset( $uploadInfo['sha1base36'] ) ) {
772 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
774 $revision->setSize( intval( $uploadInfo['size'] ) );
775 $revision->setComment( $uploadInfo['comment'] );
777 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
778 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
780 if ( isset( $uploadInfo['contributor']['username'] ) ) {
781 $revision->setUserName( $uploadInfo['contributor']['username'] );
783 $revision->setNoUpdates( $this->mNoUpdates );
785 return call_user_func( $this->mUploadCallback, $revision );
789 * @return array
791 private function handleContributor() {
792 $fields = array( 'id', 'ip', 'username' );
793 $info = array();
795 while ( $this->reader->read() ) {
796 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
797 $this->reader->name == 'contributor') {
798 break;
801 $tag = $this->reader->name;
803 if ( in_array( $tag, $fields ) ) {
804 $info[$tag] = $this->nodeContents();
808 return $info;
812 * @param $text string
813 * @return Array or false
815 private function processTitle( $text ) {
816 global $wgCommandLineMode;
818 $workTitle = $text;
819 $origTitle = Title::newFromText( $workTitle );
821 if( !is_null( $this->mTargetNamespace ) && !is_null( $origTitle ) ) {
822 # makeTitleSafe, because $origTitle can have a interwiki (different setting of interwiki map)
823 # and than dbKey can begin with a lowercase char
824 $title = Title::makeTitleSafe( $this->mTargetNamespace,
825 $origTitle->getDBkey() );
826 } else {
827 if( !is_null( $this->mTargetRootPage ) ) {
828 $workTitle = $this->mTargetRootPage . '/' . $workTitle;
830 $title = Title::newFromText( $workTitle );
833 if( is_null( $title ) ) {
834 # Invalid page title? Ignore the page
835 $this->notice( 'import-error-invalid', $workTitle );
836 return false;
837 } elseif( $title->isExternal() ) {
838 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
839 return false;
840 } elseif( !$title->canExist() ) {
841 $this->notice( 'import-error-special', $title->getPrefixedText() );
842 return false;
843 } elseif( !$title->userCan( 'edit' ) && !$wgCommandLineMode ) {
844 # Do not import if the importing wiki user cannot edit this page
845 $this->notice( 'import-error-edit', $title->getPrefixedText() );
846 return false;
847 } elseif( !$title->exists() && !$title->userCan( 'create' ) && !$wgCommandLineMode ) {
848 # Do not import if the importing wiki user cannot create this page
849 $this->notice( 'import-error-create', $title->getPrefixedText() );
850 return false;
853 return array( $title, $origTitle );
857 /** This is a horrible hack used to keep source compatibility */
858 class UploadSourceAdapter {
859 static $sourceRegistrations = array();
861 private $mSource;
862 private $mBuffer;
863 private $mPosition;
866 * @param $source
867 * @return string
869 static function registerSource( $source ) {
870 $id = wfRandomString();
872 self::$sourceRegistrations[$id] = $source;
874 return $id;
878 * @param $path
879 * @param $mode
880 * @param $options
881 * @param $opened_path
882 * @return bool
884 function stream_open( $path, $mode, $options, &$opened_path ) {
885 $url = parse_url($path);
886 $id = $url['host'];
888 if ( !isset( self::$sourceRegistrations[$id] ) ) {
889 return false;
892 $this->mSource = self::$sourceRegistrations[$id];
894 return true;
898 * @param $count
899 * @return string
901 function stream_read( $count ) {
902 $return = '';
903 $leave = false;
905 while ( !$leave && !$this->mSource->atEnd() &&
906 strlen($this->mBuffer) < $count ) {
907 $read = $this->mSource->readChunk();
909 if ( !strlen($read) ) {
910 $leave = true;
913 $this->mBuffer .= $read;
916 if ( strlen($this->mBuffer) ) {
917 $return = substr( $this->mBuffer, 0, $count );
918 $this->mBuffer = substr( $this->mBuffer, $count );
921 $this->mPosition += strlen($return);
923 return $return;
927 * @param $data
928 * @return bool
930 function stream_write( $data ) {
931 return false;
935 * @return mixed
937 function stream_tell() {
938 return $this->mPosition;
942 * @return bool
944 function stream_eof() {
945 return $this->mSource->atEnd();
949 * @return array
951 function url_stat() {
952 $result = array();
954 $result['dev'] = $result[0] = 0;
955 $result['ino'] = $result[1] = 0;
956 $result['mode'] = $result[2] = 0;
957 $result['nlink'] = $result[3] = 0;
958 $result['uid'] = $result[4] = 0;
959 $result['gid'] = $result[5] = 0;
960 $result['rdev'] = $result[6] = 0;
961 $result['size'] = $result[7] = 0;
962 $result['atime'] = $result[8] = 0;
963 $result['mtime'] = $result[9] = 0;
964 $result['ctime'] = $result[10] = 0;
965 $result['blksize'] = $result[11] = 0;
966 $result['blocks'] = $result[12] = 0;
968 return $result;
972 class XMLReader2 extends XMLReader {
975 * @return bool|string
977 function nodeContents() {
978 if( $this->isEmptyElement ) {
979 return "";
981 $buffer = "";
982 while( $this->read() ) {
983 switch( $this->nodeType ) {
984 case XmlReader::TEXT:
985 case XmlReader::SIGNIFICANT_WHITESPACE:
986 $buffer .= $this->value;
987 break;
988 case XmlReader::END_ELEMENT:
989 return $buffer;
992 return $this->close();
997 * @todo document (e.g. one-sentence class description).
998 * @ingroup SpecialPage
1000 class WikiRevision {
1001 var $importer = null;
1004 * @var Title
1006 var $title = null;
1007 var $id = 0;
1008 var $timestamp = "20010115000000";
1009 var $user = 0;
1010 var $user_text = "";
1011 var $text = "";
1012 var $comment = "";
1013 var $minor = false;
1014 var $type = "";
1015 var $action = "";
1016 var $params = "";
1017 var $fileSrc = '';
1018 var $sha1base36 = false;
1019 var $isTemp = false;
1020 var $archiveName = '';
1021 var $fileIsTemp;
1022 private $mNoUpdates = false;
1025 * @param $title
1026 * @throws MWException
1028 function setTitle( $title ) {
1029 if( is_object( $title ) ) {
1030 $this->title = $title;
1031 } elseif( is_null( $title ) ) {
1032 throw new MWException( "WikiRevision given a null title in import. You may need to adjust \$wgLegalTitleChars." );
1033 } else {
1034 throw new MWException( "WikiRevision given non-object title in import." );
1039 * @param $id
1041 function setID( $id ) {
1042 $this->id = $id;
1046 * @param $ts
1048 function setTimestamp( $ts ) {
1049 # 2003-08-05T18:30:02Z
1050 $this->timestamp = wfTimestamp( TS_MW, $ts );
1054 * @param $user
1056 function setUsername( $user ) {
1057 $this->user_text = $user;
1061 * @param $ip
1063 function setUserIP( $ip ) {
1064 $this->user_text = $ip;
1068 * @param $text
1070 function setText( $text ) {
1071 $this->text = $text;
1075 * @param $text
1077 function setComment( $text ) {
1078 $this->comment = $text;
1082 * @param $minor
1084 function setMinor( $minor ) {
1085 $this->minor = (bool)$minor;
1089 * @param $src
1091 function setSrc( $src ) {
1092 $this->src = $src;
1096 * @param $src
1097 * @param $isTemp
1099 function setFileSrc( $src, $isTemp ) {
1100 $this->fileSrc = $src;
1101 $this->fileIsTemp = $isTemp;
1105 * @param $sha1base36
1107 function setSha1Base36( $sha1base36 ) {
1108 $this->sha1base36 = $sha1base36;
1112 * @param $filename
1114 function setFilename( $filename ) {
1115 $this->filename = $filename;
1119 * @param $archiveName
1121 function setArchiveName( $archiveName ) {
1122 $this->archiveName = $archiveName;
1126 * @param $size
1128 function setSize( $size ) {
1129 $this->size = intval( $size );
1133 * @param $type
1135 function setType( $type ) {
1136 $this->type = $type;
1140 * @param $action
1142 function setAction( $action ) {
1143 $this->action = $action;
1147 * @param $params
1149 function setParams( $params ) {
1150 $this->params = $params;
1154 * @param $noupdates
1156 public function setNoUpdates( $noupdates ) {
1157 $this->mNoUpdates = $noupdates;
1161 * @return Title
1163 function getTitle() {
1164 return $this->title;
1168 * @return int
1170 function getID() {
1171 return $this->id;
1175 * @return string
1177 function getTimestamp() {
1178 return $this->timestamp;
1182 * @return string
1184 function getUser() {
1185 return $this->user_text;
1189 * @return string
1191 function getText() {
1192 return $this->text;
1196 * @return string
1198 function getComment() {
1199 return $this->comment;
1203 * @return bool
1205 function getMinor() {
1206 return $this->minor;
1210 * @return mixed
1212 function getSrc() {
1213 return $this->src;
1217 * @return bool|String
1219 function getSha1() {
1220 if ( $this->sha1base36 ) {
1221 return wfBaseConvert( $this->sha1base36, 36, 16 );
1223 return false;
1227 * @return string
1229 function getFileSrc() {
1230 return $this->fileSrc;
1234 * @return bool
1236 function isTempSrc() {
1237 return $this->isTemp;
1241 * @return mixed
1243 function getFilename() {
1244 return $this->filename;
1248 * @return string
1250 function getArchiveName() {
1251 return $this->archiveName;
1255 * @return mixed
1257 function getSize() {
1258 return $this->size;
1262 * @return string
1264 function getType() {
1265 return $this->type;
1269 * @return string
1271 function getAction() {
1272 return $this->action;
1276 * @return string
1278 function getParams() {
1279 return $this->params;
1283 * @return bool
1285 function importOldRevision() {
1286 $dbw = wfGetDB( DB_MASTER );
1288 # Sneak a single revision into place
1289 $user = User::newFromName( $this->getUser() );
1290 if( $user ) {
1291 $userId = intval( $user->getId() );
1292 $userText = $user->getName();
1293 $userObj = $user;
1294 } else {
1295 $userId = 0;
1296 $userText = $this->getUser();
1297 $userObj = new User;
1300 // avoid memory leak...?
1301 $linkCache = LinkCache::singleton();
1302 $linkCache->clear();
1304 $page = WikiPage::factory( $this->title );
1305 if( !$page->exists() ) {
1306 # must create the page...
1307 $pageId = $page->insertOn( $dbw );
1308 $created = true;
1309 $oldcountable = null;
1310 } else {
1311 $pageId = $page->getId();
1312 $created = false;
1314 $prior = $dbw->selectField( 'revision', '1',
1315 array( 'rev_page' => $pageId,
1316 'rev_timestamp' => $dbw->timestamp( $this->timestamp ),
1317 'rev_user_text' => $userText,
1318 'rev_comment' => $this->getComment() ),
1319 __METHOD__
1321 if( $prior ) {
1322 // @todo FIXME: This could fail slightly for multiple matches :P
1323 wfDebug( __METHOD__ . ": skipping existing revision for [[" .
1324 $this->title->getPrefixedText() . "]], timestamp " . $this->timestamp . "\n" );
1325 return false;
1327 $oldcountable = $page->isCountable();
1330 # @todo FIXME: Use original rev_id optionally (better for backups)
1331 # Insert the row
1332 $revision = new Revision( array(
1333 'page' => $pageId,
1334 'text' => $this->getText(),
1335 'comment' => $this->getComment(),
1336 'user' => $userId,
1337 'user_text' => $userText,
1338 'timestamp' => $this->timestamp,
1339 'minor_edit' => $this->minor,
1340 ) );
1341 $revision->insertOn( $dbw );
1342 $changed = $page->updateIfNewerOn( $dbw, $revision );
1344 if ( $changed !== false && !$this->mNoUpdates ) {
1345 wfDebug( __METHOD__ . ": running updates\n" );
1346 $page->doEditUpdates( $revision, $userObj, array( 'created' => $created, 'oldcountable' => $oldcountable ) );
1349 return true;
1353 * @return mixed
1355 function importLogItem() {
1356 $dbw = wfGetDB( DB_MASTER );
1357 # @todo FIXME: This will not record autoblocks
1358 if( !$this->getTitle() ) {
1359 wfDebug( __METHOD__ . ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1360 $this->timestamp . "\n" );
1361 return;
1363 # Check if it exists already
1364 // @todo FIXME: Use original log ID (better for backups)
1365 $prior = $dbw->selectField( 'logging', '1',
1366 array( 'log_type' => $this->getType(),
1367 'log_action' => $this->getAction(),
1368 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
1369 'log_namespace' => $this->getTitle()->getNamespace(),
1370 'log_title' => $this->getTitle()->getDBkey(),
1371 'log_comment' => $this->getComment(),
1372 #'log_user_text' => $this->user_text,
1373 'log_params' => $this->params ),
1374 __METHOD__
1376 // @todo FIXME: This could fail slightly for multiple matches :P
1377 if( $prior ) {
1378 wfDebug( __METHOD__ . ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp " .
1379 $this->timestamp . "\n" );
1380 return;
1382 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1383 $data = array(
1384 'log_id' => $log_id,
1385 'log_type' => $this->type,
1386 'log_action' => $this->action,
1387 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
1388 'log_user' => User::idFromName( $this->user_text ),
1389 #'log_user_text' => $this->user_text,
1390 'log_namespace' => $this->getTitle()->getNamespace(),
1391 'log_title' => $this->getTitle()->getDBkey(),
1392 'log_comment' => $this->getComment(),
1393 'log_params' => $this->params
1395 $dbw->insert( 'logging', $data, __METHOD__ );
1399 * @return bool
1401 function importUpload() {
1402 # Construct a file
1403 $archiveName = $this->getArchiveName();
1404 if ( $archiveName ) {
1405 wfDebug( __METHOD__ . "Importing archived file as $archiveName\n" );
1406 $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
1407 RepoGroup::singleton()->getLocalRepo(), $archiveName );
1408 } else {
1409 $file = wfLocalFile( $this->getTitle() );
1410 wfDebug( __METHOD__ . 'Importing new file as ' . $file->getName() . "\n" );
1411 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1412 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1413 $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
1414 RepoGroup::singleton()->getLocalRepo(), $archiveName );
1415 wfDebug( __METHOD__ . "File already exists; importing as $archiveName\n" );
1418 if( !$file ) {
1419 wfDebug( __METHOD__ . ': Bad file for ' . $this->getTitle() . "\n" );
1420 return false;
1423 # Get the file source or download if necessary
1424 $source = $this->getFileSrc();
1425 $flags = $this->isTempSrc() ? File::DELETE_SOURCE : 0;
1426 if ( !$source ) {
1427 $source = $this->downloadSource();
1428 $flags |= File::DELETE_SOURCE;
1430 if( !$source ) {
1431 wfDebug( __METHOD__ . ": Could not fetch remote file.\n" );
1432 return false;
1434 $sha1 = $this->getSha1();
1435 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1436 if ( $flags & File::DELETE_SOURCE ) {
1437 # Broken file; delete it if it is a temporary file
1438 unlink( $source );
1440 wfDebug( __METHOD__ . ": Corrupt file $source.\n" );
1441 return false;
1444 $user = User::newFromName( $this->user_text );
1446 # Do the actual upload
1447 if ( $archiveName ) {
1448 $status = $file->uploadOld( $source, $archiveName,
1449 $this->getTimestamp(), $this->getComment(), $user, $flags );
1450 } else {
1451 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1452 $flags, false, $this->getTimestamp(), $user );
1455 if ( $status->isGood() ) {
1456 wfDebug( __METHOD__ . ": Succesful\n" );
1457 return true;
1458 } else {
1459 wfDebug( __METHOD__ . ': failed: ' . $status->getXml() . "\n" );
1460 return false;
1465 * @return bool|string
1467 function downloadSource() {
1468 global $wgEnableUploads;
1469 if( !$wgEnableUploads ) {
1470 return false;
1473 $tempo = tempnam( wfTempDir(), 'download' );
1474 $f = fopen( $tempo, 'wb' );
1475 if( !$f ) {
1476 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1477 return false;
1480 // @todo FIXME!
1481 $src = $this->getSrc();
1482 $data = Http::get( $src );
1483 if( !$data ) {
1484 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1485 fclose( $f );
1486 unlink( $tempo );
1487 return false;
1490 fwrite( $f, $data );
1491 fclose( $f );
1493 return $tempo;
1499 * @todo document (e.g. one-sentence class description).
1500 * @ingroup SpecialPage
1502 class ImportStringSource {
1503 function __construct( $string ) {
1504 $this->mString = $string;
1505 $this->mRead = false;
1509 * @return bool
1511 function atEnd() {
1512 return $this->mRead;
1516 * @return bool|string
1518 function readChunk() {
1519 if( $this->atEnd() ) {
1520 return false;
1522 $this->mRead = true;
1523 return $this->mString;
1528 * @todo document (e.g. one-sentence class description).
1529 * @ingroup SpecialPage
1531 class ImportStreamSource {
1532 function __construct( $handle ) {
1533 $this->mHandle = $handle;
1537 * @return bool
1539 function atEnd() {
1540 return feof( $this->mHandle );
1544 * @return string
1546 function readChunk() {
1547 return fread( $this->mHandle, 32768 );
1551 * @param $filename string
1552 * @return Status
1554 static function newFromFile( $filename ) {
1555 wfSuppressWarnings();
1556 $file = fopen( $filename, 'rt' );
1557 wfRestoreWarnings();
1558 if( !$file ) {
1559 return Status::newFatal( "importcantopen" );
1561 return Status::newGood( new ImportStreamSource( $file ) );
1565 * @param $fieldname string
1566 * @return Status
1568 static function newFromUpload( $fieldname = "xmlimport" ) {
1569 $upload =& $_FILES[$fieldname];
1571 if( !isset( $upload ) || !$upload['name'] ) {
1572 return Status::newFatal( 'importnofile' );
1574 if( !empty( $upload['error'] ) ) {
1575 switch($upload['error']){
1576 case 1: # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1577 return Status::newFatal( 'importuploaderrorsize' );
1578 case 2: # The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
1579 return Status::newFatal( 'importuploaderrorsize' );
1580 case 3: # The uploaded file was only partially uploaded
1581 return Status::newFatal( 'importuploaderrorpartial' );
1582 case 6: #Missing a temporary folder.
1583 return Status::newFatal( 'importuploaderrortemp' );
1584 # case else: # Currently impossible
1588 $fname = $upload['tmp_name'];
1589 if( is_uploaded_file( $fname ) ) {
1590 return ImportStreamSource::newFromFile( $fname );
1591 } else {
1592 return Status::newFatal( 'importnofile' );
1597 * @param $url
1598 * @param $method string
1599 * @return Status
1601 static function newFromURL( $url, $method = 'GET' ) {
1602 wfDebug( __METHOD__ . ": opening $url\n" );
1603 # Use the standard HTTP fetch function; it times out
1604 # quicker and sorts out user-agent problems which might
1605 # otherwise prevent importing from large sites, such
1606 # as the Wikimedia cluster, etc.
1607 $data = Http::request( $method, $url, array( 'followRedirects' => true ) );
1608 if( $data !== false ) {
1609 $file = tmpfile();
1610 fwrite( $file, $data );
1611 fflush( $file );
1612 fseek( $file, 0 );
1613 return Status::newGood( new ImportStreamSource( $file ) );
1614 } else {
1615 return Status::newFatal( 'importcantopen' );
1620 * @param $interwiki
1621 * @param $page
1622 * @param $history bool
1623 * @param $templates bool
1624 * @param $pageLinkDepth int
1625 * @return Status
1627 public static function newFromInterwiki( $interwiki, $page, $history = false, $templates = false, $pageLinkDepth = 0 ) {
1628 if( $page == '' ) {
1629 return Status::newFatal( 'import-noarticle' );
1631 $link = Title::newFromText( "$interwiki:Special:Export/$page" );
1632 if( is_null( $link ) || $link->getInterwiki() == '' ) {
1633 return Status::newFatal( 'importbadinterwiki' );
1634 } else {
1635 $params = array();
1636 if ( $history ) $params['history'] = 1;
1637 if ( $templates ) $params['templates'] = 1;
1638 if ( $pageLinkDepth ) $params['pagelink-depth'] = $pageLinkDepth;
1639 $url = $link->getFullUrl( $params );
1640 # For interwikis, use POST to avoid redirects.
1641 return ImportStreamSource::newFromURL( $url, "POST" );