Always use 'bool' instead of 'boolean' after '@param' and '@return'
[mediawiki.git] / includes / Import.php
blob4eb8e9748833af9334f7a75fe7fb9ad89e0bfb5b
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;
40 /** @var Config */
41 private $config;
43 /**
44 * Creates an ImportXMLReader drawing from the source provided
45 * @param ImportStreamSource $source
46 * @param Config $config
48 function __construct( ImportStreamSource $source, Config $config = null ) {
49 $this->reader = new XMLReader();
50 if ( !$config ) {
51 wfDeprecated( __METHOD__ . ' without a Config instance', '1.25' );
52 $config = ConfigFactory::getDefaultInstance()->makeConfig( 'main' );
54 $this->config = $config;
56 if ( !in_array( 'uploadsource', stream_get_wrappers() ) ) {
57 stream_wrapper_register( 'uploadsource', 'UploadSourceAdapter' );
59 $id = UploadSourceAdapter::registerSource( $source );
60 if ( defined( 'LIBXML_PARSEHUGE' ) ) {
61 $this->reader->open( "uploadsource://$id", null, LIBXML_PARSEHUGE );
62 } else {
63 $this->reader->open( "uploadsource://$id" );
66 // Default callbacks
67 $this->setRevisionCallback( array( $this, "importRevision" ) );
68 $this->setUploadCallback( array( $this, 'importUpload' ) );
69 $this->setLogItemCallback( array( $this, 'importLogItem' ) );
70 $this->setPageOutCallback( array( $this, 'finishImportPage' ) );
73 /**
74 * @return null|XMLReader
76 public function getReader() {
77 return $this->reader;
80 public function throwXmlError( $err ) {
81 $this->debug( "FAILURE: $err" );
82 wfDebug( "WikiImporter XML error: $err\n" );
85 public function debug( $data ) {
86 if ( $this->mDebug ) {
87 wfDebug( "IMPORT: $data\n" );
91 public function warn( $data ) {
92 wfDebug( "IMPORT: $data\n" );
95 public function notice( $msg /*, $param, ...*/ ) {
96 $params = func_get_args();
97 array_shift( $params );
99 if ( is_callable( $this->mNoticeCallback ) ) {
100 call_user_func( $this->mNoticeCallback, $msg, $params );
101 } else { # No ImportReporter -> CLI
102 echo wfMessage( $msg, $params )->text() . "\n";
107 * Set debug mode...
108 * @param bool $debug
110 function setDebug( $debug ) {
111 $this->mDebug = $debug;
115 * Set 'no updates' mode. In this mode, the link tables will not be updated by the importer
116 * @param bool $noupdates
118 function setNoUpdates( $noupdates ) {
119 $this->mNoUpdates = $noupdates;
123 * Set a callback that displays notice messages
125 * @param callable $callback
126 * @return callable
128 public function setNoticeCallback( $callback ) {
129 return wfSetVar( $this->mNoticeCallback, $callback );
133 * Sets the action to perform as each new page in the stream is reached.
134 * @param callable $callback
135 * @return callable
137 public function setPageCallback( $callback ) {
138 $previous = $this->mPageCallback;
139 $this->mPageCallback = $callback;
140 return $previous;
144 * Sets the action to perform as each page in the stream is completed.
145 * Callback accepts the page title (as a Title object), a second object
146 * with the original title form (in case it's been overridden into a
147 * local namespace), and a count of revisions.
149 * @param callable $callback
150 * @return callable
152 public function setPageOutCallback( $callback ) {
153 $previous = $this->mPageOutCallback;
154 $this->mPageOutCallback = $callback;
155 return $previous;
159 * Sets the action to perform as each page revision is reached.
160 * @param callable $callback
161 * @return callable
163 public function setRevisionCallback( $callback ) {
164 $previous = $this->mRevisionCallback;
165 $this->mRevisionCallback = $callback;
166 return $previous;
170 * Sets the action to perform as each file upload version is reached.
171 * @param callable $callback
172 * @return callable
174 public function setUploadCallback( $callback ) {
175 $previous = $this->mUploadCallback;
176 $this->mUploadCallback = $callback;
177 return $previous;
181 * Sets the action to perform as each log item reached.
182 * @param callable $callback
183 * @return callable
185 public function setLogItemCallback( $callback ) {
186 $previous = $this->mLogItemCallback;
187 $this->mLogItemCallback = $callback;
188 return $previous;
192 * Sets the action to perform when site info is encountered
193 * @param callable $callback
194 * @return callable
196 public function setSiteInfoCallback( $callback ) {
197 $previous = $this->mSiteInfoCallback;
198 $this->mSiteInfoCallback = $callback;
199 return $previous;
203 * Set a target namespace to override the defaults
204 * @param null|int $namespace
205 * @return bool
207 public function setTargetNamespace( $namespace ) {
208 if ( is_null( $namespace ) ) {
209 // Don't override namespaces
210 $this->mTargetNamespace = null;
211 } elseif ( $namespace >= 0 ) {
212 // @todo FIXME: Check for validity
213 $this->mTargetNamespace = intval( $namespace );
214 } else {
215 return false;
220 * Set a target root page under which all pages are imported
221 * @param null|string $rootpage
222 * @return Status
224 public function setTargetRootPage( $rootpage ) {
225 $status = Status::newGood();
226 if ( is_null( $rootpage ) ) {
227 // No rootpage
228 $this->mTargetRootPage = null;
229 } elseif ( $rootpage !== '' ) {
230 $rootpage = rtrim( $rootpage, '/' ); //avoid double slashes
231 $title = Title::newFromText( $rootpage, !is_null( $this->mTargetNamespace )
232 ? $this->mTargetNamespace
233 : NS_MAIN
236 if ( !$title || $title->isExternal() ) {
237 $status->fatal( 'import-rootpage-invalid' );
238 } else {
239 if ( !MWNamespace::hasSubpages( $title->getNamespace() ) ) {
240 global $wgContLang;
242 $displayNSText = $title->getNamespace() == NS_MAIN
243 ? wfMessage( 'blanknamespace' )->text()
244 : $wgContLang->getNsText( $title->getNamespace() );
245 $status->fatal( 'import-rootpage-nosubpage', $displayNSText );
246 } else {
247 // set namespace to 'all', so the namespace check in processTitle() can passed
248 $this->setTargetNamespace( null );
249 $this->mTargetRootPage = $title->getPrefixedDBkey();
253 return $status;
257 * @param string $dir
259 public function setImageBasePath( $dir ) {
260 $this->mImageBasePath = $dir;
264 * @param bool $import
266 public function setImportUploads( $import ) {
267 $this->mImportUploads = $import;
271 * Default per-revision callback, performs the import.
272 * @param WikiRevision $revision
273 * @return bool
275 public function importRevision( $revision ) {
276 if ( !$revision->getContentHandler()->canBeUsedOn( $revision->getTitle() ) ) {
277 $this->notice( 'import-error-bad-location',
278 $revision->getTitle()->getPrefixedText(),
279 $revision->getID(),
280 $revision->getModel(),
281 $revision->getFormat() );
283 return false;
286 try {
287 $dbw = wfGetDB( DB_MASTER );
288 return $dbw->deadlockLoop( array( $revision, 'importOldRevision' ) );
289 } catch ( MWContentSerializationException $ex ) {
290 $this->notice( 'import-error-unserialize',
291 $revision->getTitle()->getPrefixedText(),
292 $revision->getID(),
293 $revision->getModel(),
294 $revision->getFormat() );
297 return false;
301 * Default per-revision callback, performs the import.
302 * @param WikiRevision $revision
303 * @return bool
305 public function importLogItem( $revision ) {
306 $dbw = wfGetDB( DB_MASTER );
307 return $dbw->deadlockLoop( array( $revision, 'importLogItem' ) );
311 * Dummy for now...
312 * @param WikiRevision $revision
313 * @return bool
315 public function importUpload( $revision ) {
316 $dbw = wfGetDB( DB_MASTER );
317 return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
321 * Mostly for hook use
322 * @param Title $title
323 * @param string $origTitle
324 * @param int $revCount
325 * @param int $sRevCount
326 * @param array $pageInfo
327 * @return bool
329 public function finishImportPage( $title, $origTitle, $revCount, $sRevCount, $pageInfo ) {
330 $args = func_get_args();
331 return wfRunHooks( 'AfterImportPage', $args );
335 * Alternate per-revision callback, for debugging.
336 * @param WikiRevision $revision
338 public function debugRevisionHandler( &$revision ) {
339 $this->debug( "Got revision:" );
340 if ( is_object( $revision->title ) ) {
341 $this->debug( "-- Title: " . $revision->title->getPrefixedText() );
342 } else {
343 $this->debug( "-- Title: <invalid>" );
345 $this->debug( "-- User: " . $revision->user_text );
346 $this->debug( "-- Timestamp: " . $revision->timestamp );
347 $this->debug( "-- Comment: " . $revision->comment );
348 $this->debug( "-- Text: " . $revision->text );
352 * Notify the callback function when a new "<page>" is reached.
353 * @param Title $title
355 function pageCallback( $title ) {
356 if ( isset( $this->mPageCallback ) ) {
357 call_user_func( $this->mPageCallback, $title );
362 * Notify the callback function when a "</page>" is closed.
363 * @param Title $title
364 * @param Title $origTitle
365 * @param int $revCount
366 * @param int $sucCount Number of revisions for which callback returned true
367 * @param array $pageInfo Associative array of page information
369 private function pageOutCallback( $title, $origTitle, $revCount, $sucCount, $pageInfo ) {
370 if ( isset( $this->mPageOutCallback ) ) {
371 $args = func_get_args();
372 call_user_func_array( $this->mPageOutCallback, $args );
377 * Notify the callback function of a revision
378 * @param WikiRevision $revision
379 * @return bool|mixed
381 private function revisionCallback( $revision ) {
382 if ( isset( $this->mRevisionCallback ) ) {
383 return call_user_func_array( $this->mRevisionCallback,
384 array( $revision, $this ) );
385 } else {
386 return false;
391 * Notify the callback function of a new log item
392 * @param WikiRevision $revision
393 * @return bool|mixed
395 private function logItemCallback( $revision ) {
396 if ( isset( $this->mLogItemCallback ) ) {
397 return call_user_func_array( $this->mLogItemCallback,
398 array( $revision, $this ) );
399 } else {
400 return false;
405 * Retrieves the contents of the named attribute of the current element.
406 * @param string $attr The name of the attribute
407 * @return string The value of the attribute or an empty string if it is not set in the current element.
409 public function nodeAttribute( $attr ) {
410 return $this->reader->getAttribute( $attr );
414 * Shouldn't something like this be built-in to XMLReader?
415 * Fetches text contents of the current element, assuming
416 * no sub-elements or such scary things.
417 * @return string
418 * @access private
420 public function nodeContents() {
421 if ( $this->reader->isEmptyElement ) {
422 return "";
424 $buffer = "";
425 while ( $this->reader->read() ) {
426 switch ( $this->reader->nodeType ) {
427 case XmlReader::TEXT:
428 case XmlReader::SIGNIFICANT_WHITESPACE:
429 $buffer .= $this->reader->value;
430 break;
431 case XmlReader::END_ELEMENT:
432 return $buffer;
436 $this->reader->close();
437 return '';
441 * Primary entry point
442 * @throws MWException
443 * @return bool
445 public function doImport() {
446 // Calls to reader->read need to be wrapped in calls to
447 // libxml_disable_entity_loader() to avoid local file
448 // inclusion attacks (bug 46932).
449 $oldDisable = libxml_disable_entity_loader( true );
450 $this->reader->read();
452 if ( $this->reader->name != 'mediawiki' ) {
453 libxml_disable_entity_loader( $oldDisable );
454 throw new MWException( "Expected <mediawiki> tag, got " .
455 $this->reader->name );
457 $this->debug( "<mediawiki> tag is correct." );
459 $this->debug( "Starting primary dump processing loop." );
461 $keepReading = $this->reader->read();
462 $skip = false;
463 while ( $keepReading ) {
464 $tag = $this->reader->name;
465 $type = $this->reader->nodeType;
467 if ( !wfRunHooks( 'ImportHandleToplevelXMLTag', array( $this ) ) ) {
468 // Do nothing
469 } elseif ( $tag == 'mediawiki' && $type == XmlReader::END_ELEMENT ) {
470 break;
471 } elseif ( $tag == 'siteinfo' ) {
472 $this->handleSiteInfo();
473 } elseif ( $tag == 'page' ) {
474 $this->handlePage();
475 } elseif ( $tag == 'logitem' ) {
476 $this->handleLogItem();
477 } elseif ( $tag != '#text' ) {
478 $this->warn( "Unhandled top-level XML tag $tag" );
480 $skip = true;
483 if ( $skip ) {
484 $keepReading = $this->reader->next();
485 $skip = false;
486 $this->debug( "Skip" );
487 } else {
488 $keepReading = $this->reader->read();
492 libxml_disable_entity_loader( $oldDisable );
493 return true;
497 * @return bool
498 * @throws MWException
500 private function handleSiteInfo() {
501 // Site info is useful, but not actually used for dump imports.
502 // Includes a quick short-circuit to save performance.
503 if ( !$this->mSiteInfoCallback ) {
504 $this->reader->next();
505 return true;
507 throw new MWException( "SiteInfo tag is not yet handled, do not set mSiteInfoCallback" );
510 private function handleLogItem() {
511 $this->debug( "Enter log item handler." );
512 $logInfo = array();
514 // Fields that can just be stuffed in the pageInfo object
515 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
516 'logtitle', 'params' );
518 while ( $this->reader->read() ) {
519 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
520 $this->reader->name == 'logitem' ) {
521 break;
524 $tag = $this->reader->name;
526 if ( !wfRunHooks( 'ImportHandleLogItemXMLTag', array(
527 $this, $logInfo
528 ) ) ) {
529 // Do nothing
530 } elseif ( in_array( $tag, $normalFields ) ) {
531 $logInfo[$tag] = $this->nodeContents();
532 } elseif ( $tag == 'contributor' ) {
533 $logInfo['contributor'] = $this->handleContributor();
534 } elseif ( $tag != '#text' ) {
535 $this->warn( "Unhandled log-item XML tag $tag" );
539 $this->processLogItem( $logInfo );
543 * @param array $logInfo
544 * @return bool|mixed
546 private function processLogItem( $logInfo ) {
547 $revision = new WikiRevision( $this->config );
549 $revision->setID( $logInfo['id'] );
550 $revision->setType( $logInfo['type'] );
551 $revision->setAction( $logInfo['action'] );
552 $revision->setTimestamp( $logInfo['timestamp'] );
553 $revision->setParams( $logInfo['params'] );
554 $revision->setTitle( Title::newFromText( $logInfo['logtitle'] ) );
555 $revision->setNoUpdates( $this->mNoUpdates );
557 if ( isset( $logInfo['comment'] ) ) {
558 $revision->setComment( $logInfo['comment'] );
561 if ( isset( $logInfo['contributor']['ip'] ) ) {
562 $revision->setUserIP( $logInfo['contributor']['ip'] );
564 if ( isset( $logInfo['contributor']['username'] ) ) {
565 $revision->setUserName( $logInfo['contributor']['username'] );
568 return $this->logItemCallback( $revision );
571 private function handlePage() {
572 // Handle page data.
573 $this->debug( "Enter page handler." );
574 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
576 // Fields that can just be stuffed in the pageInfo object
577 $normalFields = array( 'title', 'id', 'redirect', 'restrictions' );
579 $skip = false;
580 $badTitle = false;
582 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
583 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
584 $this->reader->name == 'page' ) {
585 break;
588 $tag = $this->reader->name;
590 if ( $badTitle ) {
591 // The title is invalid, bail out of this page
592 $skip = true;
593 } elseif ( !wfRunHooks( 'ImportHandlePageXMLTag', array( $this,
594 &$pageInfo ) ) ) {
595 // Do nothing
596 } elseif ( in_array( $tag, $normalFields ) ) {
597 // An XML snippet:
598 // <page>
599 // <id>123</id>
600 // <title>Page</title>
601 // <redirect title="NewTitle"/>
602 // ...
603 // Because the redirect tag is built differently, we need special handling for that case.
604 if ( $tag == 'redirect' ) {
605 $pageInfo[$tag] = $this->nodeAttribute( 'title' );
606 } else {
607 $pageInfo[$tag] = $this->nodeContents();
608 if ( $tag == 'title' ) {
609 $title = $this->processTitle( $pageInfo['title'] );
611 if ( !$title ) {
612 $badTitle = true;
613 $skip = true;
616 $this->pageCallback( $title );
617 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( $this->config );
683 if ( isset( $revisionInfo['id'] ) ) {
684 $revision->setID( $revisionInfo['id'] );
686 if ( isset( $revisionInfo['model'] ) ) {
687 $revision->setModel( $revisionInfo['model'] );
689 if ( isset( $revisionInfo['format'] ) ) {
690 $revision->setFormat( $revisionInfo['format'] );
692 $revision->setTitle( $pageInfo['_title'] );
694 if ( isset( $revisionInfo['text'] ) ) {
695 $handler = $revision->getContentHandler();
696 $text = $handler->importTransform(
697 $revisionInfo['text'],
698 $revision->getFormat() );
700 $revision->setText( $text );
702 if ( isset( $revisionInfo['timestamp'] ) ) {
703 $revision->setTimestamp( $revisionInfo['timestamp'] );
704 } else {
705 $revision->setTimestamp( wfTimestampNow() );
708 if ( isset( $revisionInfo['comment'] ) ) {
709 $revision->setComment( $revisionInfo['comment'] );
712 if ( isset( $revisionInfo['minor'] ) ) {
713 $revision->setMinor( true );
715 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
716 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
718 if ( isset( $revisionInfo['contributor']['username'] ) ) {
719 $revision->setUserName( $revisionInfo['contributor']['username'] );
721 $revision->setNoUpdates( $this->mNoUpdates );
723 return $this->revisionCallback( $revision );
727 * @param array $pageInfo
728 * @return mixed
730 private function handleUpload( &$pageInfo ) {
731 $this->debug( "Enter upload handler" );
732 $uploadInfo = array();
734 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
735 'src', 'size', 'sha1base36', 'archivename', 'rel' );
737 $skip = false;
739 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
740 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
741 $this->reader->name == 'upload' ) {
742 break;
745 $tag = $this->reader->name;
747 if ( !wfRunHooks( 'ImportHandleUploadXMLTag', array(
748 $this, $pageInfo
749 ) ) ) {
750 // Do nothing
751 } elseif ( in_array( $tag, $normalFields ) ) {
752 $uploadInfo[$tag] = $this->nodeContents();
753 } elseif ( $tag == 'contributor' ) {
754 $uploadInfo['contributor'] = $this->handleContributor();
755 } elseif ( $tag == 'contents' ) {
756 $contents = $this->nodeContents();
757 $encoding = $this->reader->getAttribute( 'encoding' );
758 if ( $encoding === 'base64' ) {
759 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
760 $uploadInfo['isTempSrc'] = true;
762 } elseif ( $tag != '#text' ) {
763 $this->warn( "Unhandled upload XML tag $tag" );
764 $skip = true;
768 if ( $this->mImageBasePath && isset( $uploadInfo['rel'] ) ) {
769 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
770 if ( file_exists( $path ) ) {
771 $uploadInfo['fileSrc'] = $path;
772 $uploadInfo['isTempSrc'] = false;
776 if ( $this->mImportUploads ) {
777 return $this->processUpload( $pageInfo, $uploadInfo );
782 * @param string $contents
783 * @return string
785 private function dumpTemp( $contents ) {
786 $filename = tempnam( wfTempDir(), 'importupload' );
787 file_put_contents( $filename, $contents );
788 return $filename;
792 * @param array $pageInfo
793 * @param array $uploadInfo
794 * @return mixed
796 private function processUpload( $pageInfo, $uploadInfo ) {
797 $revision = new WikiRevision( $this->config );
798 $text = isset( $uploadInfo['text'] ) ? $uploadInfo['text'] : '';
800 $revision->setTitle( $pageInfo['_title'] );
801 $revision->setID( $pageInfo['id'] );
802 $revision->setTimestamp( $uploadInfo['timestamp'] );
803 $revision->setText( $text );
804 $revision->setFilename( $uploadInfo['filename'] );
805 if ( isset( $uploadInfo['archivename'] ) ) {
806 $revision->setArchiveName( $uploadInfo['archivename'] );
808 $revision->setSrc( $uploadInfo['src'] );
809 if ( isset( $uploadInfo['fileSrc'] ) ) {
810 $revision->setFileSrc( $uploadInfo['fileSrc'],
811 !empty( $uploadInfo['isTempSrc'] ) );
813 if ( isset( $uploadInfo['sha1base36'] ) ) {
814 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
816 $revision->setSize( intval( $uploadInfo['size'] ) );
817 $revision->setComment( $uploadInfo['comment'] );
819 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
820 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
822 if ( isset( $uploadInfo['contributor']['username'] ) ) {
823 $revision->setUserName( $uploadInfo['contributor']['username'] );
825 $revision->setNoUpdates( $this->mNoUpdates );
827 return call_user_func( $this->mUploadCallback, $revision );
831 * @return array
833 private function handleContributor() {
834 $fields = array( 'id', 'ip', 'username' );
835 $info = array();
837 while ( $this->reader->read() ) {
838 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
839 $this->reader->name == 'contributor' ) {
840 break;
843 $tag = $this->reader->name;
845 if ( in_array( $tag, $fields ) ) {
846 $info[$tag] = $this->nodeContents();
850 return $info;
854 * @param string $text
855 * @return array|bool
857 private function processTitle( $text ) {
858 $workTitle = $text;
859 $origTitle = Title::newFromText( $workTitle );
861 if ( !is_null( $this->mTargetNamespace ) && !is_null( $origTitle ) ) {
862 # makeTitleSafe, because $origTitle can have a interwiki (different setting of interwiki map)
863 # and than dbKey can begin with a lowercase char
864 $title = Title::makeTitleSafe( $this->mTargetNamespace,
865 $origTitle->getDBkey() );
866 } else {
867 if ( !is_null( $this->mTargetRootPage ) ) {
868 $workTitle = $this->mTargetRootPage . '/' . $workTitle;
870 $title = Title::newFromText( $workTitle );
873 $commandLineMode = $this->config->get( 'CommandLineMode' );
874 if ( is_null( $title ) ) {
875 # Invalid page title? Ignore the page
876 $this->notice( 'import-error-invalid', $workTitle );
877 return false;
878 } elseif ( $title->isExternal() ) {
879 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
880 return false;
881 } elseif ( !$title->canExist() ) {
882 $this->notice( 'import-error-special', $title->getPrefixedText() );
883 return false;
884 } elseif ( !$title->userCan( 'edit' ) && !$commandLineMode ) {
885 # Do not import if the importing wiki user cannot edit this page
886 $this->notice( 'import-error-edit', $title->getPrefixedText() );
887 return false;
888 } elseif ( !$title->exists() && !$title->userCan( 'create' ) && !$commandLineMode ) {
889 # Do not import if the importing wiki user cannot create this page
890 $this->notice( 'import-error-create', $title->getPrefixedText() );
891 return false;
894 return array( $title, $origTitle );
898 /** This is a horrible hack used to keep source compatibility */
899 class UploadSourceAdapter {
900 /** @var array */
901 public static $sourceRegistrations = array();
903 /** @var string */
904 private $mSource;
906 /** @var string */
907 private $mBuffer;
909 /** @var int */
910 private $mPosition;
913 * @param ImportStreamSource $source
914 * @return string
916 static function registerSource( ImportStreamSource $source ) {
917 $id = wfRandomString();
919 self::$sourceRegistrations[$id] = $source;
921 return $id;
925 * @param string $path
926 * @param string $mode
927 * @param array $options
928 * @param string $opened_path
929 * @return bool
931 function stream_open( $path, $mode, $options, &$opened_path ) {
932 $url = parse_url( $path );
933 $id = $url['host'];
935 if ( !isset( self::$sourceRegistrations[$id] ) ) {
936 return false;
939 $this->mSource = self::$sourceRegistrations[$id];
941 return true;
945 * @param int $count
946 * @return string
948 function stream_read( $count ) {
949 $return = '';
950 $leave = false;
952 while ( !$leave && !$this->mSource->atEnd() &&
953 strlen( $this->mBuffer ) < $count ) {
954 $read = $this->mSource->readChunk();
956 if ( !strlen( $read ) ) {
957 $leave = true;
960 $this->mBuffer .= $read;
963 if ( strlen( $this->mBuffer ) ) {
964 $return = substr( $this->mBuffer, 0, $count );
965 $this->mBuffer = substr( $this->mBuffer, $count );
968 $this->mPosition += strlen( $return );
970 return $return;
974 * @param string $data
975 * @return bool
977 function stream_write( $data ) {
978 return false;
982 * @return mixed
984 function stream_tell() {
985 return $this->mPosition;
989 * @return bool
991 function stream_eof() {
992 return $this->mSource->atEnd();
996 * @return array
998 function url_stat() {
999 $result = array();
1001 $result['dev'] = $result[0] = 0;
1002 $result['ino'] = $result[1] = 0;
1003 $result['mode'] = $result[2] = 0;
1004 $result['nlink'] = $result[3] = 0;
1005 $result['uid'] = $result[4] = 0;
1006 $result['gid'] = $result[5] = 0;
1007 $result['rdev'] = $result[6] = 0;
1008 $result['size'] = $result[7] = 0;
1009 $result['atime'] = $result[8] = 0;
1010 $result['mtime'] = $result[9] = 0;
1011 $result['ctime'] = $result[10] = 0;
1012 $result['blksize'] = $result[11] = 0;
1013 $result['blocks'] = $result[12] = 0;
1015 return $result;
1020 * @todo document (e.g. one-sentence class description).
1021 * @ingroup SpecialPage
1023 class WikiRevision {
1024 /** @todo Unused? */
1025 public $importer = null;
1027 /** @var Title */
1028 public $title = null;
1030 /** @var int */
1031 public $id = 0;
1033 /** @var string */
1034 public $timestamp = "20010115000000";
1037 * @var int
1038 * @todo Can't find any uses. Public, because that's suspicious. Get clarity. */
1039 public $user = 0;
1041 /** @var string */
1042 public $user_text = "";
1044 /** @var string */
1045 public $model = null;
1047 /** @var string */
1048 public $format = null;
1050 /** @var string */
1051 public $text = "";
1053 /** @var int */
1054 protected $size;
1056 /** @var Content */
1057 public $content = null;
1059 /** @var ContentHandler */
1060 protected $contentHandler = null;
1062 /** @var string */
1063 public $comment = "";
1065 /** @var bool */
1066 public $minor = false;
1068 /** @var string */
1069 public $type = "";
1071 /** @var string */
1072 public $action = "";
1074 /** @var string */
1075 public $params = "";
1077 /** @var string */
1078 public $fileSrc = '';
1080 /** @var bool|string */
1081 public $sha1base36 = false;
1084 * @var bool
1085 * @todo Unused?
1087 public $isTemp = false;
1089 /** @var string */
1090 public $archiveName = '';
1092 protected $filename;
1094 /** @var mixed */
1095 protected $src;
1097 /** @todo Unused? */
1098 public $fileIsTemp;
1100 /** @var bool */
1101 private $mNoUpdates = false;
1103 /** @var Config $config */
1104 private $config;
1106 public function __construct( Config $config ) {
1107 $this->config = $config;
1111 * @param Title $title
1112 * @throws MWException
1114 function setTitle( $title ) {
1115 if ( is_object( $title ) ) {
1116 $this->title = $title;
1117 } elseif ( is_null( $title ) ) {
1118 throw new MWException( "WikiRevision given a null title in import. "
1119 . "You may need to adjust \$wgLegalTitleChars." );
1120 } else {
1121 throw new MWException( "WikiRevision given non-object title in import." );
1126 * @param int $id
1128 function setID( $id ) {
1129 $this->id = $id;
1133 * @param string $ts
1135 function setTimestamp( $ts ) {
1136 # 2003-08-05T18:30:02Z
1137 $this->timestamp = wfTimestamp( TS_MW, $ts );
1141 * @param string $user
1143 function setUsername( $user ) {
1144 $this->user_text = $user;
1148 * @param string $ip
1150 function setUserIP( $ip ) {
1151 $this->user_text = $ip;
1155 * @param string $model
1157 function setModel( $model ) {
1158 $this->model = $model;
1162 * @param string $format
1164 function setFormat( $format ) {
1165 $this->format = $format;
1169 * @param string $text
1171 function setText( $text ) {
1172 $this->text = $text;
1176 * @param string $text
1178 function setComment( $text ) {
1179 $this->comment = $text;
1183 * @param bool $minor
1185 function setMinor( $minor ) {
1186 $this->minor = (bool)$minor;
1190 * @param mixed $src
1192 function setSrc( $src ) {
1193 $this->src = $src;
1197 * @param string $src
1198 * @param bool $isTemp
1200 function setFileSrc( $src, $isTemp ) {
1201 $this->fileSrc = $src;
1202 $this->fileIsTemp = $isTemp;
1206 * @param string $sha1base36
1208 function setSha1Base36( $sha1base36 ) {
1209 $this->sha1base36 = $sha1base36;
1213 * @param string $filename
1215 function setFilename( $filename ) {
1216 $this->filename = $filename;
1220 * @param string $archiveName
1222 function setArchiveName( $archiveName ) {
1223 $this->archiveName = $archiveName;
1227 * @param int $size
1229 function setSize( $size ) {
1230 $this->size = intval( $size );
1234 * @param string $type
1236 function setType( $type ) {
1237 $this->type = $type;
1241 * @param string $action
1243 function setAction( $action ) {
1244 $this->action = $action;
1248 * @param array $params
1250 function setParams( $params ) {
1251 $this->params = $params;
1255 * @param bool $noupdates
1257 public function setNoUpdates( $noupdates ) {
1258 $this->mNoUpdates = $noupdates;
1262 * @return Title
1264 function getTitle() {
1265 return $this->title;
1269 * @return int
1271 function getID() {
1272 return $this->id;
1276 * @return string
1278 function getTimestamp() {
1279 return $this->timestamp;
1283 * @return string
1285 function getUser() {
1286 return $this->user_text;
1290 * @return string
1292 * @deprecated Since 1.21, use getContent() instead.
1294 function getText() {
1295 ContentHandler::deprecated( __METHOD__, '1.21' );
1297 return $this->text;
1301 * @return ContentHandler
1303 function getContentHandler() {
1304 if ( is_null( $this->contentHandler ) ) {
1305 $this->contentHandler = ContentHandler::getForModelID( $this->getModel() );
1308 return $this->contentHandler;
1312 * @return Content
1314 function getContent() {
1315 if ( is_null( $this->content ) ) {
1316 $handler = $this->getContentHandler();
1317 $this->content = $handler->unserializeContent( $this->text, $this->getFormat() );
1320 return $this->content;
1324 * @return string
1326 function getModel() {
1327 if ( is_null( $this->model ) ) {
1328 $this->model = $this->getTitle()->getContentModel();
1331 return $this->model;
1335 * @return string
1337 function getFormat() {
1338 if ( is_null( $this->format ) ) {
1339 $this->format = $this->getContentHandler()->getDefaultFormat();
1342 return $this->format;
1346 * @return string
1348 function getComment() {
1349 return $this->comment;
1353 * @return bool
1355 function getMinor() {
1356 return $this->minor;
1360 * @return mixed
1362 function getSrc() {
1363 return $this->src;
1367 * @return bool|string
1369 function getSha1() {
1370 if ( $this->sha1base36 ) {
1371 return wfBaseConvert( $this->sha1base36, 36, 16 );
1373 return false;
1377 * @return string
1379 function getFileSrc() {
1380 return $this->fileSrc;
1384 * @return bool
1386 function isTempSrc() {
1387 return $this->isTemp;
1391 * @return mixed
1393 function getFilename() {
1394 return $this->filename;
1398 * @return string
1400 function getArchiveName() {
1401 return $this->archiveName;
1405 * @return mixed
1407 function getSize() {
1408 return $this->size;
1412 * @return string
1414 function getType() {
1415 return $this->type;
1419 * @return string
1421 function getAction() {
1422 return $this->action;
1426 * @return string
1428 function getParams() {
1429 return $this->params;
1433 * @return bool
1435 function importOldRevision() {
1436 $dbw = wfGetDB( DB_MASTER );
1438 # Sneak a single revision into place
1439 $user = User::newFromName( $this->getUser() );
1440 if ( $user ) {
1441 $userId = intval( $user->getId() );
1442 $userText = $user->getName();
1443 $userObj = $user;
1444 } else {
1445 $userId = 0;
1446 $userText = $this->getUser();
1447 $userObj = new User;
1450 // avoid memory leak...?
1451 $linkCache = LinkCache::singleton();
1452 $linkCache->clear();
1454 $page = WikiPage::factory( $this->title );
1455 $page->loadPageData( 'fromdbmaster' );
1456 if ( !$page->exists() ) {
1457 # must create the page...
1458 $pageId = $page->insertOn( $dbw );
1459 $created = true;
1460 $oldcountable = null;
1461 } else {
1462 $pageId = $page->getId();
1463 $created = false;
1465 $prior = $dbw->selectField( 'revision', '1',
1466 array( 'rev_page' => $pageId,
1467 'rev_timestamp' => $dbw->timestamp( $this->timestamp ),
1468 'rev_user_text' => $userText,
1469 'rev_comment' => $this->getComment() ),
1470 __METHOD__
1472 if ( $prior ) {
1473 // @todo FIXME: This could fail slightly for multiple matches :P
1474 wfDebug( __METHOD__ . ": skipping existing revision for [[" .
1475 $this->title->getPrefixedText() . "]], timestamp " . $this->timestamp . "\n" );
1476 return false;
1478 $oldcountable = $page->isCountable();
1481 # @todo FIXME: Use original rev_id optionally (better for backups)
1482 # Insert the row
1483 $revision = new Revision( array(
1484 'title' => $this->title,
1485 'page' => $pageId,
1486 'content_model' => $this->getModel(),
1487 'content_format' => $this->getFormat(),
1488 //XXX: just set 'content' => $this->getContent()?
1489 'text' => $this->getContent()->serialize( $this->getFormat() ),
1490 'comment' => $this->getComment(),
1491 'user' => $userId,
1492 'user_text' => $userText,
1493 'timestamp' => $this->timestamp,
1494 'minor_edit' => $this->minor,
1495 ) );
1496 $revision->insertOn( $dbw );
1497 $changed = $page->updateIfNewerOn( $dbw, $revision );
1499 if ( $changed !== false && !$this->mNoUpdates ) {
1500 wfDebug( __METHOD__ . ": running updates\n" );
1501 $page->doEditUpdates(
1502 $revision,
1503 $userObj,
1504 array( 'created' => $created, 'oldcountable' => $oldcountable )
1508 return true;
1511 function importLogItem() {
1512 $dbw = wfGetDB( DB_MASTER );
1513 # @todo FIXME: This will not record autoblocks
1514 if ( !$this->getTitle() ) {
1515 wfDebug( __METHOD__ . ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1516 $this->timestamp . "\n" );
1517 return;
1519 # Check if it exists already
1520 // @todo FIXME: Use original log ID (better for backups)
1521 $prior = $dbw->selectField( 'logging', '1',
1522 array( 'log_type' => $this->getType(),
1523 'log_action' => $this->getAction(),
1524 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
1525 'log_namespace' => $this->getTitle()->getNamespace(),
1526 'log_title' => $this->getTitle()->getDBkey(),
1527 'log_comment' => $this->getComment(),
1528 #'log_user_text' => $this->user_text,
1529 'log_params' => $this->params ),
1530 __METHOD__
1532 // @todo FIXME: This could fail slightly for multiple matches :P
1533 if ( $prior ) {
1534 wfDebug( __METHOD__
1535 . ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp "
1536 . $this->timestamp . "\n" );
1537 return;
1539 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1540 $data = array(
1541 'log_id' => $log_id,
1542 'log_type' => $this->type,
1543 'log_action' => $this->action,
1544 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
1545 'log_user' => User::idFromName( $this->user_text ),
1546 #'log_user_text' => $this->user_text,
1547 'log_namespace' => $this->getTitle()->getNamespace(),
1548 'log_title' => $this->getTitle()->getDBkey(),
1549 'log_comment' => $this->getComment(),
1550 'log_params' => $this->params
1552 $dbw->insert( 'logging', $data, __METHOD__ );
1556 * @return bool
1558 function importUpload() {
1559 # Construct a file
1560 $archiveName = $this->getArchiveName();
1561 if ( $archiveName ) {
1562 wfDebug( __METHOD__ . "Importing archived file as $archiveName\n" );
1563 $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
1564 RepoGroup::singleton()->getLocalRepo(), $archiveName );
1565 } else {
1566 $file = wfLocalFile( $this->getTitle() );
1567 wfDebug( __METHOD__ . 'Importing new file as ' . $file->getName() . "\n" );
1568 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1569 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1570 $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
1571 RepoGroup::singleton()->getLocalRepo(), $archiveName );
1572 wfDebug( __METHOD__ . "File already exists; importing as $archiveName\n" );
1575 if ( !$file ) {
1576 wfDebug( __METHOD__ . ': Bad file for ' . $this->getTitle() . "\n" );
1577 return false;
1580 # Get the file source or download if necessary
1581 $source = $this->getFileSrc();
1582 $flags = $this->isTempSrc() ? File::DELETE_SOURCE : 0;
1583 if ( !$source ) {
1584 $source = $this->downloadSource();
1585 $flags |= File::DELETE_SOURCE;
1587 if ( !$source ) {
1588 wfDebug( __METHOD__ . ": Could not fetch remote file.\n" );
1589 return false;
1591 $sha1 = $this->getSha1();
1592 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1593 if ( $flags & File::DELETE_SOURCE ) {
1594 # Broken file; delete it if it is a temporary file
1595 unlink( $source );
1597 wfDebug( __METHOD__ . ": Corrupt file $source.\n" );
1598 return false;
1601 $user = User::newFromName( $this->user_text );
1603 # Do the actual upload
1604 if ( $archiveName ) {
1605 $status = $file->uploadOld( $source, $archiveName,
1606 $this->getTimestamp(), $this->getComment(), $user, $flags );
1607 } else {
1608 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1609 $flags, false, $this->getTimestamp(), $user );
1612 if ( $status->isGood() ) {
1613 wfDebug( __METHOD__ . ": Successful\n" );
1614 return true;
1615 } else {
1616 wfDebug( __METHOD__ . ': failed: ' . $status->getXml() . "\n" );
1617 return false;
1622 * @return bool|string
1624 function downloadSource() {
1625 if ( !$this->config->get( 'EnableUploads' ) ) {
1626 return false;
1629 $tempo = tempnam( wfTempDir(), 'download' );
1630 $f = fopen( $tempo, 'wb' );
1631 if ( !$f ) {
1632 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1633 return false;
1636 // @todo FIXME!
1637 $src = $this->getSrc();
1638 $data = Http::get( $src );
1639 if ( !$data ) {
1640 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1641 fclose( $f );
1642 unlink( $tempo );
1643 return false;
1646 fwrite( $f, $data );
1647 fclose( $f );
1649 return $tempo;
1655 * @todo document (e.g. one-sentence class description).
1656 * @ingroup SpecialPage
1658 class ImportStringSource {
1659 function __construct( $string ) {
1660 $this->mString = $string;
1661 $this->mRead = false;
1665 * @return bool
1667 function atEnd() {
1668 return $this->mRead;
1672 * @return bool|string
1674 function readChunk() {
1675 if ( $this->atEnd() ) {
1676 return false;
1678 $this->mRead = true;
1679 return $this->mString;
1684 * @todo document (e.g. one-sentence class description).
1685 * @ingroup SpecialPage
1687 class ImportStreamSource {
1688 function __construct( $handle ) {
1689 $this->mHandle = $handle;
1693 * @return bool
1695 function atEnd() {
1696 return feof( $this->mHandle );
1700 * @return string
1702 function readChunk() {
1703 return fread( $this->mHandle, 32768 );
1707 * @param string $filename
1708 * @return Status
1710 static function newFromFile( $filename ) {
1711 wfSuppressWarnings();
1712 $file = fopen( $filename, 'rt' );
1713 wfRestoreWarnings();
1714 if ( !$file ) {
1715 return Status::newFatal( "importcantopen" );
1717 return Status::newGood( new ImportStreamSource( $file ) );
1721 * @param string $fieldname
1722 * @return Status
1724 static function newFromUpload( $fieldname = "xmlimport" ) {
1725 $upload =& $_FILES[$fieldname];
1727 if ( $upload === null || !$upload['name'] ) {
1728 return Status::newFatal( 'importnofile' );
1730 if ( !empty( $upload['error'] ) ) {
1731 switch ( $upload['error'] ) {
1732 case 1:
1733 # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1734 return Status::newFatal( 'importuploaderrorsize' );
1735 case 2:
1736 # The uploaded file exceeds the MAX_FILE_SIZE directive that
1737 # was specified in the HTML form.
1738 return Status::newFatal( 'importuploaderrorsize' );
1739 case 3:
1740 # The uploaded file was only partially uploaded
1741 return Status::newFatal( 'importuploaderrorpartial' );
1742 case 6:
1743 # Missing a temporary folder.
1744 return Status::newFatal( 'importuploaderrortemp' );
1745 # case else: # Currently impossible
1749 $fname = $upload['tmp_name'];
1750 if ( is_uploaded_file( $fname ) ) {
1751 return ImportStreamSource::newFromFile( $fname );
1752 } else {
1753 return Status::newFatal( 'importnofile' );
1758 * @param string $url
1759 * @param string $method
1760 * @return Status
1762 static function newFromURL( $url, $method = 'GET' ) {
1763 wfDebug( __METHOD__ . ": opening $url\n" );
1764 # Use the standard HTTP fetch function; it times out
1765 # quicker and sorts out user-agent problems which might
1766 # otherwise prevent importing from large sites, such
1767 # as the Wikimedia cluster, etc.
1768 $data = Http::request( $method, $url, array( 'followRedirects' => true ) );
1769 if ( $data !== false ) {
1770 $file = tmpfile();
1771 fwrite( $file, $data );
1772 fflush( $file );
1773 fseek( $file, 0 );
1774 return Status::newGood( new ImportStreamSource( $file ) );
1775 } else {
1776 return Status::newFatal( 'importcantopen' );
1781 * @param string $interwiki
1782 * @param string $page
1783 * @param bool $history
1784 * @param bool $templates
1785 * @param int $pageLinkDepth
1786 * @return Status
1788 public static function newFromInterwiki( $interwiki, $page, $history = false,
1789 $templates = false, $pageLinkDepth = 0
1791 if ( $page == '' ) {
1792 return Status::newFatal( 'import-noarticle' );
1794 $link = Title::newFromText( "$interwiki:Special:Export/$page" );
1795 if ( is_null( $link ) || !$link->isExternal() ) {
1796 return Status::newFatal( 'importbadinterwiki' );
1797 } else {
1798 $params = array();
1799 if ( $history ) {
1800 $params['history'] = 1;
1802 if ( $templates ) {
1803 $params['templates'] = 1;
1805 if ( $pageLinkDepth ) {
1806 $params['pagelink-depth'] = $pageLinkDepth;
1808 $url = $link->getFullURL( $params );
1809 # For interwikis, use POST to avoid redirects.
1810 return ImportStreamSource::newFromURL( $url, "POST" );