Remove silly 'm' prefix from StubObject/DeprecatedGlobal members
[mediawiki.git] / includes / Import.php
blob59fa58371c29cde85ad2a04eaae47e976b4231d9
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 /**
64 * @return null|XMLReader
66 public function getReader() {
67 return $this->reader;
70 public function throwXmlError( $err ) {
71 $this->debug( "FAILURE: $err" );
72 wfDebug( "WikiImporter XML error: $err\n" );
75 public function debug( $data ) {
76 if ( $this->mDebug ) {
77 wfDebug( "IMPORT: $data\n" );
81 public function warn( $data ) {
82 wfDebug( "IMPORT: $data\n" );
85 public function notice( $msg /*, $param, ...*/ ) {
86 $params = func_get_args();
87 array_shift( $params );
89 if ( is_callable( $this->mNoticeCallback ) ) {
90 call_user_func( $this->mNoticeCallback, $msg, $params );
91 } else { # No ImportReporter -> CLI
92 echo wfMessage( $msg, $params )->text() . "\n";
96 /**
97 * Set debug mode...
98 * @param bool $debug
100 function setDebug( $debug ) {
101 $this->mDebug = $debug;
105 * Set 'no updates' mode. In this mode, the link tables will not be updated by the importer
106 * @param bool $noupdates
108 function setNoUpdates( $noupdates ) {
109 $this->mNoUpdates = $noupdates;
113 * Set a callback that displays notice messages
115 * @param callable $callback
116 * @return callable
118 public function setNoticeCallback( $callback ) {
119 return wfSetVar( $this->mNoticeCallback, $callback );
123 * Sets the action to perform as each new page in the stream is reached.
124 * @param callable $callback
125 * @return callable
127 public function setPageCallback( $callback ) {
128 $previous = $this->mPageCallback;
129 $this->mPageCallback = $callback;
130 return $previous;
134 * Sets the action to perform as each page in the stream is completed.
135 * Callback accepts the page title (as a Title object), a second object
136 * with the original title form (in case it's been overridden into a
137 * local namespace), and a count of revisions.
139 * @param callable $callback
140 * @return callable
142 public function setPageOutCallback( $callback ) {
143 $previous = $this->mPageOutCallback;
144 $this->mPageOutCallback = $callback;
145 return $previous;
149 * Sets the action to perform as each page revision is reached.
150 * @param callable $callback
151 * @return callable
153 public function setRevisionCallback( $callback ) {
154 $previous = $this->mRevisionCallback;
155 $this->mRevisionCallback = $callback;
156 return $previous;
160 * Sets the action to perform as each file upload version is reached.
161 * @param callable $callback
162 * @return callable
164 public function setUploadCallback( $callback ) {
165 $previous = $this->mUploadCallback;
166 $this->mUploadCallback = $callback;
167 return $previous;
171 * Sets the action to perform as each log item reached.
172 * @param callable $callback
173 * @return callable
175 public function setLogItemCallback( $callback ) {
176 $previous = $this->mLogItemCallback;
177 $this->mLogItemCallback = $callback;
178 return $previous;
182 * Sets the action to perform when site info is encountered
183 * @param callable $callback
184 * @return callable
186 public function setSiteInfoCallback( $callback ) {
187 $previous = $this->mSiteInfoCallback;
188 $this->mSiteInfoCallback = $callback;
189 return $previous;
193 * Set a target namespace to override the defaults
194 * @param null|int $namespace
195 * @return bool
197 public function setTargetNamespace( $namespace ) {
198 if ( is_null( $namespace ) ) {
199 // Don't override namespaces
200 $this->mTargetNamespace = null;
201 } elseif ( $namespace >= 0 ) {
202 // @todo FIXME: Check for validity
203 $this->mTargetNamespace = intval( $namespace );
204 } else {
205 return false;
210 * Set a target root page under which all pages are imported
211 * @param null|string $rootpage
212 * @return Status
214 public function setTargetRootPage( $rootpage ) {
215 $status = Status::newGood();
216 if ( is_null( $rootpage ) ) {
217 // No rootpage
218 $this->mTargetRootPage = null;
219 } elseif ( $rootpage !== '' ) {
220 $rootpage = rtrim( $rootpage, '/' ); //avoid double slashes
221 $title = Title::newFromText( $rootpage, !is_null( $this->mTargetNamespace ) ? $this->mTargetNamespace : NS_MAIN );
222 if ( !$title || $title->isExternal() ) {
223 $status->fatal( 'import-rootpage-invalid' );
224 } else {
225 if ( !MWNamespace::hasSubpages( $title->getNamespace() ) ) {
226 global $wgContLang;
228 $displayNSText = $title->getNamespace() == NS_MAIN
229 ? wfMessage( 'blanknamespace' )->text()
230 : $wgContLang->getNsText( $title->getNamespace() );
231 $status->fatal( 'import-rootpage-nosubpage', $displayNSText );
232 } else {
233 // set namespace to 'all', so the namespace check in processTitle() can passed
234 $this->setTargetNamespace( null );
235 $this->mTargetRootPage = $title->getPrefixedDBkey();
239 return $status;
243 * @param string $dir
245 public function setImageBasePath( $dir ) {
246 $this->mImageBasePath = $dir;
250 * @param bool $import
252 public function setImportUploads( $import ) {
253 $this->mImportUploads = $import;
257 * Default per-revision callback, performs the import.
258 * @param WikiRevision $revision
259 * @return bool
261 public function importRevision( $revision ) {
262 if ( !$revision->getContent()->getContentHandler()->canBeUsedOn( $revision->getTitle() ) ) {
263 $this->notice( 'import-error-bad-location',
264 $revision->getTitle()->getPrefixedText(),
265 $revision->getID(),
266 $revision->getModel(),
267 $revision->getFormat() );
269 return false;
272 try {
273 $dbw = wfGetDB( DB_MASTER );
274 return $dbw->deadlockLoop( array( $revision, 'importOldRevision' ) );
275 } catch ( MWContentSerializationException $ex ) {
276 $this->notice( 'import-error-unserialize',
277 $revision->getTitle()->getPrefixedText(),
278 $revision->getID(),
279 $revision->getModel(),
280 $revision->getFormat() );
283 return false;
287 * Default per-revision callback, performs the import.
288 * @param WikiRevision $rev
289 * @return bool
291 public function importLogItem( $rev ) {
292 $dbw = wfGetDB( DB_MASTER );
293 return $dbw->deadlockLoop( array( $rev, 'importLogItem' ) );
297 * Dummy for now...
298 * @param WikiRevision $revision
299 * @return bool
301 public function importUpload( $revision ) {
302 $dbw = wfGetDB( DB_MASTER );
303 return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
307 * Mostly for hook use
308 * @param Title $title
309 * @param string $origTitle
310 * @param int $revCount
311 * @param int $sRevCount
312 * @param array $pageInfo
313 * @return
315 public function finishImportPage( $title, $origTitle, $revCount, $sRevCount, $pageInfo ) {
316 $args = func_get_args();
317 return wfRunHooks( 'AfterImportPage', $args );
321 * Alternate per-revision callback, for debugging.
322 * @param WikiRevision $revision
324 public function debugRevisionHandler( &$revision ) {
325 $this->debug( "Got revision:" );
326 if ( is_object( $revision->title ) ) {
327 $this->debug( "-- Title: " . $revision->title->getPrefixedText() );
328 } else {
329 $this->debug( "-- Title: <invalid>" );
331 $this->debug( "-- User: " . $revision->user_text );
332 $this->debug( "-- Timestamp: " . $revision->timestamp );
333 $this->debug( "-- Comment: " . $revision->comment );
334 $this->debug( "-- Text: " . $revision->text );
338 * Notify the callback function when a new "<page>" is reached.
339 * @param Title $title
341 function pageCallback( $title ) {
342 if ( isset( $this->mPageCallback ) ) {
343 call_user_func( $this->mPageCallback, $title );
348 * Notify the callback function when a "</page>" is closed.
349 * @param Title $title
350 * @param Title $origTitle
351 * @param int $revCount
352 * @param int $sucCount Number of revisions for which callback returned true
353 * @param array $pageInfo Associative array of page information
355 private function pageOutCallback( $title, $origTitle, $revCount, $sucCount, $pageInfo ) {
356 if ( isset( $this->mPageOutCallback ) ) {
357 $args = func_get_args();
358 call_user_func_array( $this->mPageOutCallback, $args );
363 * Notify the callback function of a revision
364 * @param WikiRevision $revision
365 * @return bool|mixed
367 private function revisionCallback( $revision ) {
368 if ( isset( $this->mRevisionCallback ) ) {
369 return call_user_func_array( $this->mRevisionCallback,
370 array( $revision, $this ) );
371 } else {
372 return false;
377 * Notify the callback function of a new log item
378 * @param WikiRevision $revision
379 * @return bool|mixed
381 private function logItemCallback( $revision ) {
382 if ( isset( $this->mLogItemCallback ) ) {
383 return call_user_func_array( $this->mLogItemCallback,
384 array( $revision, $this ) );
385 } else {
386 return false;
391 * Shouldn't something like this be built-in to XMLReader?
392 * Fetches text contents of the current element, assuming
393 * no sub-elements or such scary things.
394 * @return string
395 * @access private
397 public function nodeContents() {
398 if ( $this->reader->isEmptyElement ) {
399 return "";
401 $buffer = "";
402 while ( $this->reader->read() ) {
403 switch ( $this->reader->nodeType ) {
404 case XmlReader::TEXT:
405 case XmlReader::SIGNIFICANT_WHITESPACE:
406 $buffer .= $this->reader->value;
407 break;
408 case XmlReader::END_ELEMENT:
409 return $buffer;
413 $this->reader->close();
414 return '';
417 # --------------
419 /** Left in for debugging */
420 private function dumpElement() {
421 static $lookup = null;
422 if ( !$lookup ) {
423 $xmlReaderConstants = array(
424 "NONE",
425 "ELEMENT",
426 "ATTRIBUTE",
427 "TEXT",
428 "CDATA",
429 "ENTITY_REF",
430 "ENTITY",
431 "PI",
432 "COMMENT",
433 "DOC",
434 "DOC_TYPE",
435 "DOC_FRAGMENT",
436 "NOTATION",
437 "WHITESPACE",
438 "SIGNIFICANT_WHITESPACE",
439 "END_ELEMENT",
440 "END_ENTITY",
441 "XML_DECLARATION",
443 $lookup = array();
445 foreach ( $xmlReaderConstants as $name ) {
446 $lookup[constant( "XmlReader::$name" )] = $name;
450 print var_dump(
451 $lookup[$this->reader->nodeType],
452 $this->reader->name,
453 $this->reader->value
454 ) . "\n\n";
458 * Primary entry point
459 * @throws MWException
460 * @return bool
462 public function doImport() {
464 // Calls to reader->read need to be wrapped in calls to
465 // libxml_disable_entity_loader() to avoid local file
466 // inclusion attacks (bug 46932).
467 $oldDisable = libxml_disable_entity_loader( true );
468 $this->reader->read();
470 if ( $this->reader->name != 'mediawiki' ) {
471 libxml_disable_entity_loader( $oldDisable );
472 throw new MWException( "Expected <mediawiki> tag, got " .
473 $this->reader->name );
475 $this->debug( "<mediawiki> tag is correct." );
477 $this->debug( "Starting primary dump processing loop." );
479 $keepReading = $this->reader->read();
480 $skip = false;
481 while ( $keepReading ) {
482 $tag = $this->reader->name;
483 $type = $this->reader->nodeType;
485 if ( !wfRunHooks( 'ImportHandleToplevelXMLTag', array( $this ) ) ) {
486 // Do nothing
487 } elseif ( $tag == 'mediawiki' && $type == XmlReader::END_ELEMENT ) {
488 break;
489 } elseif ( $tag == 'siteinfo' ) {
490 $this->handleSiteInfo();
491 } elseif ( $tag == 'page' ) {
492 $this->handlePage();
493 } elseif ( $tag == 'logitem' ) {
494 $this->handleLogItem();
495 } elseif ( $tag != '#text' ) {
496 $this->warn( "Unhandled top-level XML tag $tag" );
498 $skip = true;
501 if ( $skip ) {
502 $keepReading = $this->reader->next();
503 $skip = false;
504 $this->debug( "Skip" );
505 } else {
506 $keepReading = $this->reader->read();
510 libxml_disable_entity_loader( $oldDisable );
511 return true;
515 * @return bool
516 * @throws MWException
518 private function handleSiteInfo() {
519 // Site info is useful, but not actually used for dump imports.
520 // Includes a quick short-circuit to save performance.
521 if ( ! $this->mSiteInfoCallback ) {
522 $this->reader->next();
523 return true;
525 throw new MWException( "SiteInfo tag is not yet handled, do not set mSiteInfoCallback" );
528 private function handleLogItem() {
529 $this->debug( "Enter log item handler." );
530 $logInfo = array();
532 // Fields that can just be stuffed in the pageInfo object
533 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
534 'logtitle', 'params' );
536 while ( $this->reader->read() ) {
537 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
538 $this->reader->name == 'logitem' ) {
539 break;
542 $tag = $this->reader->name;
544 if ( !wfRunHooks( 'ImportHandleLogItemXMLTag', array(
545 $this, $logInfo
546 ) ) ) {
547 // Do nothing
548 } elseif ( in_array( $tag, $normalFields ) ) {
549 $logInfo[$tag] = $this->nodeContents();
550 } elseif ( $tag == 'contributor' ) {
551 $logInfo['contributor'] = $this->handleContributor();
552 } elseif ( $tag != '#text' ) {
553 $this->warn( "Unhandled log-item XML tag $tag" );
557 $this->processLogItem( $logInfo );
561 * @param array $logInfo
562 * @return bool|mixed
564 private function processLogItem( $logInfo ) {
565 $revision = new WikiRevision;
567 $revision->setID( $logInfo['id'] );
568 $revision->setType( $logInfo['type'] );
569 $revision->setAction( $logInfo['action'] );
570 $revision->setTimestamp( $logInfo['timestamp'] );
571 $revision->setParams( $logInfo['params'] );
572 $revision->setTitle( Title::newFromText( $logInfo['logtitle'] ) );
573 $revision->setNoUpdates( $this->mNoUpdates );
575 if ( isset( $logInfo['comment'] ) ) {
576 $revision->setComment( $logInfo['comment'] );
579 if ( isset( $logInfo['contributor']['ip'] ) ) {
580 $revision->setUserIP( $logInfo['contributor']['ip'] );
582 if ( isset( $logInfo['contributor']['username'] ) ) {
583 $revision->setUserName( $logInfo['contributor']['username'] );
586 return $this->logItemCallback( $revision );
589 private function handlePage() {
590 // Handle page data.
591 $this->debug( "Enter page handler." );
592 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
594 // Fields that can just be stuffed in the pageInfo object
595 $normalFields = array( 'title', 'id', 'redirect', 'restrictions' );
597 $skip = false;
598 $badTitle = false;
600 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
601 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
602 $this->reader->name == 'page' ) {
603 break;
606 $tag = $this->reader->name;
608 if ( $badTitle ) {
609 // The title is invalid, bail out of this page
610 $skip = true;
611 } elseif ( !wfRunHooks( 'ImportHandlePageXMLTag', array( $this,
612 &$pageInfo ) ) ) {
613 // Do nothing
614 } elseif ( in_array( $tag, $normalFields ) ) {
615 $pageInfo[$tag] = $this->nodeContents();
616 if ( $tag == 'title' ) {
617 $title = $this->processTitle( $pageInfo['title'] );
619 if ( !$title ) {
620 $badTitle = true;
621 $skip = true;
624 $this->pageCallback( $title );
625 list( $pageInfo['_title'], $origTitle ) = $title;
627 } elseif ( $tag == 'revision' ) {
628 $this->handleRevision( $pageInfo );
629 } elseif ( $tag == 'upload' ) {
630 $this->handleUpload( $pageInfo );
631 } elseif ( $tag != '#text' ) {
632 $this->warn( "Unhandled page XML tag $tag" );
633 $skip = true;
637 $this->pageOutCallback( $pageInfo['_title'], $origTitle,
638 $pageInfo['revisionCount'],
639 $pageInfo['successfulRevisionCount'],
640 $pageInfo );
644 * @param array $pageInfo
646 private function handleRevision( &$pageInfo ) {
647 $this->debug( "Enter revision handler" );
648 $revisionInfo = array();
650 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'model', 'format', 'text' );
652 $skip = false;
654 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
655 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
656 $this->reader->name == 'revision' ) {
657 break;
660 $tag = $this->reader->name;
662 if ( !wfRunHooks( 'ImportHandleRevisionXMLTag', array(
663 $this, $pageInfo, $revisionInfo
664 ) ) ) {
665 // Do nothing
666 } elseif ( in_array( $tag, $normalFields ) ) {
667 $revisionInfo[$tag] = $this->nodeContents();
668 } elseif ( $tag == 'contributor' ) {
669 $revisionInfo['contributor'] = $this->handleContributor();
670 } elseif ( $tag != '#text' ) {
671 $this->warn( "Unhandled revision XML tag $tag" );
672 $skip = true;
676 $pageInfo['revisionCount']++;
677 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
678 $pageInfo['successfulRevisionCount']++;
683 * @param array $pageInfo
684 * @param array $revisionInfo
685 * @return bool|mixed
687 private function processRevision( $pageInfo, $revisionInfo ) {
688 $revision = new WikiRevision;
690 if ( isset( $revisionInfo['id'] ) ) {
691 $revision->setID( $revisionInfo['id'] );
693 if ( isset( $revisionInfo['text'] ) ) {
694 $revision->setText( $revisionInfo['text'] );
696 if ( isset( $revisionInfo['model'] ) ) {
697 $revision->setModel( $revisionInfo['model'] );
699 if ( isset( $revisionInfo['format'] ) ) {
700 $revision->setFormat( $revisionInfo['format'] );
702 $revision->setTitle( $pageInfo['_title'] );
704 if ( isset( $revisionInfo['timestamp'] ) ) {
705 $revision->setTimestamp( $revisionInfo['timestamp'] );
706 } else {
707 $revision->setTimestamp( wfTimestampNow() );
710 if ( isset( $revisionInfo['comment'] ) ) {
711 $revision->setComment( $revisionInfo['comment'] );
714 if ( isset( $revisionInfo['minor'] ) ) {
715 $revision->setMinor( true );
717 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
718 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
720 if ( isset( $revisionInfo['contributor']['username'] ) ) {
721 $revision->setUserName( $revisionInfo['contributor']['username'] );
723 $revision->setNoUpdates( $this->mNoUpdates );
725 return $this->revisionCallback( $revision );
729 * @param array $pageInfo
730 * @return mixed
732 private function handleUpload( &$pageInfo ) {
733 $this->debug( "Enter upload handler" );
734 $uploadInfo = array();
736 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
737 'src', 'size', 'sha1base36', 'archivename', 'rel' );
739 $skip = false;
741 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
742 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
743 $this->reader->name == 'upload' ) {
744 break;
747 $tag = $this->reader->name;
749 if ( !wfRunHooks( 'ImportHandleUploadXMLTag', array(
750 $this, $pageInfo
751 ) ) ) {
752 // Do nothing
753 } elseif ( in_array( $tag, $normalFields ) ) {
754 $uploadInfo[$tag] = $this->nodeContents();
755 } elseif ( $tag == 'contributor' ) {
756 $uploadInfo['contributor'] = $this->handleContributor();
757 } elseif ( $tag == 'contents' ) {
758 $contents = $this->nodeContents();
759 $encoding = $this->reader->getAttribute( 'encoding' );
760 if ( $encoding === 'base64' ) {
761 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
762 $uploadInfo['isTempSrc'] = true;
764 } elseif ( $tag != '#text' ) {
765 $this->warn( "Unhandled upload XML tag $tag" );
766 $skip = true;
770 if ( $this->mImageBasePath && isset( $uploadInfo['rel'] ) ) {
771 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
772 if ( file_exists( $path ) ) {
773 $uploadInfo['fileSrc'] = $path;
774 $uploadInfo['isTempSrc'] = false;
778 if ( $this->mImportUploads ) {
779 return $this->processUpload( $pageInfo, $uploadInfo );
784 * @param string $contents
785 * @return string
787 private function dumpTemp( $contents ) {
788 $filename = tempnam( wfTempDir(), 'importupload' );
789 file_put_contents( $filename, $contents );
790 return $filename;
794 * @param array $pageInfo
795 * @param array $uploadInfo
796 * @return mixed
798 private function processUpload( $pageInfo, $uploadInfo ) {
799 $revision = new WikiRevision;
800 $text = isset( $uploadInfo['text'] ) ? $uploadInfo['text'] : '';
802 $revision->setTitle( $pageInfo['_title'] );
803 $revision->setID( $pageInfo['id'] );
804 $revision->setTimestamp( $uploadInfo['timestamp'] );
805 $revision->setText( $text );
806 $revision->setFilename( $uploadInfo['filename'] );
807 if ( isset( $uploadInfo['archivename'] ) ) {
808 $revision->setArchiveName( $uploadInfo['archivename'] );
810 $revision->setSrc( $uploadInfo['src'] );
811 if ( isset( $uploadInfo['fileSrc'] ) ) {
812 $revision->setFileSrc( $uploadInfo['fileSrc'],
813 !empty( $uploadInfo['isTempSrc'] ) );
815 if ( isset( $uploadInfo['sha1base36'] ) ) {
816 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
818 $revision->setSize( intval( $uploadInfo['size'] ) );
819 $revision->setComment( $uploadInfo['comment'] );
821 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
822 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
824 if ( isset( $uploadInfo['contributor']['username'] ) ) {
825 $revision->setUserName( $uploadInfo['contributor']['username'] );
827 $revision->setNoUpdates( $this->mNoUpdates );
829 return call_user_func( $this->mUploadCallback, $revision );
833 * @return array
835 private function handleContributor() {
836 $fields = array( 'id', 'ip', 'username' );
837 $info = array();
839 while ( $this->reader->read() ) {
840 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
841 $this->reader->name == 'contributor' ) {
842 break;
845 $tag = $this->reader->name;
847 if ( in_array( $tag, $fields ) ) {
848 $info[$tag] = $this->nodeContents();
852 return $info;
856 * @param string $text
857 * @return array|bool
859 private function processTitle( $text ) {
860 global $wgCommandLineMode;
862 $workTitle = $text;
863 $origTitle = Title::newFromText( $workTitle );
865 if ( !is_null( $this->mTargetNamespace ) && !is_null( $origTitle ) ) {
866 # makeTitleSafe, because $origTitle can have a interwiki (different setting of interwiki map)
867 # and than dbKey can begin with a lowercase char
868 $title = Title::makeTitleSafe( $this->mTargetNamespace,
869 $origTitle->getDBkey() );
870 } else {
871 if ( !is_null( $this->mTargetRootPage ) ) {
872 $workTitle = $this->mTargetRootPage . '/' . $workTitle;
874 $title = Title::newFromText( $workTitle );
877 if ( is_null( $title ) ) {
878 # Invalid page title? Ignore the page
879 $this->notice( 'import-error-invalid', $workTitle );
880 return false;
881 } elseif ( $title->isExternal() ) {
882 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
883 return false;
884 } elseif ( !$title->canExist() ) {
885 $this->notice( 'import-error-special', $title->getPrefixedText() );
886 return false;
887 } elseif ( !$title->userCan( 'edit' ) && !$wgCommandLineMode ) {
888 # Do not import if the importing wiki user cannot edit this page
889 $this->notice( 'import-error-edit', $title->getPrefixedText() );
890 return false;
891 } elseif ( !$title->exists() && !$title->userCan( 'create' ) && !$wgCommandLineMode ) {
892 # Do not import if the importing wiki user cannot create this page
893 $this->notice( 'import-error-create', $title->getPrefixedText() );
894 return false;
897 return array( $title, $origTitle );
901 /** This is a horrible hack used to keep source compatibility */
902 class UploadSourceAdapter {
903 static $sourceRegistrations = array();
905 private $mSource;
906 private $mBuffer;
907 private $mPosition;
910 * @param string $source
911 * @return string
913 static function registerSource( $source ) {
914 $id = wfRandomString();
916 self::$sourceRegistrations[$id] = $source;
918 return $id;
922 * @param string $path
923 * @param string $mode
924 * @param array $options
925 * @param string $opened_path
926 * @return bool
928 function stream_open( $path, $mode, $options, &$opened_path ) {
929 $url = parse_url( $path );
930 $id = $url['host'];
932 if ( !isset( self::$sourceRegistrations[$id] ) ) {
933 return false;
936 $this->mSource = self::$sourceRegistrations[$id];
938 return true;
942 * @param int $count
943 * @return string
945 function stream_read( $count ) {
946 $return = '';
947 $leave = false;
949 while ( !$leave && !$this->mSource->atEnd() &&
950 strlen( $this->mBuffer ) < $count ) {
951 $read = $this->mSource->readChunk();
953 if ( !strlen( $read ) ) {
954 $leave = true;
957 $this->mBuffer .= $read;
960 if ( strlen( $this->mBuffer ) ) {
961 $return = substr( $this->mBuffer, 0, $count );
962 $this->mBuffer = substr( $this->mBuffer, $count );
965 $this->mPosition += strlen( $return );
967 return $return;
971 * @param string $data
972 * @return bool
974 function stream_write( $data ) {
975 return false;
979 * @return mixed
981 function stream_tell() {
982 return $this->mPosition;
986 * @return bool
988 function stream_eof() {
989 return $this->mSource->atEnd();
993 * @return array
995 function url_stat() {
996 $result = array();
998 $result['dev'] = $result[0] = 0;
999 $result['ino'] = $result[1] = 0;
1000 $result['mode'] = $result[2] = 0;
1001 $result['nlink'] = $result[3] = 0;
1002 $result['uid'] = $result[4] = 0;
1003 $result['gid'] = $result[5] = 0;
1004 $result['rdev'] = $result[6] = 0;
1005 $result['size'] = $result[7] = 0;
1006 $result['atime'] = $result[8] = 0;
1007 $result['mtime'] = $result[9] = 0;
1008 $result['ctime'] = $result[10] = 0;
1009 $result['blksize'] = $result[11] = 0;
1010 $result['blocks'] = $result[12] = 0;
1012 return $result;
1016 class XMLReader2 extends XMLReader {
1019 * @return bool|string
1021 function nodeContents() {
1022 if ( $this->isEmptyElement ) {
1023 return "";
1025 $buffer = "";
1026 while ( $this->read() ) {
1027 switch ( $this->nodeType ) {
1028 case XmlReader::TEXT:
1029 case XmlReader::SIGNIFICANT_WHITESPACE:
1030 $buffer .= $this->value;
1031 break;
1032 case XmlReader::END_ELEMENT:
1033 return $buffer;
1036 return $this->close();
1041 * @todo document (e.g. one-sentence class description).
1042 * @ingroup SpecialPage
1044 class WikiRevision {
1045 var $importer = null;
1048 * @var Title
1050 var $title = null;
1051 var $id = 0;
1052 var $timestamp = "20010115000000";
1053 var $user = 0;
1054 var $user_text = "";
1055 var $model = null;
1056 var $format = null;
1057 var $text = "";
1058 var $content = null;
1059 var $comment = "";
1060 var $minor = false;
1061 var $type = "";
1062 var $action = "";
1063 var $params = "";
1064 var $fileSrc = '';
1065 var $sha1base36 = false;
1066 var $isTemp = false;
1067 var $archiveName = '';
1068 var $fileIsTemp;
1069 private $mNoUpdates = false;
1072 * @param Title $title
1073 * @throws MWException
1075 function setTitle( $title ) {
1076 if ( is_object( $title ) ) {
1077 $this->title = $title;
1078 } elseif ( is_null( $title ) ) {
1079 throw new MWException( "WikiRevision given a null title in import. You may need to adjust \$wgLegalTitleChars." );
1080 } else {
1081 throw new MWException( "WikiRevision given non-object title in import." );
1086 * @param int $id
1088 function setID( $id ) {
1089 $this->id = $id;
1093 * @param string $ts
1095 function setTimestamp( $ts ) {
1096 # 2003-08-05T18:30:02Z
1097 $this->timestamp = wfTimestamp( TS_MW, $ts );
1101 * @param string $user
1103 function setUsername( $user ) {
1104 $this->user_text = $user;
1108 * @param string $ip
1110 function setUserIP( $ip ) {
1111 $this->user_text = $ip;
1115 * @param string $model
1117 function setModel( $model ) {
1118 $this->model = $model;
1122 * @param string $format
1124 function setFormat( $format ) {
1125 $this->format = $format;
1129 * @param string $text
1131 function setText( $text ) {
1132 $this->text = $text;
1136 * @param string $text
1138 function setComment( $text ) {
1139 $this->comment = $text;
1143 * @param bool $minor
1145 function setMinor( $minor ) {
1146 $this->minor = (bool)$minor;
1150 * @param mixed $src
1152 function setSrc( $src ) {
1153 $this->src = $src;
1157 * @param string $src
1158 * @param bool $isTemp
1160 function setFileSrc( $src, $isTemp ) {
1161 $this->fileSrc = $src;
1162 $this->fileIsTemp = $isTemp;
1166 * @param string $sha1base36
1168 function setSha1Base36( $sha1base36 ) {
1169 $this->sha1base36 = $sha1base36;
1173 * @param string $filename
1175 function setFilename( $filename ) {
1176 $this->filename = $filename;
1180 * @param string $archiveName
1182 function setArchiveName( $archiveName ) {
1183 $this->archiveName = $archiveName;
1187 * @param int $size
1189 function setSize( $size ) {
1190 $this->size = intval( $size );
1194 * @param string $type
1196 function setType( $type ) {
1197 $this->type = $type;
1201 * @param string $action
1203 function setAction( $action ) {
1204 $this->action = $action;
1208 * @param array $params
1210 function setParams( $params ) {
1211 $this->params = $params;
1215 * @param bool $noupdates
1217 public function setNoUpdates( $noupdates ) {
1218 $this->mNoUpdates = $noupdates;
1222 * @return Title
1224 function getTitle() {
1225 return $this->title;
1229 * @return int
1231 function getID() {
1232 return $this->id;
1236 * @return string
1238 function getTimestamp() {
1239 return $this->timestamp;
1243 * @return string
1245 function getUser() {
1246 return $this->user_text;
1250 * @return string
1252 * @deprecated Since 1.21, use getContent() instead.
1254 function getText() {
1255 ContentHandler::deprecated( __METHOD__, '1.21' );
1257 return $this->text;
1261 * @return Content
1263 function getContent() {
1264 if ( is_null( $this->content ) ) {
1265 $this->content =
1266 ContentHandler::makeContent(
1267 $this->text,
1268 $this->getTitle(),
1269 $this->getModel(),
1270 $this->getFormat()
1274 return $this->content;
1278 * @return string
1280 function getModel() {
1281 if ( is_null( $this->model ) ) {
1282 $this->model = $this->getTitle()->getContentModel();
1285 return $this->model;
1289 * @return string
1291 function getFormat() {
1292 if ( is_null( $this->model ) ) {
1293 $this->format = ContentHandler::getForTitle( $this->getTitle() )->getDefaultFormat();
1296 return $this->format;
1300 * @return string
1302 function getComment() {
1303 return $this->comment;
1307 * @return bool
1309 function getMinor() {
1310 return $this->minor;
1314 * @return mixed
1316 function getSrc() {
1317 return $this->src;
1321 * @return bool|string
1323 function getSha1() {
1324 if ( $this->sha1base36 ) {
1325 return wfBaseConvert( $this->sha1base36, 36, 16 );
1327 return false;
1331 * @return string
1333 function getFileSrc() {
1334 return $this->fileSrc;
1338 * @return bool
1340 function isTempSrc() {
1341 return $this->isTemp;
1345 * @return mixed
1347 function getFilename() {
1348 return $this->filename;
1352 * @return string
1354 function getArchiveName() {
1355 return $this->archiveName;
1359 * @return mixed
1361 function getSize() {
1362 return $this->size;
1366 * @return string
1368 function getType() {
1369 return $this->type;
1373 * @return string
1375 function getAction() {
1376 return $this->action;
1380 * @return string
1382 function getParams() {
1383 return $this->params;
1387 * @return bool
1389 function importOldRevision() {
1390 $dbw = wfGetDB( DB_MASTER );
1392 # Sneak a single revision into place
1393 $user = User::newFromName( $this->getUser() );
1394 if ( $user ) {
1395 $userId = intval( $user->getId() );
1396 $userText = $user->getName();
1397 $userObj = $user;
1398 } else {
1399 $userId = 0;
1400 $userText = $this->getUser();
1401 $userObj = new User;
1404 // avoid memory leak...?
1405 $linkCache = LinkCache::singleton();
1406 $linkCache->clear();
1408 $page = WikiPage::factory( $this->title );
1409 if ( !$page->exists() ) {
1410 # must create the page...
1411 $pageId = $page->insertOn( $dbw );
1412 $created = true;
1413 $oldcountable = null;
1414 } else {
1415 $pageId = $page->getId();
1416 $created = false;
1418 $prior = $dbw->selectField( 'revision', '1',
1419 array( 'rev_page' => $pageId,
1420 'rev_timestamp' => $dbw->timestamp( $this->timestamp ),
1421 'rev_user_text' => $userText,
1422 'rev_comment' => $this->getComment() ),
1423 __METHOD__
1425 if ( $prior ) {
1426 // @todo FIXME: This could fail slightly for multiple matches :P
1427 wfDebug( __METHOD__ . ": skipping existing revision for [[" .
1428 $this->title->getPrefixedText() . "]], timestamp " . $this->timestamp . "\n" );
1429 return false;
1431 $oldcountable = $page->isCountable();
1434 # @todo FIXME: Use original rev_id optionally (better for backups)
1435 # Insert the row
1436 $revision = new Revision( array(
1437 'title' => $this->title,
1438 'page' => $pageId,
1439 'content_model' => $this->getModel(),
1440 'content_format' => $this->getFormat(),
1441 'text' => $this->getContent()->serialize( $this->getFormat() ), //XXX: just set 'content' => $this->getContent()?
1442 'comment' => $this->getComment(),
1443 'user' => $userId,
1444 'user_text' => $userText,
1445 'timestamp' => $this->timestamp,
1446 'minor_edit' => $this->minor,
1447 ) );
1448 $revision->insertOn( $dbw );
1449 $changed = $page->updateIfNewerOn( $dbw, $revision );
1451 if ( $changed !== false && !$this->mNoUpdates ) {
1452 wfDebug( __METHOD__ . ": running updates\n" );
1453 $page->doEditUpdates( $revision, $userObj, array( 'created' => $created, 'oldcountable' => $oldcountable ) );
1456 return true;
1460 * @return mixed
1462 function importLogItem() {
1463 $dbw = wfGetDB( DB_MASTER );
1464 # @todo FIXME: This will not record autoblocks
1465 if ( !$this->getTitle() ) {
1466 wfDebug( __METHOD__ . ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1467 $this->timestamp . "\n" );
1468 return;
1470 # Check if it exists already
1471 // @todo FIXME: Use original log ID (better for backups)
1472 $prior = $dbw->selectField( 'logging', '1',
1473 array( 'log_type' => $this->getType(),
1474 'log_action' => $this->getAction(),
1475 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
1476 'log_namespace' => $this->getTitle()->getNamespace(),
1477 'log_title' => $this->getTitle()->getDBkey(),
1478 'log_comment' => $this->getComment(),
1479 #'log_user_text' => $this->user_text,
1480 'log_params' => $this->params ),
1481 __METHOD__
1483 // @todo FIXME: This could fail slightly for multiple matches :P
1484 if ( $prior ) {
1485 wfDebug( __METHOD__ . ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp " .
1486 $this->timestamp . "\n" );
1487 return;
1489 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1490 $data = array(
1491 'log_id' => $log_id,
1492 'log_type' => $this->type,
1493 'log_action' => $this->action,
1494 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
1495 'log_user' => User::idFromName( $this->user_text ),
1496 #'log_user_text' => $this->user_text,
1497 'log_namespace' => $this->getTitle()->getNamespace(),
1498 'log_title' => $this->getTitle()->getDBkey(),
1499 'log_comment' => $this->getComment(),
1500 'log_params' => $this->params
1502 $dbw->insert( 'logging', $data, __METHOD__ );
1506 * @return bool
1508 function importUpload() {
1509 # Construct a file
1510 $archiveName = $this->getArchiveName();
1511 if ( $archiveName ) {
1512 wfDebug( __METHOD__ . "Importing archived file as $archiveName\n" );
1513 $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
1514 RepoGroup::singleton()->getLocalRepo(), $archiveName );
1515 } else {
1516 $file = wfLocalFile( $this->getTitle() );
1517 wfDebug( __METHOD__ . 'Importing new file as ' . $file->getName() . "\n" );
1518 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1519 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1520 $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
1521 RepoGroup::singleton()->getLocalRepo(), $archiveName );
1522 wfDebug( __METHOD__ . "File already exists; importing as $archiveName\n" );
1525 if ( !$file ) {
1526 wfDebug( __METHOD__ . ': Bad file for ' . $this->getTitle() . "\n" );
1527 return false;
1530 # Get the file source or download if necessary
1531 $source = $this->getFileSrc();
1532 $flags = $this->isTempSrc() ? File::DELETE_SOURCE : 0;
1533 if ( !$source ) {
1534 $source = $this->downloadSource();
1535 $flags |= File::DELETE_SOURCE;
1537 if ( !$source ) {
1538 wfDebug( __METHOD__ . ": Could not fetch remote file.\n" );
1539 return false;
1541 $sha1 = $this->getSha1();
1542 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1543 if ( $flags & File::DELETE_SOURCE ) {
1544 # Broken file; delete it if it is a temporary file
1545 unlink( $source );
1547 wfDebug( __METHOD__ . ": Corrupt file $source.\n" );
1548 return false;
1551 $user = User::newFromName( $this->user_text );
1553 # Do the actual upload
1554 if ( $archiveName ) {
1555 $status = $file->uploadOld( $source, $archiveName,
1556 $this->getTimestamp(), $this->getComment(), $user, $flags );
1557 } else {
1558 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1559 $flags, false, $this->getTimestamp(), $user );
1562 if ( $status->isGood() ) {
1563 wfDebug( __METHOD__ . ": Successful\n" );
1564 return true;
1565 } else {
1566 wfDebug( __METHOD__ . ': failed: ' . $status->getXml() . "\n" );
1567 return false;
1572 * @return bool|string
1574 function downloadSource() {
1575 global $wgEnableUploads;
1576 if ( !$wgEnableUploads ) {
1577 return false;
1580 $tempo = tempnam( wfTempDir(), 'download' );
1581 $f = fopen( $tempo, 'wb' );
1582 if ( !$f ) {
1583 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1584 return false;
1587 // @todo FIXME!
1588 $src = $this->getSrc();
1589 $data = Http::get( $src );
1590 if ( !$data ) {
1591 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1592 fclose( $f );
1593 unlink( $tempo );
1594 return false;
1597 fwrite( $f, $data );
1598 fclose( $f );
1600 return $tempo;
1606 * @todo document (e.g. one-sentence class description).
1607 * @ingroup SpecialPage
1609 class ImportStringSource {
1610 function __construct( $string ) {
1611 $this->mString = $string;
1612 $this->mRead = false;
1616 * @return bool
1618 function atEnd() {
1619 return $this->mRead;
1623 * @return bool|string
1625 function readChunk() {
1626 if ( $this->atEnd() ) {
1627 return false;
1629 $this->mRead = true;
1630 return $this->mString;
1635 * @todo document (e.g. one-sentence class description).
1636 * @ingroup SpecialPage
1638 class ImportStreamSource {
1639 function __construct( $handle ) {
1640 $this->mHandle = $handle;
1644 * @return bool
1646 function atEnd() {
1647 return feof( $this->mHandle );
1651 * @return string
1653 function readChunk() {
1654 return fread( $this->mHandle, 32768 );
1658 * @param string $filename
1659 * @return Status
1661 static function newFromFile( $filename ) {
1662 wfSuppressWarnings();
1663 $file = fopen( $filename, 'rt' );
1664 wfRestoreWarnings();
1665 if ( !$file ) {
1666 return Status::newFatal( "importcantopen" );
1668 return Status::newGood( new ImportStreamSource( $file ) );
1672 * @param string $fieldname
1673 * @return Status
1675 static function newFromUpload( $fieldname = "xmlimport" ) {
1676 $upload =& $_FILES[$fieldname];
1678 if ( $upload === null || !$upload['name'] ) {
1679 return Status::newFatal( 'importnofile' );
1681 if ( !empty( $upload['error'] ) ) {
1682 switch ( $upload['error'] ) {
1683 case 1: # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1684 return Status::newFatal( 'importuploaderrorsize' );
1685 case 2: # The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
1686 return Status::newFatal( 'importuploaderrorsize' );
1687 case 3: # The uploaded file was only partially uploaded
1688 return Status::newFatal( 'importuploaderrorpartial' );
1689 case 6: #Missing a temporary folder.
1690 return Status::newFatal( 'importuploaderrortemp' );
1691 # case else: # Currently impossible
1695 $fname = $upload['tmp_name'];
1696 if ( is_uploaded_file( $fname ) ) {
1697 return ImportStreamSource::newFromFile( $fname );
1698 } else {
1699 return Status::newFatal( 'importnofile' );
1704 * @param string $url
1705 * @param string $method
1706 * @return Status
1708 static function newFromURL( $url, $method = 'GET' ) {
1709 wfDebug( __METHOD__ . ": opening $url\n" );
1710 # Use the standard HTTP fetch function; it times out
1711 # quicker and sorts out user-agent problems which might
1712 # otherwise prevent importing from large sites, such
1713 # as the Wikimedia cluster, etc.
1714 $data = Http::request( $method, $url, array( 'followRedirects' => true ) );
1715 if ( $data !== false ) {
1716 $file = tmpfile();
1717 fwrite( $file, $data );
1718 fflush( $file );
1719 fseek( $file, 0 );
1720 return Status::newGood( new ImportStreamSource( $file ) );
1721 } else {
1722 return Status::newFatal( 'importcantopen' );
1727 * @param string $interwiki
1728 * @param string $page
1729 * @param bool $history
1730 * @param bool $templates
1731 * @param int $pageLinkDepth
1732 * @return Status
1734 public static function newFromInterwiki( $interwiki, $page, $history = false, $templates = false, $pageLinkDepth = 0 ) {
1735 if ( $page == '' ) {
1736 return Status::newFatal( 'import-noarticle' );
1738 $link = Title::newFromText( "$interwiki:Special:Export/$page" );
1739 if ( is_null( $link ) || !$link->isExternal() ) {
1740 return Status::newFatal( 'importbadinterwiki' );
1741 } else {
1742 $params = array();
1743 if ( $history ) {
1744 $params['history'] = 1;
1746 if ( $templates ) {
1747 $params['templates'] = 1;
1749 if ( $pageLinkDepth ) {
1750 $params['pagelink-depth'] = $pageLinkDepth;
1752 $url = $link->getFullURL( $params );
1753 # For interwikis, use POST to avoid redirects.
1754 return ImportStreamSource::newFromURL( $url, "POST" );