Merge "Remove messageTypes.inc and replace it by a hook"
[mediawiki.git] / includes / Import.php
blobf6e9032a94427cecb3336d5b20dcf0d60b0e8cdb
1 <?php
2 /**
3 * MediaWiki page data importer.
5 * Copyright © 2003,2005 Brion Vibber <brion@pobox.com>
6 * https://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 string $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 bool $debug
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 bool $noupdates
101 function setNoUpdates( $noupdates ) {
102 $this->mNoUpdates = $noupdates;
106 * Set a callback that displays notice messages
108 * @param callable $callback
109 * @return callable
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 callable $callback
118 * @return callable
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 callable $callback
133 * @return callable
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 callable $callback
144 * @return callable
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 callable $callback
155 * @return callable
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 callable $callback
166 * @return callable
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 callable $callback
177 * @return callable
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 null|int $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 null|string $rootpage
205 * @return Status
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 string $dir
238 public function setImageBasePath( $dir ) {
239 $this->mImageBasePath = $dir;
243 * @param bool $import
245 public function setImportUploads( $import ) {
246 $this->mImportUploads = $import;
250 * Default per-revision callback, performs the import.
251 * @param WikiRevision $revision
252 * @return bool
254 public function importRevision( $revision ) {
255 if ( !$revision->getContent()->getContentHandler()->canBeUsedOn( $revision->getTitle() ) ) {
256 $this->notice( 'import-error-bad-location',
257 $revision->getTitle()->getPrefixedText(),
258 $revision->getID(),
259 $revision->getModel(),
260 $revision->getFormat() );
262 return false;
265 try {
266 $dbw = wfGetDB( DB_MASTER );
267 return $dbw->deadlockLoop( array( $revision, 'importOldRevision' ) );
268 } catch ( MWContentSerializationException $ex ) {
269 $this->notice( 'import-error-unserialize',
270 $revision->getTitle()->getPrefixedText(),
271 $revision->getID(),
272 $revision->getModel(),
273 $revision->getFormat() );
276 return false;
280 * Default per-revision callback, performs the import.
281 * @param WikiRevision $rev
282 * @return bool
284 public function importLogItem( $rev ) {
285 $dbw = wfGetDB( DB_MASTER );
286 return $dbw->deadlockLoop( array( $rev, 'importLogItem' ) );
290 * Dummy for now...
291 * @param WikiRevision $revision
292 * @return bool
294 public function importUpload( $revision ) {
295 $dbw = wfGetDB( DB_MASTER );
296 return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
300 * Mostly for hook use
301 * @param Title $title
302 * @param string $origTitle
303 * @param int $revCount
304 * @param int $sRevCount
305 * @param array $pageInfo
306 * @return
308 public function finishImportPage( $title, $origTitle, $revCount, $sRevCount, $pageInfo ) {
309 $args = func_get_args();
310 return wfRunHooks( 'AfterImportPage', $args );
314 * Alternate per-revision callback, for debugging.
315 * @param WikiRevision $revision
317 public function debugRevisionHandler( &$revision ) {
318 $this->debug( "Got revision:" );
319 if ( is_object( $revision->title ) ) {
320 $this->debug( "-- Title: " . $revision->title->getPrefixedText() );
321 } else {
322 $this->debug( "-- Title: <invalid>" );
324 $this->debug( "-- User: " . $revision->user_text );
325 $this->debug( "-- Timestamp: " . $revision->timestamp );
326 $this->debug( "-- Comment: " . $revision->comment );
327 $this->debug( "-- Text: " . $revision->text );
331 * Notify the callback function when a new "<page>" is reached.
332 * @param Title $title
334 function pageCallback( $title ) {
335 if ( isset( $this->mPageCallback ) ) {
336 call_user_func( $this->mPageCallback, $title );
341 * Notify the callback function when a "</page>" is closed.
342 * @param Title $title
343 * @param Title $origTitle
344 * @param int $revCount
345 * @param int $sucCount Number of revisions for which callback returned true
346 * @param array $pageInfo Associative array of page information
348 private function pageOutCallback( $title, $origTitle, $revCount, $sucCount, $pageInfo ) {
349 if ( isset( $this->mPageOutCallback ) ) {
350 $args = func_get_args();
351 call_user_func_array( $this->mPageOutCallback, $args );
356 * Notify the callback function of a revision
357 * @param WikiRevision $revision
358 * @return bool|mixed
360 private function revisionCallback( $revision ) {
361 if ( isset( $this->mRevisionCallback ) ) {
362 return call_user_func_array( $this->mRevisionCallback,
363 array( $revision, $this ) );
364 } else {
365 return false;
370 * Notify the callback function of a new log item
371 * @param WikiRevision $revision
372 * @return bool|mixed
374 private function logItemCallback( $revision ) {
375 if ( isset( $this->mLogItemCallback ) ) {
376 return call_user_func_array( $this->mLogItemCallback,
377 array( $revision, $this ) );
378 } else {
379 return false;
384 * Shouldn't something like this be built-in to XMLReader?
385 * Fetches text contents of the current element, assuming
386 * no sub-elements or such scary things.
387 * @return string
388 * @access private
390 private function nodeContents() {
391 if ( $this->reader->isEmptyElement ) {
392 return "";
394 $buffer = "";
395 while ( $this->reader->read() ) {
396 switch ( $this->reader->nodeType ) {
397 case XmlReader::TEXT:
398 case XmlReader::SIGNIFICANT_WHITESPACE:
399 $buffer .= $this->reader->value;
400 break;
401 case XmlReader::END_ELEMENT:
402 return $buffer;
406 $this->reader->close();
407 return '';
410 # --------------
412 /** Left in for debugging */
413 private function dumpElement() {
414 static $lookup = null;
415 if ( !$lookup ) {
416 $xmlReaderConstants = array(
417 "NONE",
418 "ELEMENT",
419 "ATTRIBUTE",
420 "TEXT",
421 "CDATA",
422 "ENTITY_REF",
423 "ENTITY",
424 "PI",
425 "COMMENT",
426 "DOC",
427 "DOC_TYPE",
428 "DOC_FRAGMENT",
429 "NOTATION",
430 "WHITESPACE",
431 "SIGNIFICANT_WHITESPACE",
432 "END_ELEMENT",
433 "END_ENTITY",
434 "XML_DECLARATION",
436 $lookup = array();
438 foreach ( $xmlReaderConstants as $name ) {
439 $lookup[constant( "XmlReader::$name" )] = $name;
443 print var_dump(
444 $lookup[$this->reader->nodeType],
445 $this->reader->name,
446 $this->reader->value
447 ) . "\n\n";
451 * Primary entry point
452 * @throws MWException
453 * @return bool
455 public function doImport() {
457 // Calls to reader->read need to be wrapped in calls to
458 // libxml_disable_entity_loader() to avoid local file
459 // inclusion attacks (bug 46932).
460 $oldDisable = libxml_disable_entity_loader( true );
461 $this->reader->read();
463 if ( $this->reader->name != 'mediawiki' ) {
464 libxml_disable_entity_loader( $oldDisable );
465 throw new MWException( "Expected <mediawiki> tag, got " .
466 $this->reader->name );
468 $this->debug( "<mediawiki> tag is correct." );
470 $this->debug( "Starting primary dump processing loop." );
472 $keepReading = $this->reader->read();
473 $skip = false;
474 while ( $keepReading ) {
475 $tag = $this->reader->name;
476 $type = $this->reader->nodeType;
478 if ( !wfRunHooks( 'ImportHandleToplevelXMLTag', array( $this ) ) ) {
479 // Do nothing
480 } elseif ( $tag == 'mediawiki' && $type == XmlReader::END_ELEMENT ) {
481 break;
482 } elseif ( $tag == 'siteinfo' ) {
483 $this->handleSiteInfo();
484 } elseif ( $tag == 'page' ) {
485 $this->handlePage();
486 } elseif ( $tag == 'logitem' ) {
487 $this->handleLogItem();
488 } elseif ( $tag != '#text' ) {
489 $this->warn( "Unhandled top-level XML tag $tag" );
491 $skip = true;
494 if ( $skip ) {
495 $keepReading = $this->reader->next();
496 $skip = false;
497 $this->debug( "Skip" );
498 } else {
499 $keepReading = $this->reader->read();
503 libxml_disable_entity_loader( $oldDisable );
504 return true;
508 * @return bool
509 * @throws MWException
511 private function handleSiteInfo() {
512 // Site info is useful, but not actually used for dump imports.
513 // Includes a quick short-circuit to save performance.
514 if ( ! $this->mSiteInfoCallback ) {
515 $this->reader->next();
516 return true;
518 throw new MWException( "SiteInfo tag is not yet handled, do not set mSiteInfoCallback" );
521 private function handleLogItem() {
522 $this->debug( "Enter log item handler." );
523 $logInfo = array();
525 // Fields that can just be stuffed in the pageInfo object
526 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
527 'logtitle', 'params' );
529 while ( $this->reader->read() ) {
530 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
531 $this->reader->name == 'logitem' ) {
532 break;
535 $tag = $this->reader->name;
537 if ( !wfRunHooks( 'ImportHandleLogItemXMLTag', array(
538 $this, $logInfo
539 ) ) ) {
540 // Do nothing
541 } elseif ( in_array( $tag, $normalFields ) ) {
542 $logInfo[$tag] = $this->nodeContents();
543 } elseif ( $tag == 'contributor' ) {
544 $logInfo['contributor'] = $this->handleContributor();
545 } elseif ( $tag != '#text' ) {
546 $this->warn( "Unhandled log-item XML tag $tag" );
550 $this->processLogItem( $logInfo );
554 * @param array $logInfo
555 * @return bool|mixed
557 private function processLogItem( $logInfo ) {
558 $revision = new WikiRevision;
560 $revision->setID( $logInfo['id'] );
561 $revision->setType( $logInfo['type'] );
562 $revision->setAction( $logInfo['action'] );
563 $revision->setTimestamp( $logInfo['timestamp'] );
564 $revision->setParams( $logInfo['params'] );
565 $revision->setTitle( Title::newFromText( $logInfo['logtitle'] ) );
566 $revision->setNoUpdates( $this->mNoUpdates );
568 if ( isset( $logInfo['comment'] ) ) {
569 $revision->setComment( $logInfo['comment'] );
572 if ( isset( $logInfo['contributor']['ip'] ) ) {
573 $revision->setUserIP( $logInfo['contributor']['ip'] );
575 if ( isset( $logInfo['contributor']['username'] ) ) {
576 $revision->setUserName( $logInfo['contributor']['username'] );
579 return $this->logItemCallback( $revision );
582 private function handlePage() {
583 // Handle page data.
584 $this->debug( "Enter page handler." );
585 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
587 // Fields that can just be stuffed in the pageInfo object
588 $normalFields = array( 'title', 'id', 'redirect', 'restrictions' );
590 $skip = false;
591 $badTitle = false;
593 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
594 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
595 $this->reader->name == 'page' ) {
596 break;
599 $tag = $this->reader->name;
601 if ( $badTitle ) {
602 // The title is invalid, bail out of this page
603 $skip = true;
604 } elseif ( !wfRunHooks( 'ImportHandlePageXMLTag', array( $this,
605 &$pageInfo ) ) ) {
606 // Do nothing
607 } elseif ( in_array( $tag, $normalFields ) ) {
608 $pageInfo[$tag] = $this->nodeContents();
609 if ( $tag == 'title' ) {
610 $title = $this->processTitle( $pageInfo['title'] );
612 if ( !$title ) {
613 $badTitle = true;
614 $skip = true;
617 $this->pageCallback( $title );
618 list( $pageInfo['_title'], $origTitle ) = $title;
620 } elseif ( $tag == 'revision' ) {
621 $this->handleRevision( $pageInfo );
622 } elseif ( $tag == 'upload' ) {
623 $this->handleUpload( $pageInfo );
624 } elseif ( $tag != '#text' ) {
625 $this->warn( "Unhandled page XML tag $tag" );
626 $skip = true;
630 $this->pageOutCallback( $pageInfo['_title'], $origTitle,
631 $pageInfo['revisionCount'],
632 $pageInfo['successfulRevisionCount'],
633 $pageInfo );
637 * @param array $pageInfo
639 private function handleRevision( &$pageInfo ) {
640 $this->debug( "Enter revision handler" );
641 $revisionInfo = array();
643 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'model', 'format', 'text' );
645 $skip = false;
647 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
648 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
649 $this->reader->name == 'revision' ) {
650 break;
653 $tag = $this->reader->name;
655 if ( !wfRunHooks( 'ImportHandleRevisionXMLTag', array(
656 $this, $pageInfo, $revisionInfo
657 ) ) ) {
658 // Do nothing
659 } elseif ( in_array( $tag, $normalFields ) ) {
660 $revisionInfo[$tag] = $this->nodeContents();
661 } elseif ( $tag == 'contributor' ) {
662 $revisionInfo['contributor'] = $this->handleContributor();
663 } elseif ( $tag != '#text' ) {
664 $this->warn( "Unhandled revision XML tag $tag" );
665 $skip = true;
669 $pageInfo['revisionCount']++;
670 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
671 $pageInfo['successfulRevisionCount']++;
676 * @param array $pageInfo
677 * @param array $revisionInfo
678 * @return bool|mixed
680 private function processRevision( $pageInfo, $revisionInfo ) {
681 $revision = new WikiRevision;
683 if ( isset( $revisionInfo['id'] ) ) {
684 $revision->setID( $revisionInfo['id'] );
686 if ( isset( $revisionInfo['text'] ) ) {
687 $revision->setText( $revisionInfo['text'] );
689 if ( isset( $revisionInfo['model'] ) ) {
690 $revision->setModel( $revisionInfo['model'] );
692 if ( isset( $revisionInfo['format'] ) ) {
693 $revision->setFormat( $revisionInfo['format'] );
695 $revision->setTitle( $pageInfo['_title'] );
697 if ( isset( $revisionInfo['timestamp'] ) ) {
698 $revision->setTimestamp( $revisionInfo['timestamp'] );
699 } else {
700 $revision->setTimestamp( wfTimestampNow() );
703 if ( isset( $revisionInfo['comment'] ) ) {
704 $revision->setComment( $revisionInfo['comment'] );
707 if ( isset( $revisionInfo['minor'] ) ) {
708 $revision->setMinor( true );
710 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
711 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
713 if ( isset( $revisionInfo['contributor']['username'] ) ) {
714 $revision->setUserName( $revisionInfo['contributor']['username'] );
716 $revision->setNoUpdates( $this->mNoUpdates );
718 return $this->revisionCallback( $revision );
722 * @param array $pageInfo
723 * @return mixed
725 private function handleUpload( &$pageInfo ) {
726 $this->debug( "Enter upload handler" );
727 $uploadInfo = array();
729 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
730 'src', 'size', 'sha1base36', 'archivename', 'rel' );
732 $skip = false;
734 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
735 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
736 $this->reader->name == 'upload' ) {
737 break;
740 $tag = $this->reader->name;
742 if ( !wfRunHooks( 'ImportHandleUploadXMLTag', array(
743 $this, $pageInfo
744 ) ) ) {
745 // Do nothing
746 } elseif ( in_array( $tag, $normalFields ) ) {
747 $uploadInfo[$tag] = $this->nodeContents();
748 } elseif ( $tag == 'contributor' ) {
749 $uploadInfo['contributor'] = $this->handleContributor();
750 } elseif ( $tag == 'contents' ) {
751 $contents = $this->nodeContents();
752 $encoding = $this->reader->getAttribute( 'encoding' );
753 if ( $encoding === 'base64' ) {
754 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
755 $uploadInfo['isTempSrc'] = true;
757 } elseif ( $tag != '#text' ) {
758 $this->warn( "Unhandled upload XML tag $tag" );
759 $skip = true;
763 if ( $this->mImageBasePath && isset( $uploadInfo['rel'] ) ) {
764 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
765 if ( file_exists( $path ) ) {
766 $uploadInfo['fileSrc'] = $path;
767 $uploadInfo['isTempSrc'] = false;
771 if ( $this->mImportUploads ) {
772 return $this->processUpload( $pageInfo, $uploadInfo );
777 * @param string $contents
778 * @return string
780 private function dumpTemp( $contents ) {
781 $filename = tempnam( wfTempDir(), 'importupload' );
782 file_put_contents( $filename, $contents );
783 return $filename;
787 * @param array $pageInfo
788 * @param array $uploadInfo
789 * @return mixed
791 private function processUpload( $pageInfo, $uploadInfo ) {
792 $revision = new WikiRevision;
793 $text = isset( $uploadInfo['text'] ) ? $uploadInfo['text'] : '';
795 $revision->setTitle( $pageInfo['_title'] );
796 $revision->setID( $pageInfo['id'] );
797 $revision->setTimestamp( $uploadInfo['timestamp'] );
798 $revision->setText( $text );
799 $revision->setFilename( $uploadInfo['filename'] );
800 if ( isset( $uploadInfo['archivename'] ) ) {
801 $revision->setArchiveName( $uploadInfo['archivename'] );
803 $revision->setSrc( $uploadInfo['src'] );
804 if ( isset( $uploadInfo['fileSrc'] ) ) {
805 $revision->setFileSrc( $uploadInfo['fileSrc'],
806 !empty( $uploadInfo['isTempSrc'] ) );
808 if ( isset( $uploadInfo['sha1base36'] ) ) {
809 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
811 $revision->setSize( intval( $uploadInfo['size'] ) );
812 $revision->setComment( $uploadInfo['comment'] );
814 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
815 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
817 if ( isset( $uploadInfo['contributor']['username'] ) ) {
818 $revision->setUserName( $uploadInfo['contributor']['username'] );
820 $revision->setNoUpdates( $this->mNoUpdates );
822 return call_user_func( $this->mUploadCallback, $revision );
826 * @return array
828 private function handleContributor() {
829 $fields = array( 'id', 'ip', 'username' );
830 $info = array();
832 while ( $this->reader->read() ) {
833 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
834 $this->reader->name == 'contributor' ) {
835 break;
838 $tag = $this->reader->name;
840 if ( in_array( $tag, $fields ) ) {
841 $info[$tag] = $this->nodeContents();
845 return $info;
849 * @param string $text
850 * @return array|bool
852 private function processTitle( $text ) {
853 global $wgCommandLineMode;
855 $workTitle = $text;
856 $origTitle = Title::newFromText( $workTitle );
858 if ( !is_null( $this->mTargetNamespace ) && !is_null( $origTitle ) ) {
859 # makeTitleSafe, because $origTitle can have a interwiki (different setting of interwiki map)
860 # and than dbKey can begin with a lowercase char
861 $title = Title::makeTitleSafe( $this->mTargetNamespace,
862 $origTitle->getDBkey() );
863 } else {
864 if ( !is_null( $this->mTargetRootPage ) ) {
865 $workTitle = $this->mTargetRootPage . '/' . $workTitle;
867 $title = Title::newFromText( $workTitle );
870 if ( is_null( $title ) ) {
871 # Invalid page title? Ignore the page
872 $this->notice( 'import-error-invalid', $workTitle );
873 return false;
874 } elseif ( $title->isExternal() ) {
875 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
876 return false;
877 } elseif ( !$title->canExist() ) {
878 $this->notice( 'import-error-special', $title->getPrefixedText() );
879 return false;
880 } elseif ( !$title->userCan( 'edit' ) && !$wgCommandLineMode ) {
881 # Do not import if the importing wiki user cannot edit this page
882 $this->notice( 'import-error-edit', $title->getPrefixedText() );
883 return false;
884 } elseif ( !$title->exists() && !$title->userCan( 'create' ) && !$wgCommandLineMode ) {
885 # Do not import if the importing wiki user cannot create this page
886 $this->notice( 'import-error-create', $title->getPrefixedText() );
887 return false;
890 return array( $title, $origTitle );
894 /** This is a horrible hack used to keep source compatibility */
895 class UploadSourceAdapter {
896 static $sourceRegistrations = array();
898 private $mSource;
899 private $mBuffer;
900 private $mPosition;
903 * @param string $source
904 * @return string
906 static function registerSource( $source ) {
907 $id = wfRandomString();
909 self::$sourceRegistrations[$id] = $source;
911 return $id;
915 * @param string $path
916 * @param string $mode
917 * @param array $options
918 * @param string $opened_path
919 * @return bool
921 function stream_open( $path, $mode, $options, &$opened_path ) {
922 $url = parse_url( $path );
923 $id = $url['host'];
925 if ( !isset( self::$sourceRegistrations[$id] ) ) {
926 return false;
929 $this->mSource = self::$sourceRegistrations[$id];
931 return true;
935 * @param int $count
936 * @return string
938 function stream_read( $count ) {
939 $return = '';
940 $leave = false;
942 while ( !$leave && !$this->mSource->atEnd() &&
943 strlen( $this->mBuffer ) < $count ) {
944 $read = $this->mSource->readChunk();
946 if ( !strlen( $read ) ) {
947 $leave = true;
950 $this->mBuffer .= $read;
953 if ( strlen( $this->mBuffer ) ) {
954 $return = substr( $this->mBuffer, 0, $count );
955 $this->mBuffer = substr( $this->mBuffer, $count );
958 $this->mPosition += strlen( $return );
960 return $return;
964 * @param string $data
965 * @return bool
967 function stream_write( $data ) {
968 return false;
972 * @return mixed
974 function stream_tell() {
975 return $this->mPosition;
979 * @return bool
981 function stream_eof() {
982 return $this->mSource->atEnd();
986 * @return array
988 function url_stat() {
989 $result = array();
991 $result['dev'] = $result[0] = 0;
992 $result['ino'] = $result[1] = 0;
993 $result['mode'] = $result[2] = 0;
994 $result['nlink'] = $result[3] = 0;
995 $result['uid'] = $result[4] = 0;
996 $result['gid'] = $result[5] = 0;
997 $result['rdev'] = $result[6] = 0;
998 $result['size'] = $result[7] = 0;
999 $result['atime'] = $result[8] = 0;
1000 $result['mtime'] = $result[9] = 0;
1001 $result['ctime'] = $result[10] = 0;
1002 $result['blksize'] = $result[11] = 0;
1003 $result['blocks'] = $result[12] = 0;
1005 return $result;
1009 class XMLReader2 extends XMLReader {
1012 * @return bool|string
1014 function nodeContents() {
1015 if ( $this->isEmptyElement ) {
1016 return "";
1018 $buffer = "";
1019 while ( $this->read() ) {
1020 switch ( $this->nodeType ) {
1021 case XmlReader::TEXT:
1022 case XmlReader::SIGNIFICANT_WHITESPACE:
1023 $buffer .= $this->value;
1024 break;
1025 case XmlReader::END_ELEMENT:
1026 return $buffer;
1029 return $this->close();
1034 * @todo document (e.g. one-sentence class description).
1035 * @ingroup SpecialPage
1037 class WikiRevision {
1038 var $importer = null;
1041 * @var Title
1043 var $title = null;
1044 var $id = 0;
1045 var $timestamp = "20010115000000";
1046 var $user = 0;
1047 var $user_text = "";
1048 var $model = null;
1049 var $format = null;
1050 var $text = "";
1051 var $content = null;
1052 var $comment = "";
1053 var $minor = false;
1054 var $type = "";
1055 var $action = "";
1056 var $params = "";
1057 var $fileSrc = '';
1058 var $sha1base36 = false;
1059 var $isTemp = false;
1060 var $archiveName = '';
1061 var $fileIsTemp;
1062 private $mNoUpdates = false;
1065 * @param Title $title
1066 * @throws MWException
1068 function setTitle( $title ) {
1069 if ( is_object( $title ) ) {
1070 $this->title = $title;
1071 } elseif ( is_null( $title ) ) {
1072 throw new MWException( "WikiRevision given a null title in import. You may need to adjust \$wgLegalTitleChars." );
1073 } else {
1074 throw new MWException( "WikiRevision given non-object title in import." );
1079 * @param int $id
1081 function setID( $id ) {
1082 $this->id = $id;
1086 * @param string $ts
1088 function setTimestamp( $ts ) {
1089 # 2003-08-05T18:30:02Z
1090 $this->timestamp = wfTimestamp( TS_MW, $ts );
1094 * @param string $user
1096 function setUsername( $user ) {
1097 $this->user_text = $user;
1101 * @param string $ip
1103 function setUserIP( $ip ) {
1104 $this->user_text = $ip;
1108 * @param string $model
1110 function setModel( $model ) {
1111 $this->model = $model;
1115 * @param string $format
1117 function setFormat( $format ) {
1118 $this->format = $format;
1122 * @param string $text
1124 function setText( $text ) {
1125 $this->text = $text;
1129 * @param string $text
1131 function setComment( $text ) {
1132 $this->comment = $text;
1136 * @param bool $minor
1138 function setMinor( $minor ) {
1139 $this->minor = (bool)$minor;
1143 * @param mixed $src
1145 function setSrc( $src ) {
1146 $this->src = $src;
1150 * @param string $src
1151 * @param bool $isTemp
1153 function setFileSrc( $src, $isTemp ) {
1154 $this->fileSrc = $src;
1155 $this->fileIsTemp = $isTemp;
1159 * @param string $sha1base36
1161 function setSha1Base36( $sha1base36 ) {
1162 $this->sha1base36 = $sha1base36;
1166 * @param string $filename
1168 function setFilename( $filename ) {
1169 $this->filename = $filename;
1173 * @param string $archiveName
1175 function setArchiveName( $archiveName ) {
1176 $this->archiveName = $archiveName;
1180 * @param int $size
1182 function setSize( $size ) {
1183 $this->size = intval( $size );
1187 * @param string $type
1189 function setType( $type ) {
1190 $this->type = $type;
1194 * @param string $action
1196 function setAction( $action ) {
1197 $this->action = $action;
1201 * @param array $params
1203 function setParams( $params ) {
1204 $this->params = $params;
1208 * @param bool $noupdates
1210 public function setNoUpdates( $noupdates ) {
1211 $this->mNoUpdates = $noupdates;
1215 * @return Title
1217 function getTitle() {
1218 return $this->title;
1222 * @return int
1224 function getID() {
1225 return $this->id;
1229 * @return string
1231 function getTimestamp() {
1232 return $this->timestamp;
1236 * @return string
1238 function getUser() {
1239 return $this->user_text;
1243 * @return string
1245 * @deprecated Since 1.21, use getContent() instead.
1247 function getText() {
1248 ContentHandler::deprecated( __METHOD__, '1.21' );
1250 return $this->text;
1254 * @return Content
1256 function getContent() {
1257 if ( is_null( $this->content ) ) {
1258 $this->content =
1259 ContentHandler::makeContent(
1260 $this->text,
1261 $this->getTitle(),
1262 $this->getModel(),
1263 $this->getFormat()
1267 return $this->content;
1271 * @return string
1273 function getModel() {
1274 if ( is_null( $this->model ) ) {
1275 $this->model = $this->getTitle()->getContentModel();
1278 return $this->model;
1282 * @return string
1284 function getFormat() {
1285 if ( is_null( $this->model ) ) {
1286 $this->format = ContentHandler::getForTitle( $this->getTitle() )->getDefaultFormat();
1289 return $this->format;
1293 * @return string
1295 function getComment() {
1296 return $this->comment;
1300 * @return bool
1302 function getMinor() {
1303 return $this->minor;
1307 * @return mixed
1309 function getSrc() {
1310 return $this->src;
1314 * @return bool|string
1316 function getSha1() {
1317 if ( $this->sha1base36 ) {
1318 return wfBaseConvert( $this->sha1base36, 36, 16 );
1320 return false;
1324 * @return string
1326 function getFileSrc() {
1327 return $this->fileSrc;
1331 * @return bool
1333 function isTempSrc() {
1334 return $this->isTemp;
1338 * @return mixed
1340 function getFilename() {
1341 return $this->filename;
1345 * @return string
1347 function getArchiveName() {
1348 return $this->archiveName;
1352 * @return mixed
1354 function getSize() {
1355 return $this->size;
1359 * @return string
1361 function getType() {
1362 return $this->type;
1366 * @return string
1368 function getAction() {
1369 return $this->action;
1373 * @return string
1375 function getParams() {
1376 return $this->params;
1380 * @return bool
1382 function importOldRevision() {
1383 $dbw = wfGetDB( DB_MASTER );
1385 # Sneak a single revision into place
1386 $user = User::newFromName( $this->getUser() );
1387 if ( $user ) {
1388 $userId = intval( $user->getId() );
1389 $userText = $user->getName();
1390 $userObj = $user;
1391 } else {
1392 $userId = 0;
1393 $userText = $this->getUser();
1394 $userObj = new User;
1397 // avoid memory leak...?
1398 $linkCache = LinkCache::singleton();
1399 $linkCache->clear();
1401 $page = WikiPage::factory( $this->title );
1402 if ( !$page->exists() ) {
1403 # must create the page...
1404 $pageId = $page->insertOn( $dbw );
1405 $created = true;
1406 $oldcountable = null;
1407 } else {
1408 $pageId = $page->getId();
1409 $created = false;
1411 $prior = $dbw->selectField( 'revision', '1',
1412 array( 'rev_page' => $pageId,
1413 'rev_timestamp' => $dbw->timestamp( $this->timestamp ),
1414 'rev_user_text' => $userText,
1415 'rev_comment' => $this->getComment() ),
1416 __METHOD__
1418 if ( $prior ) {
1419 // @todo FIXME: This could fail slightly for multiple matches :P
1420 wfDebug( __METHOD__ . ": skipping existing revision for [[" .
1421 $this->title->getPrefixedText() . "]], timestamp " . $this->timestamp . "\n" );
1422 return false;
1424 $oldcountable = $page->isCountable();
1427 # @todo FIXME: Use original rev_id optionally (better for backups)
1428 # Insert the row
1429 $revision = new Revision( array(
1430 'title' => $this->title,
1431 'page' => $pageId,
1432 'content_model' => $this->getModel(),
1433 'content_format' => $this->getFormat(),
1434 'text' => $this->getContent()->serialize( $this->getFormat() ), //XXX: just set 'content' => $this->getContent()?
1435 'comment' => $this->getComment(),
1436 'user' => $userId,
1437 'user_text' => $userText,
1438 'timestamp' => $this->timestamp,
1439 'minor_edit' => $this->minor,
1440 ) );
1441 $revision->insertOn( $dbw );
1442 $changed = $page->updateIfNewerOn( $dbw, $revision );
1444 if ( $changed !== false && !$this->mNoUpdates ) {
1445 wfDebug( __METHOD__ . ": running updates\n" );
1446 $page->doEditUpdates( $revision, $userObj, array( 'created' => $created, 'oldcountable' => $oldcountable ) );
1449 return true;
1453 * @return mixed
1455 function importLogItem() {
1456 $dbw = wfGetDB( DB_MASTER );
1457 # @todo FIXME: This will not record autoblocks
1458 if ( !$this->getTitle() ) {
1459 wfDebug( __METHOD__ . ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1460 $this->timestamp . "\n" );
1461 return;
1463 # Check if it exists already
1464 // @todo FIXME: Use original log ID (better for backups)
1465 $prior = $dbw->selectField( 'logging', '1',
1466 array( 'log_type' => $this->getType(),
1467 'log_action' => $this->getAction(),
1468 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
1469 'log_namespace' => $this->getTitle()->getNamespace(),
1470 'log_title' => $this->getTitle()->getDBkey(),
1471 'log_comment' => $this->getComment(),
1472 #'log_user_text' => $this->user_text,
1473 'log_params' => $this->params ),
1474 __METHOD__
1476 // @todo FIXME: This could fail slightly for multiple matches :P
1477 if ( $prior ) {
1478 wfDebug( __METHOD__ . ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp " .
1479 $this->timestamp . "\n" );
1480 return;
1482 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1483 $data = array(
1484 'log_id' => $log_id,
1485 'log_type' => $this->type,
1486 'log_action' => $this->action,
1487 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
1488 'log_user' => User::idFromName( $this->user_text ),
1489 #'log_user_text' => $this->user_text,
1490 'log_namespace' => $this->getTitle()->getNamespace(),
1491 'log_title' => $this->getTitle()->getDBkey(),
1492 'log_comment' => $this->getComment(),
1493 'log_params' => $this->params
1495 $dbw->insert( 'logging', $data, __METHOD__ );
1499 * @return bool
1501 function importUpload() {
1502 # Construct a file
1503 $archiveName = $this->getArchiveName();
1504 if ( $archiveName ) {
1505 wfDebug( __METHOD__ . "Importing archived file as $archiveName\n" );
1506 $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
1507 RepoGroup::singleton()->getLocalRepo(), $archiveName );
1508 } else {
1509 $file = wfLocalFile( $this->getTitle() );
1510 wfDebug( __METHOD__ . 'Importing new file as ' . $file->getName() . "\n" );
1511 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1512 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1513 $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
1514 RepoGroup::singleton()->getLocalRepo(), $archiveName );
1515 wfDebug( __METHOD__ . "File already exists; importing as $archiveName\n" );
1518 if ( !$file ) {
1519 wfDebug( __METHOD__ . ': Bad file for ' . $this->getTitle() . "\n" );
1520 return false;
1523 # Get the file source or download if necessary
1524 $source = $this->getFileSrc();
1525 $flags = $this->isTempSrc() ? File::DELETE_SOURCE : 0;
1526 if ( !$source ) {
1527 $source = $this->downloadSource();
1528 $flags |= File::DELETE_SOURCE;
1530 if ( !$source ) {
1531 wfDebug( __METHOD__ . ": Could not fetch remote file.\n" );
1532 return false;
1534 $sha1 = $this->getSha1();
1535 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1536 if ( $flags & File::DELETE_SOURCE ) {
1537 # Broken file; delete it if it is a temporary file
1538 unlink( $source );
1540 wfDebug( __METHOD__ . ": Corrupt file $source.\n" );
1541 return false;
1544 $user = User::newFromName( $this->user_text );
1546 # Do the actual upload
1547 if ( $archiveName ) {
1548 $status = $file->uploadOld( $source, $archiveName,
1549 $this->getTimestamp(), $this->getComment(), $user, $flags );
1550 } else {
1551 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1552 $flags, false, $this->getTimestamp(), $user );
1555 if ( $status->isGood() ) {
1556 wfDebug( __METHOD__ . ": Successful\n" );
1557 return true;
1558 } else {
1559 wfDebug( __METHOD__ . ': failed: ' . $status->getXml() . "\n" );
1560 return false;
1565 * @return bool|string
1567 function downloadSource() {
1568 global $wgEnableUploads;
1569 if ( !$wgEnableUploads ) {
1570 return false;
1573 $tempo = tempnam( wfTempDir(), 'download' );
1574 $f = fopen( $tempo, 'wb' );
1575 if ( !$f ) {
1576 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1577 return false;
1580 // @todo FIXME!
1581 $src = $this->getSrc();
1582 $data = Http::get( $src );
1583 if ( !$data ) {
1584 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1585 fclose( $f );
1586 unlink( $tempo );
1587 return false;
1590 fwrite( $f, $data );
1591 fclose( $f );
1593 return $tempo;
1599 * @todo document (e.g. one-sentence class description).
1600 * @ingroup SpecialPage
1602 class ImportStringSource {
1603 function __construct( $string ) {
1604 $this->mString = $string;
1605 $this->mRead = false;
1609 * @return bool
1611 function atEnd() {
1612 return $this->mRead;
1616 * @return bool|string
1618 function readChunk() {
1619 if ( $this->atEnd() ) {
1620 return false;
1622 $this->mRead = true;
1623 return $this->mString;
1628 * @todo document (e.g. one-sentence class description).
1629 * @ingroup SpecialPage
1631 class ImportStreamSource {
1632 function __construct( $handle ) {
1633 $this->mHandle = $handle;
1637 * @return bool
1639 function atEnd() {
1640 return feof( $this->mHandle );
1644 * @return string
1646 function readChunk() {
1647 return fread( $this->mHandle, 32768 );
1651 * @param string $filename
1652 * @return Status
1654 static function newFromFile( $filename ) {
1655 wfSuppressWarnings();
1656 $file = fopen( $filename, 'rt' );
1657 wfRestoreWarnings();
1658 if ( !$file ) {
1659 return Status::newFatal( "importcantopen" );
1661 return Status::newGood( new ImportStreamSource( $file ) );
1665 * @param string $fieldname
1666 * @return Status
1668 static function newFromUpload( $fieldname = "xmlimport" ) {
1669 $upload =& $_FILES[$fieldname];
1671 if ( $upload === null || !$upload['name'] ) {
1672 return Status::newFatal( 'importnofile' );
1674 if ( !empty( $upload['error'] ) ) {
1675 switch ( $upload['error'] ) {
1676 case 1: # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1677 return Status::newFatal( 'importuploaderrorsize' );
1678 case 2: # The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
1679 return Status::newFatal( 'importuploaderrorsize' );
1680 case 3: # The uploaded file was only partially uploaded
1681 return Status::newFatal( 'importuploaderrorpartial' );
1682 case 6: #Missing a temporary folder.
1683 return Status::newFatal( 'importuploaderrortemp' );
1684 # case else: # Currently impossible
1688 $fname = $upload['tmp_name'];
1689 if ( is_uploaded_file( $fname ) ) {
1690 return ImportStreamSource::newFromFile( $fname );
1691 } else {
1692 return Status::newFatal( 'importnofile' );
1697 * @param string $url
1698 * @param string $method
1699 * @return Status
1701 static function newFromURL( $url, $method = 'GET' ) {
1702 wfDebug( __METHOD__ . ": opening $url\n" );
1703 # Use the standard HTTP fetch function; it times out
1704 # quicker and sorts out user-agent problems which might
1705 # otherwise prevent importing from large sites, such
1706 # as the Wikimedia cluster, etc.
1707 $data = Http::request( $method, $url, array( 'followRedirects' => true ) );
1708 if ( $data !== false ) {
1709 $file = tmpfile();
1710 fwrite( $file, $data );
1711 fflush( $file );
1712 fseek( $file, 0 );
1713 return Status::newGood( new ImportStreamSource( $file ) );
1714 } else {
1715 return Status::newFatal( 'importcantopen' );
1720 * @param string $interwiki
1721 * @param string $page
1722 * @param bool $history
1723 * @param bool $templates
1724 * @param int $pageLinkDepth
1725 * @return Status
1727 public static function newFromInterwiki( $interwiki, $page, $history = false, $templates = false, $pageLinkDepth = 0 ) {
1728 if ( $page == '' ) {
1729 return Status::newFatal( 'import-noarticle' );
1731 $link = Title::newFromText( "$interwiki:Special:Export/$page" );
1732 if ( is_null( $link ) || !$link->isExternal() ) {
1733 return Status::newFatal( 'importbadinterwiki' );
1734 } else {
1735 $params = array();
1736 if ( $history ) {
1737 $params['history'] = 1;
1739 if ( $templates ) {
1740 $params['templates'] = 1;
1742 if ( $pageLinkDepth ) {
1743 $params['pagelink-depth'] = $pageLinkDepth;
1745 $url = $link->getFullURL( $params );
1746 # For interwikis, use POST to avoid redirects.
1747 return ImportStreamSource::newFromURL( $url, "POST" );