Move MemcachedBagOStuff b/c logic to ObjectCache
[mediawiki.git] / includes / Import.php
blob33ab4eacedd3fb1b3cb9be2e491ffa39258a09a0
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 $foreignNamespaces = null;
36 private $mLogItemCallback, $mUploadCallback, $mRevisionCallback, $mPageCallback;
37 private $mSiteInfoCallback, $mPageOutCallback;
38 private $mNoticeCallback, $mDebug;
39 private $mImportUploads, $mImageBasePath;
40 private $mNoUpdates = false;
41 /** @var Config */
42 private $config;
43 /** @var ImportTitleFactory */
44 private $importTitleFactory;
45 /** @var array */
46 private $countableCache = array();
48 /**
49 * Creates an ImportXMLReader drawing from the source provided
50 * @param ImportSource $source
51 * @param Config $config
52 * @throws Exception
54 function __construct( ImportSource $source, Config $config = null ) {
55 if ( !class_exists( 'XMLReader' ) ) {
56 throw new Exception( 'Import requires PHP to have been compiled with libxml support' );
59 $this->reader = new XMLReader();
60 if ( !$config ) {
61 wfDeprecated( __METHOD__ . ' without a Config instance', '1.25' );
62 $config = ConfigFactory::getDefaultInstance()->makeConfig( 'main' );
64 $this->config = $config;
66 if ( !in_array( 'uploadsource', stream_get_wrappers() ) ) {
67 stream_wrapper_register( 'uploadsource', 'UploadSourceAdapter' );
69 $id = UploadSourceAdapter::registerSource( $source );
71 // Enable the entity loader, as it is needed for loading external URLs via
72 // XMLReader::open (T86036)
73 $oldDisable = libxml_disable_entity_loader( false );
74 if ( defined( 'LIBXML_PARSEHUGE' ) ) {
75 $status = $this->reader->open( "uploadsource://$id", null, LIBXML_PARSEHUGE );
76 } else {
77 $status = $this->reader->open( "uploadsource://$id" );
79 if ( !$status ) {
80 $error = libxml_get_last_error();
81 libxml_disable_entity_loader( $oldDisable );
82 throw new MWException( 'Encountered an internal error while initializing WikiImporter object: ' .
83 $error->message );
85 libxml_disable_entity_loader( $oldDisable );
87 // Default callbacks
88 $this->setPageCallback( array( $this, 'beforeImportPage' ) );
89 $this->setRevisionCallback( array( $this, "importRevision" ) );
90 $this->setUploadCallback( array( $this, 'importUpload' ) );
91 $this->setLogItemCallback( array( $this, 'importLogItem' ) );
92 $this->setPageOutCallback( array( $this, 'finishImportPage' ) );
94 $this->importTitleFactory = new NaiveImportTitleFactory();
97 /**
98 * @return null|XMLReader
100 public function getReader() {
101 return $this->reader;
104 public function throwXmlError( $err ) {
105 $this->debug( "FAILURE: $err" );
106 wfDebug( "WikiImporter XML error: $err\n" );
109 public function debug( $data ) {
110 if ( $this->mDebug ) {
111 wfDebug( "IMPORT: $data\n" );
115 public function warn( $data ) {
116 wfDebug( "IMPORT: $data\n" );
119 public function notice( $msg /*, $param, ...*/ ) {
120 $params = func_get_args();
121 array_shift( $params );
123 if ( is_callable( $this->mNoticeCallback ) ) {
124 call_user_func( $this->mNoticeCallback, $msg, $params );
125 } else { # No ImportReporter -> CLI
126 echo wfMessage( $msg, $params )->text() . "\n";
131 * Set debug mode...
132 * @param bool $debug
134 function setDebug( $debug ) {
135 $this->mDebug = $debug;
139 * Set 'no updates' mode. In this mode, the link tables will not be updated by the importer
140 * @param bool $noupdates
142 function setNoUpdates( $noupdates ) {
143 $this->mNoUpdates = $noupdates;
147 * Set a callback that displays notice messages
149 * @param callable $callback
150 * @return callable
152 public function setNoticeCallback( $callback ) {
153 return wfSetVar( $this->mNoticeCallback, $callback );
157 * Sets the action to perform as each new page in the stream is reached.
158 * @param callable $callback
159 * @return callable
161 public function setPageCallback( $callback ) {
162 $previous = $this->mPageCallback;
163 $this->mPageCallback = $callback;
164 return $previous;
168 * Sets the action to perform as each page in the stream is completed.
169 * Callback accepts the page title (as a Title object), a second object
170 * with the original title form (in case it's been overridden into a
171 * local namespace), and a count of revisions.
173 * @param callable $callback
174 * @return callable
176 public function setPageOutCallback( $callback ) {
177 $previous = $this->mPageOutCallback;
178 $this->mPageOutCallback = $callback;
179 return $previous;
183 * Sets the action to perform as each page revision is reached.
184 * @param callable $callback
185 * @return callable
187 public function setRevisionCallback( $callback ) {
188 $previous = $this->mRevisionCallback;
189 $this->mRevisionCallback = $callback;
190 return $previous;
194 * Sets the action to perform as each file upload version is reached.
195 * @param callable $callback
196 * @return callable
198 public function setUploadCallback( $callback ) {
199 $previous = $this->mUploadCallback;
200 $this->mUploadCallback = $callback;
201 return $previous;
205 * Sets the action to perform as each log item reached.
206 * @param callable $callback
207 * @return callable
209 public function setLogItemCallback( $callback ) {
210 $previous = $this->mLogItemCallback;
211 $this->mLogItemCallback = $callback;
212 return $previous;
216 * Sets the action to perform when site info is encountered
217 * @param callable $callback
218 * @return callable
220 public function setSiteInfoCallback( $callback ) {
221 $previous = $this->mSiteInfoCallback;
222 $this->mSiteInfoCallback = $callback;
223 return $previous;
227 * Sets the factory object to use to convert ForeignTitle objects into local
228 * Title objects
229 * @param ImportTitleFactory $factory
231 public function setImportTitleFactory( $factory ) {
232 $this->importTitleFactory = $factory;
236 * Set a target namespace to override the defaults
237 * @param null|int $namespace
238 * @return bool
240 public function setTargetNamespace( $namespace ) {
241 if ( is_null( $namespace ) ) {
242 // Don't override namespaces
243 $this->setImportTitleFactory( new NaiveImportTitleFactory() );
244 return true;
245 } elseif (
246 $namespace >= 0 &&
247 MWNamespace::exists( intval( $namespace ) )
249 $namespace = intval( $namespace );
250 $this->setImportTitleFactory( new NamespaceImportTitleFactory( $namespace ) );
251 return true;
252 } else {
253 return false;
258 * Set a target root page under which all pages are imported
259 * @param null|string $rootpage
260 * @return Status
262 public function setTargetRootPage( $rootpage ) {
263 $status = Status::newGood();
264 if ( is_null( $rootpage ) ) {
265 // No rootpage
266 $this->setImportTitleFactory( new NaiveImportTitleFactory() );
267 } elseif ( $rootpage !== '' ) {
268 $rootpage = rtrim( $rootpage, '/' ); // avoid double slashes
269 $title = Title::newFromText( $rootpage );
271 if ( !$title || $title->isExternal() ) {
272 $status->fatal( 'import-rootpage-invalid' );
273 } else {
274 if ( !MWNamespace::hasSubpages( $title->getNamespace() ) ) {
275 global $wgContLang;
277 $displayNSText = $title->getNamespace() == NS_MAIN
278 ? wfMessage( 'blanknamespace' )->text()
279 : $wgContLang->getNsText( $title->getNamespace() );
280 $status->fatal( 'import-rootpage-nosubpage', $displayNSText );
281 } else {
282 // set namespace to 'all', so the namespace check in processTitle() can pass
283 $this->setTargetNamespace( null );
284 $this->setImportTitleFactory( new SubpageImportTitleFactory( $title ) );
288 return $status;
292 * @param string $dir
294 public function setImageBasePath( $dir ) {
295 $this->mImageBasePath = $dir;
299 * @param bool $import
301 public function setImportUploads( $import ) {
302 $this->mImportUploads = $import;
306 * Default per-page callback. Sets up some things related to site statistics
307 * @param array $titleAndForeignTitle Two-element array, with Title object at
308 * index 0 and ForeignTitle object at index 1
309 * @return bool
311 public function beforeImportPage( $titleAndForeignTitle ) {
312 $title = $titleAndForeignTitle[0];
313 $page = WikiPage::factory( $title );
314 $this->countableCache['title_' . $title->getPrefixedText()] = $page->isCountable();
315 return true;
319 * Default per-revision callback, performs the import.
320 * @param WikiRevision $revision
321 * @return bool
323 public function importRevision( $revision ) {
324 if ( !$revision->getContentHandler()->canBeUsedOn( $revision->getTitle() ) ) {
325 $this->notice( 'import-error-bad-location',
326 $revision->getTitle()->getPrefixedText(),
327 $revision->getID(),
328 $revision->getModel(),
329 $revision->getFormat() );
331 return false;
334 try {
335 $dbw = wfGetDB( DB_MASTER );
336 return $dbw->deadlockLoop( array( $revision, 'importOldRevision' ) );
337 } catch ( MWContentSerializationException $ex ) {
338 $this->notice( 'import-error-unserialize',
339 $revision->getTitle()->getPrefixedText(),
340 $revision->getID(),
341 $revision->getModel(),
342 $revision->getFormat() );
345 return false;
349 * Default per-revision callback, performs the import.
350 * @param WikiRevision $revision
351 * @return bool
353 public function importLogItem( $revision ) {
354 $dbw = wfGetDB( DB_MASTER );
355 return $dbw->deadlockLoop( array( $revision, 'importLogItem' ) );
359 * Dummy for now...
360 * @param WikiRevision $revision
361 * @return bool
363 public function importUpload( $revision ) {
364 $dbw = wfGetDB( DB_MASTER );
365 return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
369 * Mostly for hook use
370 * @param Title $title
371 * @param ForeignTitle $foreignTitle
372 * @param int $revCount
373 * @param int $sRevCount
374 * @param array $pageInfo
375 * @return bool
377 public function finishImportPage( $title, $foreignTitle, $revCount,
378 $sRevCount, $pageInfo ) {
380 // Update article count statistics (T42009)
381 // The normal counting logic in WikiPage->doEditUpdates() is designed for
382 // one-revision-at-a-time editing, not bulk imports. In this situation it
383 // suffers from issues of slave lag. We let WikiPage handle the total page
384 // and revision count, and we implement our own custom logic for the
385 // article (content page) count.
386 $page = WikiPage::factory( $title );
387 $page->loadPageData( 'fromdbmaster' );
388 $content = $page->getContent();
389 if ( $content === null ) {
390 wfDebug( __METHOD__ . ': Skipping article count adjustment for ' . $title .
391 ' because WikiPage::getContent() returned null' );
392 } else {
393 $editInfo = $page->prepareContentForEdit( $content );
394 $countKey = 'title_' . $title->getPrefixedText();
395 $countable = $page->isCountable( $editInfo );
396 if ( array_key_exists( $countKey, $this->countableCache ) &&
397 $countable != $this->countableCache[$countKey] ) {
398 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( array(
399 'articles' => ( (int)$countable - (int)$this->countableCache[$countKey] )
400 ) ) );
404 $args = func_get_args();
405 return Hooks::run( 'AfterImportPage', $args );
409 * Alternate per-revision callback, for debugging.
410 * @param WikiRevision $revision
412 public function debugRevisionHandler( &$revision ) {
413 $this->debug( "Got revision:" );
414 if ( is_object( $revision->title ) ) {
415 $this->debug( "-- Title: " . $revision->title->getPrefixedText() );
416 } else {
417 $this->debug( "-- Title: <invalid>" );
419 $this->debug( "-- User: " . $revision->user_text );
420 $this->debug( "-- Timestamp: " . $revision->timestamp );
421 $this->debug( "-- Comment: " . $revision->comment );
422 $this->debug( "-- Text: " . $revision->text );
426 * Notify the callback function of site info
427 * @param array $siteInfo
428 * @return bool|mixed
430 private function siteInfoCallback( $siteInfo ) {
431 if ( isset( $this->mSiteInfoCallback ) ) {
432 return call_user_func_array( $this->mSiteInfoCallback,
433 array( $siteInfo, $this ) );
434 } else {
435 return false;
440 * Notify the callback function when a new "<page>" is reached.
441 * @param Title $title
443 function pageCallback( $title ) {
444 if ( isset( $this->mPageCallback ) ) {
445 call_user_func( $this->mPageCallback, $title );
450 * Notify the callback function when a "</page>" is closed.
451 * @param Title $title
452 * @param ForeignTitle $foreignTitle
453 * @param int $revCount
454 * @param int $sucCount Number of revisions for which callback returned true
455 * @param array $pageInfo Associative array of page information
457 private function pageOutCallback( $title, $foreignTitle, $revCount,
458 $sucCount, $pageInfo ) {
459 if ( isset( $this->mPageOutCallback ) ) {
460 $args = func_get_args();
461 call_user_func_array( $this->mPageOutCallback, $args );
466 * Notify the callback function of a revision
467 * @param WikiRevision $revision
468 * @return bool|mixed
470 private function revisionCallback( $revision ) {
471 if ( isset( $this->mRevisionCallback ) ) {
472 return call_user_func_array( $this->mRevisionCallback,
473 array( $revision, $this ) );
474 } else {
475 return false;
480 * Notify the callback function of a new log item
481 * @param WikiRevision $revision
482 * @return bool|mixed
484 private function logItemCallback( $revision ) {
485 if ( isset( $this->mLogItemCallback ) ) {
486 return call_user_func_array( $this->mLogItemCallback,
487 array( $revision, $this ) );
488 } else {
489 return false;
494 * Retrieves the contents of the named attribute of the current element.
495 * @param string $attr The name of the attribute
496 * @return string The value of the attribute or an empty string if it is not set in the current
497 * element.
499 public function nodeAttribute( $attr ) {
500 return $this->reader->getAttribute( $attr );
504 * Shouldn't something like this be built-in to XMLReader?
505 * Fetches text contents of the current element, assuming
506 * no sub-elements or such scary things.
507 * @return string
508 * @access private
510 public function nodeContents() {
511 if ( $this->reader->isEmptyElement ) {
512 return "";
514 $buffer = "";
515 while ( $this->reader->read() ) {
516 switch ( $this->reader->nodeType ) {
517 case XMLReader::TEXT:
518 case XMLReader::SIGNIFICANT_WHITESPACE:
519 $buffer .= $this->reader->value;
520 break;
521 case XMLReader::END_ELEMENT:
522 return $buffer;
526 $this->reader->close();
527 return '';
531 * Primary entry point
532 * @throws MWException
533 * @return bool
535 public function doImport() {
536 // Calls to reader->read need to be wrapped in calls to
537 // libxml_disable_entity_loader() to avoid local file
538 // inclusion attacks (bug 46932).
539 $oldDisable = libxml_disable_entity_loader( true );
540 $this->reader->read();
542 if ( $this->reader->localName != 'mediawiki' ) {
543 libxml_disable_entity_loader( $oldDisable );
544 throw new MWException( "Expected <mediawiki> tag, got " .
545 $this->reader->localName );
547 $this->debug( "<mediawiki> tag is correct." );
549 $this->debug( "Starting primary dump processing loop." );
551 $keepReading = $this->reader->read();
552 $skip = false;
553 $rethrow = null;
554 try {
555 while ( $keepReading ) {
556 $tag = $this->reader->localName;
557 $type = $this->reader->nodeType;
559 if ( !Hooks::run( 'ImportHandleToplevelXMLTag', array( $this ) ) ) {
560 // Do nothing
561 } elseif ( $tag == 'mediawiki' && $type == XMLReader::END_ELEMENT ) {
562 break;
563 } elseif ( $tag == 'siteinfo' ) {
564 $this->handleSiteInfo();
565 } elseif ( $tag == 'page' ) {
566 $this->handlePage();
567 } elseif ( $tag == 'logitem' ) {
568 $this->handleLogItem();
569 } elseif ( $tag != '#text' ) {
570 $this->warn( "Unhandled top-level XML tag $tag" );
572 $skip = true;
575 if ( $skip ) {
576 $keepReading = $this->reader->next();
577 $skip = false;
578 $this->debug( "Skip" );
579 } else {
580 $keepReading = $this->reader->read();
583 } catch ( Exception $ex ) {
584 $rethrow = $ex;
587 // finally
588 libxml_disable_entity_loader( $oldDisable );
589 $this->reader->close();
591 if ( $rethrow ) {
592 throw $rethrow;
595 return true;
598 private function handleSiteInfo() {
599 $this->debug( "Enter site info handler." );
600 $siteInfo = array();
602 // Fields that can just be stuffed in the siteInfo object
603 $normalFields = array( 'sitename', 'base', 'generator', 'case' );
605 while ( $this->reader->read() ) {
606 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
607 $this->reader->localName == 'siteinfo' ) {
608 break;
611 $tag = $this->reader->localName;
613 if ( $tag == 'namespace' ) {
614 $this->foreignNamespaces[$this->nodeAttribute( 'key' )] =
615 $this->nodeContents();
616 } elseif ( in_array( $tag, $normalFields ) ) {
617 $siteInfo[$tag] = $this->nodeContents();
621 $siteInfo['_namespaces'] = $this->foreignNamespaces;
622 $this->siteInfoCallback( $siteInfo );
625 private function handleLogItem() {
626 $this->debug( "Enter log item handler." );
627 $logInfo = array();
629 // Fields that can just be stuffed in the pageInfo object
630 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
631 'logtitle', 'params' );
633 while ( $this->reader->read() ) {
634 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
635 $this->reader->localName == 'logitem' ) {
636 break;
639 $tag = $this->reader->localName;
641 if ( !Hooks::run( 'ImportHandleLogItemXMLTag', array(
642 $this, $logInfo
643 ) ) ) {
644 // Do nothing
645 } elseif ( in_array( $tag, $normalFields ) ) {
646 $logInfo[$tag] = $this->nodeContents();
647 } elseif ( $tag == 'contributor' ) {
648 $logInfo['contributor'] = $this->handleContributor();
649 } elseif ( $tag != '#text' ) {
650 $this->warn( "Unhandled log-item XML tag $tag" );
654 $this->processLogItem( $logInfo );
658 * @param array $logInfo
659 * @return bool|mixed
661 private function processLogItem( $logInfo ) {
662 $revision = new WikiRevision( $this->config );
664 $revision->setID( $logInfo['id'] );
665 $revision->setType( $logInfo['type'] );
666 $revision->setAction( $logInfo['action'] );
667 $revision->setTimestamp( $logInfo['timestamp'] );
668 $revision->setParams( $logInfo['params'] );
669 $revision->setTitle( Title::newFromText( $logInfo['logtitle'] ) );
670 $revision->setNoUpdates( $this->mNoUpdates );
672 if ( isset( $logInfo['comment'] ) ) {
673 $revision->setComment( $logInfo['comment'] );
676 if ( isset( $logInfo['contributor']['ip'] ) ) {
677 $revision->setUserIP( $logInfo['contributor']['ip'] );
679 if ( isset( $logInfo['contributor']['username'] ) ) {
680 $revision->setUserName( $logInfo['contributor']['username'] );
683 return $this->logItemCallback( $revision );
686 private function handlePage() {
687 // Handle page data.
688 $this->debug( "Enter page handler." );
689 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
691 // Fields that can just be stuffed in the pageInfo object
692 $normalFields = array( 'title', 'ns', 'id', 'redirect', 'restrictions' );
694 $skip = false;
695 $badTitle = false;
697 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
698 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
699 $this->reader->localName == 'page' ) {
700 break;
703 $skip = false;
705 $tag = $this->reader->localName;
707 if ( $badTitle ) {
708 // The title is invalid, bail out of this page
709 $skip = true;
710 } elseif ( !Hooks::run( 'ImportHandlePageXMLTag', array( $this,
711 &$pageInfo ) ) ) {
712 // Do nothing
713 } elseif ( in_array( $tag, $normalFields ) ) {
714 // An XML snippet:
715 // <page>
716 // <id>123</id>
717 // <title>Page</title>
718 // <redirect title="NewTitle"/>
719 // ...
720 // Because the redirect tag is built differently, we need special handling for that case.
721 if ( $tag == 'redirect' ) {
722 $pageInfo[$tag] = $this->nodeAttribute( 'title' );
723 } else {
724 $pageInfo[$tag] = $this->nodeContents();
726 } elseif ( $tag == 'revision' || $tag == 'upload' ) {
727 if ( !isset( $title ) ) {
728 $title = $this->processTitle( $pageInfo['title'],
729 isset( $pageInfo['ns'] ) ? $pageInfo['ns'] : null );
731 // $title is either an array of two titles or false.
732 if ( is_array( $title ) ) {
733 $this->pageCallback( $title );
734 list( $pageInfo['_title'], $foreignTitle ) = $title;
735 } else {
736 $badTitle = true;
737 $skip = true;
741 if ( $title ) {
742 if ( $tag == 'revision' ) {
743 $this->handleRevision( $pageInfo );
744 } else {
745 $this->handleUpload( $pageInfo );
748 } elseif ( $tag != '#text' ) {
749 $this->warn( "Unhandled page XML tag $tag" );
750 $skip = true;
754 // @note $pageInfo is only set if a valid $title is processed above with
755 // no error. If we have a valid $title, then pageCallback is called
756 // above, $pageInfo['title'] is set and we do pageOutCallback here.
757 // If $pageInfo['_title'] is not set, then $foreignTitle is also not
758 // set since they both come from $title above.
759 if ( array_key_exists( '_title', $pageInfo ) ) {
760 $this->pageOutCallback( $pageInfo['_title'], $foreignTitle,
761 $pageInfo['revisionCount'],
762 $pageInfo['successfulRevisionCount'],
763 $pageInfo );
768 * @param array $pageInfo
770 private function handleRevision( &$pageInfo ) {
771 $this->debug( "Enter revision handler" );
772 $revisionInfo = array();
774 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'model', 'format', 'text' );
776 $skip = false;
778 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
779 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
780 $this->reader->localName == 'revision' ) {
781 break;
784 $tag = $this->reader->localName;
786 if ( !Hooks::run( 'ImportHandleRevisionXMLTag', array(
787 $this, $pageInfo, $revisionInfo
788 ) ) ) {
789 // Do nothing
790 } elseif ( in_array( $tag, $normalFields ) ) {
791 $revisionInfo[$tag] = $this->nodeContents();
792 } elseif ( $tag == 'contributor' ) {
793 $revisionInfo['contributor'] = $this->handleContributor();
794 } elseif ( $tag != '#text' ) {
795 $this->warn( "Unhandled revision XML tag $tag" );
796 $skip = true;
800 $pageInfo['revisionCount']++;
801 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
802 $pageInfo['successfulRevisionCount']++;
807 * @param array $pageInfo
808 * @param array $revisionInfo
809 * @return bool|mixed
811 private function processRevision( $pageInfo, $revisionInfo ) {
812 $revision = new WikiRevision( $this->config );
814 if ( isset( $revisionInfo['id'] ) ) {
815 $revision->setID( $revisionInfo['id'] );
817 if ( isset( $revisionInfo['model'] ) ) {
818 $revision->setModel( $revisionInfo['model'] );
820 if ( isset( $revisionInfo['format'] ) ) {
821 $revision->setFormat( $revisionInfo['format'] );
823 $revision->setTitle( $pageInfo['_title'] );
825 if ( isset( $revisionInfo['text'] ) ) {
826 $handler = $revision->getContentHandler();
827 $text = $handler->importTransform(
828 $revisionInfo['text'],
829 $revision->getFormat() );
831 $revision->setText( $text );
833 if ( isset( $revisionInfo['timestamp'] ) ) {
834 $revision->setTimestamp( $revisionInfo['timestamp'] );
835 } else {
836 $revision->setTimestamp( wfTimestampNow() );
839 if ( isset( $revisionInfo['comment'] ) ) {
840 $revision->setComment( $revisionInfo['comment'] );
843 if ( isset( $revisionInfo['minor'] ) ) {
844 $revision->setMinor( true );
846 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
847 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
849 if ( isset( $revisionInfo['contributor']['username'] ) ) {
850 $revision->setUserName( $revisionInfo['contributor']['username'] );
852 $revision->setNoUpdates( $this->mNoUpdates );
854 return $this->revisionCallback( $revision );
858 * @param array $pageInfo
859 * @return mixed
861 private function handleUpload( &$pageInfo ) {
862 $this->debug( "Enter upload handler" );
863 $uploadInfo = array();
865 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
866 'src', 'size', 'sha1base36', 'archivename', 'rel' );
868 $skip = false;
870 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
871 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
872 $this->reader->localName == 'upload' ) {
873 break;
876 $tag = $this->reader->localName;
878 if ( !Hooks::run( 'ImportHandleUploadXMLTag', array(
879 $this, $pageInfo
880 ) ) ) {
881 // Do nothing
882 } elseif ( in_array( $tag, $normalFields ) ) {
883 $uploadInfo[$tag] = $this->nodeContents();
884 } elseif ( $tag == 'contributor' ) {
885 $uploadInfo['contributor'] = $this->handleContributor();
886 } elseif ( $tag == 'contents' ) {
887 $contents = $this->nodeContents();
888 $encoding = $this->reader->getAttribute( 'encoding' );
889 if ( $encoding === 'base64' ) {
890 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
891 $uploadInfo['isTempSrc'] = true;
893 } elseif ( $tag != '#text' ) {
894 $this->warn( "Unhandled upload XML tag $tag" );
895 $skip = true;
899 if ( $this->mImageBasePath && isset( $uploadInfo['rel'] ) ) {
900 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
901 if ( file_exists( $path ) ) {
902 $uploadInfo['fileSrc'] = $path;
903 $uploadInfo['isTempSrc'] = false;
907 if ( $this->mImportUploads ) {
908 return $this->processUpload( $pageInfo, $uploadInfo );
913 * @param string $contents
914 * @return string
916 private function dumpTemp( $contents ) {
917 $filename = tempnam( wfTempDir(), 'importupload' );
918 file_put_contents( $filename, $contents );
919 return $filename;
923 * @param array $pageInfo
924 * @param array $uploadInfo
925 * @return mixed
927 private function processUpload( $pageInfo, $uploadInfo ) {
928 $revision = new WikiRevision( $this->config );
929 $text = isset( $uploadInfo['text'] ) ? $uploadInfo['text'] : '';
931 $revision->setTitle( $pageInfo['_title'] );
932 $revision->setID( $pageInfo['id'] );
933 $revision->setTimestamp( $uploadInfo['timestamp'] );
934 $revision->setText( $text );
935 $revision->setFilename( $uploadInfo['filename'] );
936 if ( isset( $uploadInfo['archivename'] ) ) {
937 $revision->setArchiveName( $uploadInfo['archivename'] );
939 $revision->setSrc( $uploadInfo['src'] );
940 if ( isset( $uploadInfo['fileSrc'] ) ) {
941 $revision->setFileSrc( $uploadInfo['fileSrc'],
942 !empty( $uploadInfo['isTempSrc'] ) );
944 if ( isset( $uploadInfo['sha1base36'] ) ) {
945 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
947 $revision->setSize( intval( $uploadInfo['size'] ) );
948 $revision->setComment( $uploadInfo['comment'] );
950 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
951 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
953 if ( isset( $uploadInfo['contributor']['username'] ) ) {
954 $revision->setUserName( $uploadInfo['contributor']['username'] );
956 $revision->setNoUpdates( $this->mNoUpdates );
958 return call_user_func( $this->mUploadCallback, $revision );
962 * @return array
964 private function handleContributor() {
965 $fields = array( 'id', 'ip', 'username' );
966 $info = array();
968 while ( $this->reader->read() ) {
969 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
970 $this->reader->localName == 'contributor' ) {
971 break;
974 $tag = $this->reader->localName;
976 if ( in_array( $tag, $fields ) ) {
977 $info[$tag] = $this->nodeContents();
981 return $info;
985 * @param string $text
986 * @param string|null $ns
987 * @return array|bool
989 private function processTitle( $text, $ns = null ) {
990 if ( is_null( $this->foreignNamespaces ) ) {
991 $foreignTitleFactory = new NaiveForeignTitleFactory();
992 } else {
993 $foreignTitleFactory = new NamespaceAwareForeignTitleFactory(
994 $this->foreignNamespaces );
997 $foreignTitle = $foreignTitleFactory->createForeignTitle( $text,
998 intval( $ns ) );
1000 $title = $this->importTitleFactory->createTitleFromForeignTitle(
1001 $foreignTitle );
1003 $commandLineMode = $this->config->get( 'CommandLineMode' );
1004 if ( is_null( $title ) ) {
1005 # Invalid page title? Ignore the page
1006 $this->notice( 'import-error-invalid', $foreignTitle->getFullText() );
1007 return false;
1008 } elseif ( $title->isExternal() ) {
1009 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
1010 return false;
1011 } elseif ( !$title->canExist() ) {
1012 $this->notice( 'import-error-special', $title->getPrefixedText() );
1013 return false;
1014 } elseif ( !$title->userCan( 'edit' ) && !$commandLineMode ) {
1015 # Do not import if the importing wiki user cannot edit this page
1016 $this->notice( 'import-error-edit', $title->getPrefixedText() );
1017 return false;
1018 } elseif ( !$title->exists() && !$title->userCan( 'create' ) && !$commandLineMode ) {
1019 # Do not import if the importing wiki user cannot create this page
1020 $this->notice( 'import-error-create', $title->getPrefixedText() );
1021 return false;
1024 return array( $title, $foreignTitle );
1028 /** This is a horrible hack used to keep source compatibility */
1029 class UploadSourceAdapter {
1030 /** @var array */
1031 public static $sourceRegistrations = array();
1033 /** @var string */
1034 private $mSource;
1036 /** @var string */
1037 private $mBuffer;
1039 /** @var int */
1040 private $mPosition;
1043 * @param ImportSource $source
1044 * @return string
1046 static function registerSource( ImportSource $source ) {
1047 $id = wfRandomString();
1049 self::$sourceRegistrations[$id] = $source;
1051 return $id;
1055 * @param string $path
1056 * @param string $mode
1057 * @param array $options
1058 * @param string $opened_path
1059 * @return bool
1061 function stream_open( $path, $mode, $options, &$opened_path ) {
1062 $url = parse_url( $path );
1063 $id = $url['host'];
1065 if ( !isset( self::$sourceRegistrations[$id] ) ) {
1066 return false;
1069 $this->mSource = self::$sourceRegistrations[$id];
1071 return true;
1075 * @param int $count
1076 * @return string
1078 function stream_read( $count ) {
1079 $return = '';
1080 $leave = false;
1082 while ( !$leave && !$this->mSource->atEnd() &&
1083 strlen( $this->mBuffer ) < $count ) {
1084 $read = $this->mSource->readChunk();
1086 if ( !strlen( $read ) ) {
1087 $leave = true;
1090 $this->mBuffer .= $read;
1093 if ( strlen( $this->mBuffer ) ) {
1094 $return = substr( $this->mBuffer, 0, $count );
1095 $this->mBuffer = substr( $this->mBuffer, $count );
1098 $this->mPosition += strlen( $return );
1100 return $return;
1104 * @param string $data
1105 * @return bool
1107 function stream_write( $data ) {
1108 return false;
1112 * @return mixed
1114 function stream_tell() {
1115 return $this->mPosition;
1119 * @return bool
1121 function stream_eof() {
1122 return $this->mSource->atEnd();
1126 * @return array
1128 function url_stat() {
1129 $result = array();
1131 $result['dev'] = $result[0] = 0;
1132 $result['ino'] = $result[1] = 0;
1133 $result['mode'] = $result[2] = 0;
1134 $result['nlink'] = $result[3] = 0;
1135 $result['uid'] = $result[4] = 0;
1136 $result['gid'] = $result[5] = 0;
1137 $result['rdev'] = $result[6] = 0;
1138 $result['size'] = $result[7] = 0;
1139 $result['atime'] = $result[8] = 0;
1140 $result['mtime'] = $result[9] = 0;
1141 $result['ctime'] = $result[10] = 0;
1142 $result['blksize'] = $result[11] = 0;
1143 $result['blocks'] = $result[12] = 0;
1145 return $result;
1150 * @todo document (e.g. one-sentence class description).
1151 * @ingroup SpecialPage
1153 class WikiRevision {
1154 /** @todo Unused? */
1155 public $importer = null;
1157 /** @var Title */
1158 public $title = null;
1160 /** @var int */
1161 public $id = 0;
1163 /** @var string */
1164 public $timestamp = "20010115000000";
1167 * @var int
1168 * @todo Can't find any uses. Public, because that's suspicious. Get clarity. */
1169 public $user = 0;
1171 /** @var string */
1172 public $user_text = "";
1174 /** @var string */
1175 public $model = null;
1177 /** @var string */
1178 public $format = null;
1180 /** @var string */
1181 public $text = "";
1183 /** @var int */
1184 protected $size;
1186 /** @var Content */
1187 public $content = null;
1189 /** @var ContentHandler */
1190 protected $contentHandler = null;
1192 /** @var string */
1193 public $comment = "";
1195 /** @var bool */
1196 public $minor = false;
1198 /** @var string */
1199 public $type = "";
1201 /** @var string */
1202 public $action = "";
1204 /** @var string */
1205 public $params = "";
1207 /** @var string */
1208 public $fileSrc = '';
1210 /** @var bool|string */
1211 public $sha1base36 = false;
1214 * @var bool
1215 * @todo Unused?
1217 public $isTemp = false;
1219 /** @var string */
1220 public $archiveName = '';
1222 protected $filename;
1224 /** @var mixed */
1225 protected $src;
1227 /** @todo Unused? */
1228 public $fileIsTemp;
1230 /** @var bool */
1231 private $mNoUpdates = false;
1233 /** @var Config $config */
1234 private $config;
1236 public function __construct( Config $config ) {
1237 $this->config = $config;
1241 * @param Title $title
1242 * @throws MWException
1244 function setTitle( $title ) {
1245 if ( is_object( $title ) ) {
1246 $this->title = $title;
1247 } elseif ( is_null( $title ) ) {
1248 throw new MWException( "WikiRevision given a null title in import. "
1249 . "You may need to adjust \$wgLegalTitleChars." );
1250 } else {
1251 throw new MWException( "WikiRevision given non-object title in import." );
1256 * @param int $id
1258 function setID( $id ) {
1259 $this->id = $id;
1263 * @param string $ts
1265 function setTimestamp( $ts ) {
1266 # 2003-08-05T18:30:02Z
1267 $this->timestamp = wfTimestamp( TS_MW, $ts );
1271 * @param string $user
1273 function setUsername( $user ) {
1274 $this->user_text = $user;
1278 * @param string $ip
1280 function setUserIP( $ip ) {
1281 $this->user_text = $ip;
1285 * @param string $model
1287 function setModel( $model ) {
1288 $this->model = $model;
1292 * @param string $format
1294 function setFormat( $format ) {
1295 $this->format = $format;
1299 * @param string $text
1301 function setText( $text ) {
1302 $this->text = $text;
1306 * @param string $text
1308 function setComment( $text ) {
1309 $this->comment = $text;
1313 * @param bool $minor
1315 function setMinor( $minor ) {
1316 $this->minor = (bool)$minor;
1320 * @param mixed $src
1322 function setSrc( $src ) {
1323 $this->src = $src;
1327 * @param string $src
1328 * @param bool $isTemp
1330 function setFileSrc( $src, $isTemp ) {
1331 $this->fileSrc = $src;
1332 $this->fileIsTemp = $isTemp;
1336 * @param string $sha1base36
1338 function setSha1Base36( $sha1base36 ) {
1339 $this->sha1base36 = $sha1base36;
1343 * @param string $filename
1345 function setFilename( $filename ) {
1346 $this->filename = $filename;
1350 * @param string $archiveName
1352 function setArchiveName( $archiveName ) {
1353 $this->archiveName = $archiveName;
1357 * @param int $size
1359 function setSize( $size ) {
1360 $this->size = intval( $size );
1364 * @param string $type
1366 function setType( $type ) {
1367 $this->type = $type;
1371 * @param string $action
1373 function setAction( $action ) {
1374 $this->action = $action;
1378 * @param array $params
1380 function setParams( $params ) {
1381 $this->params = $params;
1385 * @param bool $noupdates
1387 public function setNoUpdates( $noupdates ) {
1388 $this->mNoUpdates = $noupdates;
1392 * @return Title
1394 function getTitle() {
1395 return $this->title;
1399 * @return int
1401 function getID() {
1402 return $this->id;
1406 * @return string
1408 function getTimestamp() {
1409 return $this->timestamp;
1413 * @return string
1415 function getUser() {
1416 return $this->user_text;
1420 * @return string
1422 * @deprecated Since 1.21, use getContent() instead.
1424 function getText() {
1425 ContentHandler::deprecated( __METHOD__, '1.21' );
1427 return $this->text;
1431 * @return ContentHandler
1433 function getContentHandler() {
1434 if ( is_null( $this->contentHandler ) ) {
1435 $this->contentHandler = ContentHandler::getForModelID( $this->getModel() );
1438 return $this->contentHandler;
1442 * @return Content
1444 function getContent() {
1445 if ( is_null( $this->content ) ) {
1446 $handler = $this->getContentHandler();
1447 $this->content = $handler->unserializeContent( $this->text, $this->getFormat() );
1450 return $this->content;
1454 * @return string
1456 function getModel() {
1457 if ( is_null( $this->model ) ) {
1458 $this->model = $this->getTitle()->getContentModel();
1461 return $this->model;
1465 * @return string
1467 function getFormat() {
1468 if ( is_null( $this->format ) ) {
1469 $this->format = $this->getContentHandler()->getDefaultFormat();
1472 return $this->format;
1476 * @return string
1478 function getComment() {
1479 return $this->comment;
1483 * @return bool
1485 function getMinor() {
1486 return $this->minor;
1490 * @return mixed
1492 function getSrc() {
1493 return $this->src;
1497 * @return bool|string
1499 function getSha1() {
1500 if ( $this->sha1base36 ) {
1501 return wfBaseConvert( $this->sha1base36, 36, 16 );
1503 return false;
1507 * @return string
1509 function getFileSrc() {
1510 return $this->fileSrc;
1514 * @return bool
1516 function isTempSrc() {
1517 return $this->isTemp;
1521 * @return mixed
1523 function getFilename() {
1524 return $this->filename;
1528 * @return string
1530 function getArchiveName() {
1531 return $this->archiveName;
1535 * @return mixed
1537 function getSize() {
1538 return $this->size;
1542 * @return string
1544 function getType() {
1545 return $this->type;
1549 * @return string
1551 function getAction() {
1552 return $this->action;
1556 * @return string
1558 function getParams() {
1559 return $this->params;
1563 * @return bool
1565 function importOldRevision() {
1566 $dbw = wfGetDB( DB_MASTER );
1568 # Sneak a single revision into place
1569 $user = User::newFromName( $this->getUser() );
1570 if ( $user ) {
1571 $userId = intval( $user->getId() );
1572 $userText = $user->getName();
1573 $userObj = $user;
1574 } else {
1575 $userId = 0;
1576 $userText = $this->getUser();
1577 $userObj = new User;
1580 // avoid memory leak...?
1581 Title::clearCaches();
1583 $page = WikiPage::factory( $this->title );
1584 $page->loadPageData( 'fromdbmaster' );
1585 if ( !$page->exists() ) {
1586 # must create the page...
1587 $pageId = $page->insertOn( $dbw );
1588 $created = true;
1589 $oldcountable = null;
1590 } else {
1591 $pageId = $page->getId();
1592 $created = false;
1594 $prior = $dbw->selectField( 'revision', '1',
1595 array( 'rev_page' => $pageId,
1596 'rev_timestamp' => $dbw->timestamp( $this->timestamp ),
1597 'rev_user_text' => $userText,
1598 'rev_comment' => $this->getComment() ),
1599 __METHOD__
1601 if ( $prior ) {
1602 // @todo FIXME: This could fail slightly for multiple matches :P
1603 wfDebug( __METHOD__ . ": skipping existing revision for [[" .
1604 $this->title->getPrefixedText() . "]], timestamp " . $this->timestamp . "\n" );
1605 return false;
1609 // Select previous version to make size diffs correct
1610 $prevId = $dbw->selectField( 'revision', 'rev_id',
1611 array(
1612 'rev_page' => $pageId,
1613 'rev_timestamp <= ' . $dbw->timestamp( $this->timestamp ),
1615 __METHOD__,
1616 array( 'ORDER BY' => array(
1617 'rev_timestamp DESC',
1618 'rev_id DESC', // timestamp is not unique per page
1623 # @todo FIXME: Use original rev_id optionally (better for backups)
1624 # Insert the row
1625 $revision = new Revision( array(
1626 'title' => $this->title,
1627 'page' => $pageId,
1628 'content_model' => $this->getModel(),
1629 'content_format' => $this->getFormat(),
1630 // XXX: just set 'content' => $this->getContent()?
1631 'text' => $this->getContent()->serialize( $this->getFormat() ),
1632 'comment' => $this->getComment(),
1633 'user' => $userId,
1634 'user_text' => $userText,
1635 'timestamp' => $this->timestamp,
1636 'minor_edit' => $this->minor,
1637 'parent_id' => $prevId,
1638 ) );
1639 $revision->insertOn( $dbw );
1640 $changed = $page->updateIfNewerOn( $dbw, $revision );
1642 if ( $changed !== false && !$this->mNoUpdates ) {
1643 wfDebug( __METHOD__ . ": running updates\n" );
1644 // countable/oldcountable stuff is handled in WikiImporter::finishImportPage
1645 $page->doEditUpdates(
1646 $revision,
1647 $userObj,
1648 array( 'created' => $created, 'oldcountable' => 'no-change' )
1652 return true;
1655 function importLogItem() {
1656 $dbw = wfGetDB( DB_MASTER );
1657 # @todo FIXME: This will not record autoblocks
1658 if ( !$this->getTitle() ) {
1659 wfDebug( __METHOD__ . ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1660 $this->timestamp . "\n" );
1661 return;
1663 # Check if it exists already
1664 // @todo FIXME: Use original log ID (better for backups)
1665 $prior = $dbw->selectField( 'logging', '1',
1666 array( 'log_type' => $this->getType(),
1667 'log_action' => $this->getAction(),
1668 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
1669 'log_namespace' => $this->getTitle()->getNamespace(),
1670 'log_title' => $this->getTitle()->getDBkey(),
1671 'log_comment' => $this->getComment(),
1672 # 'log_user_text' => $this->user_text,
1673 'log_params' => $this->params ),
1674 __METHOD__
1676 // @todo FIXME: This could fail slightly for multiple matches :P
1677 if ( $prior ) {
1678 wfDebug( __METHOD__
1679 . ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp "
1680 . $this->timestamp . "\n" );
1681 return;
1683 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1684 $data = array(
1685 'log_id' => $log_id,
1686 'log_type' => $this->type,
1687 'log_action' => $this->action,
1688 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
1689 'log_user' => User::idFromName( $this->user_text ),
1690 # 'log_user_text' => $this->user_text,
1691 'log_namespace' => $this->getTitle()->getNamespace(),
1692 'log_title' => $this->getTitle()->getDBkey(),
1693 'log_comment' => $this->getComment(),
1694 'log_params' => $this->params
1696 $dbw->insert( 'logging', $data, __METHOD__ );
1700 * @return bool
1702 function importUpload() {
1703 # Construct a file
1704 $archiveName = $this->getArchiveName();
1705 if ( $archiveName ) {
1706 wfDebug( __METHOD__ . "Importing archived file as $archiveName\n" );
1707 $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
1708 RepoGroup::singleton()->getLocalRepo(), $archiveName );
1709 } else {
1710 $file = wfLocalFile( $this->getTitle() );
1711 $file->load( File::READ_LATEST );
1712 wfDebug( __METHOD__ . 'Importing new file as ' . $file->getName() . "\n" );
1713 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1714 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1715 $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
1716 RepoGroup::singleton()->getLocalRepo(), $archiveName );
1717 wfDebug( __METHOD__ . "File already exists; importing as $archiveName\n" );
1720 if ( !$file ) {
1721 wfDebug( __METHOD__ . ': Bad file for ' . $this->getTitle() . "\n" );
1722 return false;
1725 # Get the file source or download if necessary
1726 $source = $this->getFileSrc();
1727 $flags = $this->isTempSrc() ? File::DELETE_SOURCE : 0;
1728 if ( !$source ) {
1729 $source = $this->downloadSource();
1730 $flags |= File::DELETE_SOURCE;
1732 if ( !$source ) {
1733 wfDebug( __METHOD__ . ": Could not fetch remote file.\n" );
1734 return false;
1736 $sha1 = $this->getSha1();
1737 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1738 if ( $flags & File::DELETE_SOURCE ) {
1739 # Broken file; delete it if it is a temporary file
1740 unlink( $source );
1742 wfDebug( __METHOD__ . ": Corrupt file $source.\n" );
1743 return false;
1746 $user = User::newFromName( $this->user_text );
1748 # Do the actual upload
1749 if ( $archiveName ) {
1750 $status = $file->uploadOld( $source, $archiveName,
1751 $this->getTimestamp(), $this->getComment(), $user, $flags );
1752 } else {
1753 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1754 $flags, false, $this->getTimestamp(), $user );
1757 if ( $status->isGood() ) {
1758 wfDebug( __METHOD__ . ": Successful\n" );
1759 return true;
1760 } else {
1761 wfDebug( __METHOD__ . ': failed: ' . $status->getHTML() . "\n" );
1762 return false;
1767 * @return bool|string
1769 function downloadSource() {
1770 if ( !$this->config->get( 'EnableUploads' ) ) {
1771 return false;
1774 $tempo = tempnam( wfTempDir(), 'download' );
1775 $f = fopen( $tempo, 'wb' );
1776 if ( !$f ) {
1777 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1778 return false;
1781 // @todo FIXME!
1782 $src = $this->getSrc();
1783 $data = Http::get( $src, array(), __METHOD__ );
1784 if ( !$data ) {
1785 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1786 fclose( $f );
1787 unlink( $tempo );
1788 return false;
1791 fwrite( $f, $data );
1792 fclose( $f );
1794 return $tempo;
1800 * Source interface for XML import.
1802 interface ImportSource {
1805 * Indicates whether the end of the input has been reached.
1806 * Will return true after a finite number of calls to readChunk.
1808 * @return bool true if there is no more input, false otherwise.
1810 function atEnd();
1813 * Return a chunk of the input, as a (possibly empty) string.
1814 * When the end of input is reached, readChunk() returns false.
1815 * If atEnd() returns false, readChunk() will return a string.
1816 * If atEnd() returns true, readChunk() will return false.
1818 * @return bool|string
1820 function readChunk();
1824 * Used for importing XML dumps where the content of the dump is in a string.
1825 * This class is ineffecient, and should only be used for small dumps.
1826 * For larger dumps, ImportStreamSource should be used instead.
1828 * @ingroup SpecialPage
1830 class ImportStringSource implements ImportSource {
1831 function __construct( $string ) {
1832 $this->mString = $string;
1833 $this->mRead = false;
1837 * @return bool
1839 function atEnd() {
1840 return $this->mRead;
1844 * @return bool|string
1846 function readChunk() {
1847 if ( $this->atEnd() ) {
1848 return false;
1850 $this->mRead = true;
1851 return $this->mString;
1856 * Imports a XML dump from a file (either from file upload, files on disk, or HTTP)
1857 * @ingroup SpecialPage
1859 class ImportStreamSource implements ImportSource {
1860 function __construct( $handle ) {
1861 $this->mHandle = $handle;
1865 * @return bool
1867 function atEnd() {
1868 return feof( $this->mHandle );
1872 * @return string
1874 function readChunk() {
1875 return fread( $this->mHandle, 32768 );
1879 * @param string $filename
1880 * @return Status
1882 static function newFromFile( $filename ) {
1883 MediaWiki\suppressWarnings();
1884 $file = fopen( $filename, 'rt' );
1885 MediaWiki\restoreWarnings();
1886 if ( !$file ) {
1887 return Status::newFatal( "importcantopen" );
1889 return Status::newGood( new ImportStreamSource( $file ) );
1893 * @param string $fieldname
1894 * @return Status
1896 static function newFromUpload( $fieldname = "xmlimport" ) {
1897 $upload =& $_FILES[$fieldname];
1899 if ( $upload === null || !$upload['name'] ) {
1900 return Status::newFatal( 'importnofile' );
1902 if ( !empty( $upload['error'] ) ) {
1903 switch ( $upload['error'] ) {
1904 case 1:
1905 # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1906 return Status::newFatal( 'importuploaderrorsize' );
1907 case 2:
1908 # The uploaded file exceeds the MAX_FILE_SIZE directive that
1909 # was specified in the HTML form.
1910 return Status::newFatal( 'importuploaderrorsize' );
1911 case 3:
1912 # The uploaded file was only partially uploaded
1913 return Status::newFatal( 'importuploaderrorpartial' );
1914 case 6:
1915 # Missing a temporary folder.
1916 return Status::newFatal( 'importuploaderrortemp' );
1917 # case else: # Currently impossible
1921 $fname = $upload['tmp_name'];
1922 if ( is_uploaded_file( $fname ) ) {
1923 return ImportStreamSource::newFromFile( $fname );
1924 } else {
1925 return Status::newFatal( 'importnofile' );
1930 * @param string $url
1931 * @param string $method
1932 * @return Status
1934 static function newFromURL( $url, $method = 'GET' ) {
1935 wfDebug( __METHOD__ . ": opening $url\n" );
1936 # Use the standard HTTP fetch function; it times out
1937 # quicker and sorts out user-agent problems which might
1938 # otherwise prevent importing from large sites, such
1939 # as the Wikimedia cluster, etc.
1940 $data = Http::request( $method, $url, array( 'followRedirects' => true ), __METHOD__ );
1941 if ( $data !== false ) {
1942 $file = tmpfile();
1943 fwrite( $file, $data );
1944 fflush( $file );
1945 fseek( $file, 0 );
1946 return Status::newGood( new ImportStreamSource( $file ) );
1947 } else {
1948 return Status::newFatal( 'importcantopen' );
1953 * @param string $interwiki
1954 * @param string $page
1955 * @param bool $history
1956 * @param bool $templates
1957 * @param int $pageLinkDepth
1958 * @return Status
1960 public static function newFromInterwiki( $interwiki, $page, $history = false,
1961 $templates = false, $pageLinkDepth = 0
1963 if ( $page == '' ) {
1964 return Status::newFatal( 'import-noarticle' );
1966 $link = Title::newFromText( "$interwiki:Special:Export/$page" );
1967 if ( is_null( $link ) || !$link->isExternal() ) {
1968 return Status::newFatal( 'importbadinterwiki' );
1969 } else {
1970 $params = array();
1971 if ( $history ) {
1972 $params['history'] = 1;
1974 if ( $templates ) {
1975 $params['templates'] = 1;
1977 if ( $pageLinkDepth ) {
1978 $params['pagelink-depth'] = $pageLinkDepth;
1980 $url = $link->getFullURL( $params );
1981 # For interwikis, use POST to avoid redirects.
1982 return ImportStreamSource::newFromURL( $url, "POST" );