SpecialLinkSearch: clean up munged query variable handling
[mediawiki.git] / includes / Import.php
blobeb2ca778fef7e70908f13eed83a8e334845626f9
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, $mTargetNamespace, $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
53 function __construct( ImportSource $source, Config $config = null ) {
54 $this->reader = new XMLReader();
55 if ( !$config ) {
56 wfDeprecated( __METHOD__ . ' without a Config instance', '1.25' );
57 $config = ConfigFactory::getDefaultInstance()->makeConfig( 'main' );
59 $this->config = $config;
61 if ( !in_array( 'uploadsource', stream_get_wrappers() ) ) {
62 stream_wrapper_register( 'uploadsource', 'UploadSourceAdapter' );
64 $id = UploadSourceAdapter::registerSource( $source );
65 if ( defined( 'LIBXML_PARSEHUGE' ) ) {
66 $this->reader->open( "uploadsource://$id", null, LIBXML_PARSEHUGE );
67 } else {
68 $this->reader->open( "uploadsource://$id" );
71 // Default callbacks
72 $this->setPageCallback( array( $this, 'beforeImportPage' ) );
73 $this->setRevisionCallback( array( $this, "importRevision" ) );
74 $this->setUploadCallback( array( $this, 'importUpload' ) );
75 $this->setLogItemCallback( array( $this, 'importLogItem' ) );
76 $this->setPageOutCallback( array( $this, 'finishImportPage' ) );
78 $this->importTitleFactory = new NaiveImportTitleFactory();
81 /**
82 * @return null|XMLReader
84 public function getReader() {
85 return $this->reader;
88 public function throwXmlError( $err ) {
89 $this->debug( "FAILURE: $err" );
90 wfDebug( "WikiImporter XML error: $err\n" );
93 public function debug( $data ) {
94 if ( $this->mDebug ) {
95 wfDebug( "IMPORT: $data\n" );
99 public function warn( $data ) {
100 wfDebug( "IMPORT: $data\n" );
103 public function notice( $msg /*, $param, ...*/ ) {
104 $params = func_get_args();
105 array_shift( $params );
107 if ( is_callable( $this->mNoticeCallback ) ) {
108 call_user_func( $this->mNoticeCallback, $msg, $params );
109 } else { # No ImportReporter -> CLI
110 echo wfMessage( $msg, $params )->text() . "\n";
115 * Set debug mode...
116 * @param bool $debug
118 function setDebug( $debug ) {
119 $this->mDebug = $debug;
123 * Set 'no updates' mode. In this mode, the link tables will not be updated by the importer
124 * @param bool $noupdates
126 function setNoUpdates( $noupdates ) {
127 $this->mNoUpdates = $noupdates;
131 * Set a callback that displays notice messages
133 * @param callable $callback
134 * @return callable
136 public function setNoticeCallback( $callback ) {
137 return wfSetVar( $this->mNoticeCallback, $callback );
141 * Sets the action to perform as each new page in the stream is reached.
142 * @param callable $callback
143 * @return callable
145 public function setPageCallback( $callback ) {
146 $previous = $this->mPageCallback;
147 $this->mPageCallback = $callback;
148 return $previous;
152 * Sets the action to perform as each page in the stream is completed.
153 * Callback accepts the page title (as a Title object), a second object
154 * with the original title form (in case it's been overridden into a
155 * local namespace), and a count of revisions.
157 * @param callable $callback
158 * @return callable
160 public function setPageOutCallback( $callback ) {
161 $previous = $this->mPageOutCallback;
162 $this->mPageOutCallback = $callback;
163 return $previous;
167 * Sets the action to perform as each page revision is reached.
168 * @param callable $callback
169 * @return callable
171 public function setRevisionCallback( $callback ) {
172 $previous = $this->mRevisionCallback;
173 $this->mRevisionCallback = $callback;
174 return $previous;
178 * Sets the action to perform as each file upload version is reached.
179 * @param callable $callback
180 * @return callable
182 public function setUploadCallback( $callback ) {
183 $previous = $this->mUploadCallback;
184 $this->mUploadCallback = $callback;
185 return $previous;
189 * Sets the action to perform as each log item reached.
190 * @param callable $callback
191 * @return callable
193 public function setLogItemCallback( $callback ) {
194 $previous = $this->mLogItemCallback;
195 $this->mLogItemCallback = $callback;
196 return $previous;
200 * Sets the action to perform when site info is encountered
201 * @param callable $callback
202 * @return callable
204 public function setSiteInfoCallback( $callback ) {
205 $previous = $this->mSiteInfoCallback;
206 $this->mSiteInfoCallback = $callback;
207 return $previous;
211 * Sets the factory object to use to convert ForeignTitle objects into local
212 * Title objects
213 * @param ImportTitleFactory $factory
215 public function setImportTitleFactory( $factory ) {
216 $this->importTitleFactory = $factory;
220 * Set a target namespace to override the defaults
221 * @param null|int $namespace
222 * @return bool
224 public function setTargetNamespace( $namespace ) {
225 if ( is_null( $namespace ) ) {
226 // Don't override namespaces
227 $this->mTargetNamespace = null;
228 $this->setImportTitleFactory( new NaiveImportTitleFactory() );
229 return true;
230 } elseif (
231 $namespace >= 0 &&
232 MWNamespace::exists( intval( $namespace ) )
234 $namespace = intval( $namespace );
235 $this->mTargetNamespace = $namespace;
236 $this->setImportTitleFactory( new NamespaceImportTitleFactory( $namespace ) );
237 return true;
238 } else {
239 return false;
244 * Set a target root page under which all pages are imported
245 * @param null|string $rootpage
246 * @return Status
248 public function setTargetRootPage( $rootpage ) {
249 $status = Status::newGood();
250 if ( is_null( $rootpage ) ) {
251 // No rootpage
252 $this->setImportTitleFactory( new NaiveImportTitleFactory() );
253 } elseif ( $rootpage !== '' ) {
254 $rootpage = rtrim( $rootpage, '/' ); //avoid double slashes
255 $title = Title::newFromText( $rootpage, !is_null( $this->mTargetNamespace )
256 ? $this->mTargetNamespace
257 : NS_MAIN
260 if ( !$title || $title->isExternal() ) {
261 $status->fatal( 'import-rootpage-invalid' );
262 } else {
263 if ( !MWNamespace::hasSubpages( $title->getNamespace() ) ) {
264 global $wgContLang;
266 $displayNSText = $title->getNamespace() == NS_MAIN
267 ? wfMessage( 'blanknamespace' )->text()
268 : $wgContLang->getNsText( $title->getNamespace() );
269 $status->fatal( 'import-rootpage-nosubpage', $displayNSText );
270 } else {
271 // set namespace to 'all', so the namespace check in processTitle() can pass
272 $this->setTargetNamespace( null );
273 $this->setImportTitleFactory( new SubpageImportTitleFactory( $title ) );
277 return $status;
281 * @param string $dir
283 public function setImageBasePath( $dir ) {
284 $this->mImageBasePath = $dir;
288 * @param bool $import
290 public function setImportUploads( $import ) {
291 $this->mImportUploads = $import;
295 * Default per-page callback. Sets up some things related to site statistics
296 * @param array $titleAndForeignTitle Two-element array, with Title object at
297 * index 0 and ForeignTitle object at index 1
298 * @return bool
300 public function beforeImportPage( $titleAndForeignTitle ) {
301 $title = $titleAndForeignTitle[0];
302 $page = WikiPage::factory( $title );
303 $this->countableCache['title_' . $title->getPrefixedText()] = $page->isCountable();
304 return true;
308 * Default per-revision callback, performs the import.
309 * @param WikiRevision $revision
310 * @return bool
312 public function importRevision( $revision ) {
313 if ( !$revision->getContentHandler()->canBeUsedOn( $revision->getTitle() ) ) {
314 $this->notice( 'import-error-bad-location',
315 $revision->getTitle()->getPrefixedText(),
316 $revision->getID(),
317 $revision->getModel(),
318 $revision->getFormat() );
320 return false;
323 try {
324 $dbw = wfGetDB( DB_MASTER );
325 return $dbw->deadlockLoop( array( $revision, 'importOldRevision' ) );
326 } catch ( MWContentSerializationException $ex ) {
327 $this->notice( 'import-error-unserialize',
328 $revision->getTitle()->getPrefixedText(),
329 $revision->getID(),
330 $revision->getModel(),
331 $revision->getFormat() );
334 return false;
338 * Default per-revision callback, performs the import.
339 * @param WikiRevision $revision
340 * @return bool
342 public function importLogItem( $revision ) {
343 $dbw = wfGetDB( DB_MASTER );
344 return $dbw->deadlockLoop( array( $revision, 'importLogItem' ) );
348 * Dummy for now...
349 * @param WikiRevision $revision
350 * @return bool
352 public function importUpload( $revision ) {
353 $dbw = wfGetDB( DB_MASTER );
354 return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
358 * Mostly for hook use
359 * @param Title $title
360 * @param ForeignTitle $foreignTitle
361 * @param int $revCount
362 * @param int $sRevCount
363 * @param array $pageInfo
364 * @return bool
366 public function finishImportPage( $title, $foreignTitle, $revCount,
367 $sRevCount, $pageInfo ) {
369 // Update article count statistics (T42009)
370 // The normal counting logic in WikiPage->doEditUpdates() is designed for
371 // one-revision-at-a-time editing, not bulk imports. In this situation it
372 // suffers from issues of slave lag. We let WikiPage handle the total page
373 // and revision count, and we implement our own custom logic for the
374 // article (content page) count.
375 $page = WikiPage::factory( $title );
376 $page->loadPageData( 'fromdbmaster' );
377 $content = $page->getContent();
378 $editInfo = $page->prepareContentForEdit( $content );
380 $countable = $page->isCountable( $editInfo );
381 $oldcountable = $this->countableCache['title_' . $title->getPrefixedText()];
382 if ( isset( $oldcountable ) && $countable != $oldcountable ) {
383 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( array(
384 'articles' => ( (int)$countable - (int)$oldcountable )
385 ) ) );
388 $args = func_get_args();
389 return Hooks::run( 'AfterImportPage', $args );
393 * Alternate per-revision callback, for debugging.
394 * @param WikiRevision $revision
396 public function debugRevisionHandler( &$revision ) {
397 $this->debug( "Got revision:" );
398 if ( is_object( $revision->title ) ) {
399 $this->debug( "-- Title: " . $revision->title->getPrefixedText() );
400 } else {
401 $this->debug( "-- Title: <invalid>" );
403 $this->debug( "-- User: " . $revision->user_text );
404 $this->debug( "-- Timestamp: " . $revision->timestamp );
405 $this->debug( "-- Comment: " . $revision->comment );
406 $this->debug( "-- Text: " . $revision->text );
410 * Notify the callback function of site info
411 * @param array $siteInfo
412 * @return bool|mixed
414 private function siteInfoCallback( $siteInfo ) {
415 if ( isset( $this->mSiteInfoCallback ) ) {
416 return call_user_func_array( $this->mSiteInfoCallback,
417 array( $siteInfo, $this ) );
418 } else {
419 return false;
424 * Notify the callback function when a new "<page>" is reached.
425 * @param Title $title
427 function pageCallback( $title ) {
428 if ( isset( $this->mPageCallback ) ) {
429 call_user_func( $this->mPageCallback, $title );
434 * Notify the callback function when a "</page>" is closed.
435 * @param Title $title
436 * @param ForeignTitle $foreignTitle
437 * @param int $revCount
438 * @param int $sucCount Number of revisions for which callback returned true
439 * @param array $pageInfo Associative array of page information
441 private function pageOutCallback( $title, $foreignTitle, $revCount,
442 $sucCount, $pageInfo ) {
443 if ( isset( $this->mPageOutCallback ) ) {
444 $args = func_get_args();
445 call_user_func_array( $this->mPageOutCallback, $args );
450 * Notify the callback function of a revision
451 * @param WikiRevision $revision
452 * @return bool|mixed
454 private function revisionCallback( $revision ) {
455 if ( isset( $this->mRevisionCallback ) ) {
456 return call_user_func_array( $this->mRevisionCallback,
457 array( $revision, $this ) );
458 } else {
459 return false;
464 * Notify the callback function of a new log item
465 * @param WikiRevision $revision
466 * @return bool|mixed
468 private function logItemCallback( $revision ) {
469 if ( isset( $this->mLogItemCallback ) ) {
470 return call_user_func_array( $this->mLogItemCallback,
471 array( $revision, $this ) );
472 } else {
473 return false;
478 * Retrieves the contents of the named attribute of the current element.
479 * @param string $attr The name of the attribute
480 * @return string The value of the attribute or an empty string if it is not set in the current element.
482 public function nodeAttribute( $attr ) {
483 return $this->reader->getAttribute( $attr );
487 * Shouldn't something like this be built-in to XMLReader?
488 * Fetches text contents of the current element, assuming
489 * no sub-elements or such scary things.
490 * @return string
491 * @access private
493 public function nodeContents() {
494 if ( $this->reader->isEmptyElement ) {
495 return "";
497 $buffer = "";
498 while ( $this->reader->read() ) {
499 switch ( $this->reader->nodeType ) {
500 case XMLReader::TEXT:
501 case XMLReader::SIGNIFICANT_WHITESPACE:
502 $buffer .= $this->reader->value;
503 break;
504 case XMLReader::END_ELEMENT:
505 return $buffer;
509 $this->reader->close();
510 return '';
514 * Primary entry point
515 * @throws MWException
516 * @return bool
518 public function doImport() {
519 // Calls to reader->read need to be wrapped in calls to
520 // libxml_disable_entity_loader() to avoid local file
521 // inclusion attacks (bug 46932).
522 $oldDisable = libxml_disable_entity_loader( true );
523 $this->reader->read();
525 if ( $this->reader->name != 'mediawiki' ) {
526 libxml_disable_entity_loader( $oldDisable );
527 throw new MWException( "Expected <mediawiki> tag, got " .
528 $this->reader->name );
530 $this->debug( "<mediawiki> tag is correct." );
532 $this->debug( "Starting primary dump processing loop." );
534 $keepReading = $this->reader->read();
535 $skip = false;
536 $rethrow = null;
537 try {
538 while ( $keepReading ) {
539 $tag = $this->reader->name;
540 $type = $this->reader->nodeType;
542 if ( !Hooks::run( 'ImportHandleToplevelXMLTag', array( $this ) ) ) {
543 // Do nothing
544 } elseif ( $tag == 'mediawiki' && $type == XMLReader::END_ELEMENT ) {
545 break;
546 } elseif ( $tag == 'siteinfo' ) {
547 $this->handleSiteInfo();
548 } elseif ( $tag == 'page' ) {
549 $this->handlePage();
550 } elseif ( $tag == 'logitem' ) {
551 $this->handleLogItem();
552 } elseif ( $tag != '#text' ) {
553 $this->warn( "Unhandled top-level XML tag $tag" );
555 $skip = true;
558 if ( $skip ) {
559 $keepReading = $this->reader->next();
560 $skip = false;
561 $this->debug( "Skip" );
562 } else {
563 $keepReading = $this->reader->read();
566 } catch ( Exception $ex ) {
567 $rethrow = $ex;
570 // finally
571 libxml_disable_entity_loader( $oldDisable );
572 $this->reader->close();
574 if ( $rethrow ) {
575 throw $rethrow;
578 return true;
581 private function handleSiteInfo() {
582 $this->debug( "Enter site info handler." );
583 $siteInfo = array();
585 // Fields that can just be stuffed in the siteInfo object
586 $normalFields = array( 'sitename', 'base', 'generator', 'case' );
588 while ( $this->reader->read() ) {
589 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
590 $this->reader->name == 'siteinfo' ) {
591 break;
594 $tag = $this->reader->name;
596 if ( $tag == 'namespace' ) {
597 $this->foreignNamespaces[ $this->nodeAttribute( 'key' ) ] =
598 $this->nodeContents();
599 } elseif ( in_array( $tag, $normalFields ) ) {
600 $siteInfo[$tag] = $this->nodeContents();
604 $siteInfo['_namespaces'] = $this->foreignNamespaces;
605 $this->siteInfoCallback( $siteInfo );
608 private function handleLogItem() {
609 $this->debug( "Enter log item handler." );
610 $logInfo = array();
612 // Fields that can just be stuffed in the pageInfo object
613 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
614 'logtitle', 'params' );
616 while ( $this->reader->read() ) {
617 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
618 $this->reader->name == 'logitem' ) {
619 break;
622 $tag = $this->reader->name;
624 if ( !Hooks::run( 'ImportHandleLogItemXMLTag', array(
625 $this, $logInfo
626 ) ) ) {
627 // Do nothing
628 } elseif ( in_array( $tag, $normalFields ) ) {
629 $logInfo[$tag] = $this->nodeContents();
630 } elseif ( $tag == 'contributor' ) {
631 $logInfo['contributor'] = $this->handleContributor();
632 } elseif ( $tag != '#text' ) {
633 $this->warn( "Unhandled log-item XML tag $tag" );
637 $this->processLogItem( $logInfo );
641 * @param array $logInfo
642 * @return bool|mixed
644 private function processLogItem( $logInfo ) {
645 $revision = new WikiRevision( $this->config );
647 $revision->setID( $logInfo['id'] );
648 $revision->setType( $logInfo['type'] );
649 $revision->setAction( $logInfo['action'] );
650 $revision->setTimestamp( $logInfo['timestamp'] );
651 $revision->setParams( $logInfo['params'] );
652 $revision->setTitle( Title::newFromText( $logInfo['logtitle'] ) );
653 $revision->setNoUpdates( $this->mNoUpdates );
655 if ( isset( $logInfo['comment'] ) ) {
656 $revision->setComment( $logInfo['comment'] );
659 if ( isset( $logInfo['contributor']['ip'] ) ) {
660 $revision->setUserIP( $logInfo['contributor']['ip'] );
662 if ( isset( $logInfo['contributor']['username'] ) ) {
663 $revision->setUserName( $logInfo['contributor']['username'] );
666 return $this->logItemCallback( $revision );
669 private function handlePage() {
670 // Handle page data.
671 $this->debug( "Enter page handler." );
672 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
674 // Fields that can just be stuffed in the pageInfo object
675 $normalFields = array( 'title', 'ns', 'id', 'redirect', 'restrictions' );
677 $skip = false;
678 $badTitle = false;
680 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
681 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
682 $this->reader->name == 'page' ) {
683 break;
686 $skip = false;
688 $tag = $this->reader->name;
690 if ( $badTitle ) {
691 // The title is invalid, bail out of this page
692 $skip = true;
693 } elseif ( !Hooks::run( 'ImportHandlePageXMLTag', array( $this,
694 &$pageInfo ) ) ) {
695 // Do nothing
696 } elseif ( in_array( $tag, $normalFields ) ) {
697 // An XML snippet:
698 // <page>
699 // <id>123</id>
700 // <title>Page</title>
701 // <redirect title="NewTitle"/>
702 // ...
703 // Because the redirect tag is built differently, we need special handling for that case.
704 if ( $tag == 'redirect' ) {
705 $pageInfo[$tag] = $this->nodeAttribute( 'title' );
706 } else {
707 $pageInfo[$tag] = $this->nodeContents();
709 } elseif ( $tag == 'revision' || $tag == 'upload' ) {
710 if ( !isset( $title ) ) {
711 $title = $this->processTitle( $pageInfo['title'],
712 isset( $pageInfo['ns'] ) ? $pageInfo['ns'] : null );
714 if ( !$title ) {
715 $badTitle = true;
716 $skip = true;
719 $this->pageCallback( $title );
720 list( $pageInfo['_title'], $foreignTitle ) = $title;
723 if ( $title ) {
724 if ( $tag == 'revision' ) {
725 $this->handleRevision( $pageInfo );
726 } else {
727 $this->handleUpload( $pageInfo );
730 } elseif ( $tag != '#text' ) {
731 $this->warn( "Unhandled page XML tag $tag" );
732 $skip = true;
736 $this->pageOutCallback( $pageInfo['_title'], $foreignTitle,
737 $pageInfo['revisionCount'],
738 $pageInfo['successfulRevisionCount'],
739 $pageInfo );
743 * @param array $pageInfo
745 private function handleRevision( &$pageInfo ) {
746 $this->debug( "Enter revision handler" );
747 $revisionInfo = array();
749 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'model', 'format', 'text' );
751 $skip = false;
753 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
754 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
755 $this->reader->name == 'revision' ) {
756 break;
759 $tag = $this->reader->name;
761 if ( !Hooks::run( 'ImportHandleRevisionXMLTag', array(
762 $this, $pageInfo, $revisionInfo
763 ) ) ) {
764 // Do nothing
765 } elseif ( in_array( $tag, $normalFields ) ) {
766 $revisionInfo[$tag] = $this->nodeContents();
767 } elseif ( $tag == 'contributor' ) {
768 $revisionInfo['contributor'] = $this->handleContributor();
769 } elseif ( $tag != '#text' ) {
770 $this->warn( "Unhandled revision XML tag $tag" );
771 $skip = true;
775 $pageInfo['revisionCount']++;
776 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
777 $pageInfo['successfulRevisionCount']++;
782 * @param array $pageInfo
783 * @param array $revisionInfo
784 * @return bool|mixed
786 private function processRevision( $pageInfo, $revisionInfo ) {
787 $revision = new WikiRevision( $this->config );
789 if ( isset( $revisionInfo['id'] ) ) {
790 $revision->setID( $revisionInfo['id'] );
792 if ( isset( $revisionInfo['model'] ) ) {
793 $revision->setModel( $revisionInfo['model'] );
795 if ( isset( $revisionInfo['format'] ) ) {
796 $revision->setFormat( $revisionInfo['format'] );
798 $revision->setTitle( $pageInfo['_title'] );
800 if ( isset( $revisionInfo['text'] ) ) {
801 $handler = $revision->getContentHandler();
802 $text = $handler->importTransform(
803 $revisionInfo['text'],
804 $revision->getFormat() );
806 $revision->setText( $text );
808 if ( isset( $revisionInfo['timestamp'] ) ) {
809 $revision->setTimestamp( $revisionInfo['timestamp'] );
810 } else {
811 $revision->setTimestamp( wfTimestampNow() );
814 if ( isset( $revisionInfo['comment'] ) ) {
815 $revision->setComment( $revisionInfo['comment'] );
818 if ( isset( $revisionInfo['minor'] ) ) {
819 $revision->setMinor( true );
821 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
822 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
824 if ( isset( $revisionInfo['contributor']['username'] ) ) {
825 $revision->setUserName( $revisionInfo['contributor']['username'] );
827 $revision->setNoUpdates( $this->mNoUpdates );
829 return $this->revisionCallback( $revision );
833 * @param array $pageInfo
834 * @return mixed
836 private function handleUpload( &$pageInfo ) {
837 $this->debug( "Enter upload handler" );
838 $uploadInfo = array();
840 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
841 'src', 'size', 'sha1base36', 'archivename', 'rel' );
843 $skip = false;
845 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
846 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
847 $this->reader->name == 'upload' ) {
848 break;
851 $tag = $this->reader->name;
853 if ( !Hooks::run( 'ImportHandleUploadXMLTag', array(
854 $this, $pageInfo
855 ) ) ) {
856 // Do nothing
857 } elseif ( in_array( $tag, $normalFields ) ) {
858 $uploadInfo[$tag] = $this->nodeContents();
859 } elseif ( $tag == 'contributor' ) {
860 $uploadInfo['contributor'] = $this->handleContributor();
861 } elseif ( $tag == 'contents' ) {
862 $contents = $this->nodeContents();
863 $encoding = $this->reader->getAttribute( 'encoding' );
864 if ( $encoding === 'base64' ) {
865 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
866 $uploadInfo['isTempSrc'] = true;
868 } elseif ( $tag != '#text' ) {
869 $this->warn( "Unhandled upload XML tag $tag" );
870 $skip = true;
874 if ( $this->mImageBasePath && isset( $uploadInfo['rel'] ) ) {
875 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
876 if ( file_exists( $path ) ) {
877 $uploadInfo['fileSrc'] = $path;
878 $uploadInfo['isTempSrc'] = false;
882 if ( $this->mImportUploads ) {
883 return $this->processUpload( $pageInfo, $uploadInfo );
888 * @param string $contents
889 * @return string
891 private function dumpTemp( $contents ) {
892 $filename = tempnam( wfTempDir(), 'importupload' );
893 file_put_contents( $filename, $contents );
894 return $filename;
898 * @param array $pageInfo
899 * @param array $uploadInfo
900 * @return mixed
902 private function processUpload( $pageInfo, $uploadInfo ) {
903 $revision = new WikiRevision( $this->config );
904 $text = isset( $uploadInfo['text'] ) ? $uploadInfo['text'] : '';
906 $revision->setTitle( $pageInfo['_title'] );
907 $revision->setID( $pageInfo['id'] );
908 $revision->setTimestamp( $uploadInfo['timestamp'] );
909 $revision->setText( $text );
910 $revision->setFilename( $uploadInfo['filename'] );
911 if ( isset( $uploadInfo['archivename'] ) ) {
912 $revision->setArchiveName( $uploadInfo['archivename'] );
914 $revision->setSrc( $uploadInfo['src'] );
915 if ( isset( $uploadInfo['fileSrc'] ) ) {
916 $revision->setFileSrc( $uploadInfo['fileSrc'],
917 !empty( $uploadInfo['isTempSrc'] ) );
919 if ( isset( $uploadInfo['sha1base36'] ) ) {
920 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
922 $revision->setSize( intval( $uploadInfo['size'] ) );
923 $revision->setComment( $uploadInfo['comment'] );
925 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
926 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
928 if ( isset( $uploadInfo['contributor']['username'] ) ) {
929 $revision->setUserName( $uploadInfo['contributor']['username'] );
931 $revision->setNoUpdates( $this->mNoUpdates );
933 return call_user_func( $this->mUploadCallback, $revision );
937 * @return array
939 private function handleContributor() {
940 $fields = array( 'id', 'ip', 'username' );
941 $info = array();
943 while ( $this->reader->read() ) {
944 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
945 $this->reader->name == 'contributor' ) {
946 break;
949 $tag = $this->reader->name;
951 if ( in_array( $tag, $fields ) ) {
952 $info[$tag] = $this->nodeContents();
956 return $info;
960 * @param string $text
961 * @param string|null $ns
962 * @return array|bool
964 private function processTitle( $text, $ns = null ) {
965 if ( is_null( $this->foreignNamespaces ) ) {
966 $foreignTitleFactory = new NaiveForeignTitleFactory();
967 } else {
968 $foreignTitleFactory = new NamespaceAwareForeignTitleFactory(
969 $this->foreignNamespaces );
972 $foreignTitle = $foreignTitleFactory->createForeignTitle( $text,
973 intval( $ns ) );
975 $title = $this->importTitleFactory->createTitleFromForeignTitle(
976 $foreignTitle );
978 $commandLineMode = $this->config->get( 'CommandLineMode' );
979 if ( is_null( $title ) ) {
980 # Invalid page title? Ignore the page
981 $this->notice( 'import-error-invalid', $foreignTitle->getFullText() );
982 return false;
983 } elseif ( $title->isExternal() ) {
984 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
985 return false;
986 } elseif ( !$title->canExist() ) {
987 $this->notice( 'import-error-special', $title->getPrefixedText() );
988 return false;
989 } elseif ( !$title->userCan( 'edit' ) && !$commandLineMode ) {
990 # Do not import if the importing wiki user cannot edit this page
991 $this->notice( 'import-error-edit', $title->getPrefixedText() );
992 return false;
993 } elseif ( !$title->exists() && !$title->userCan( 'create' ) && !$commandLineMode ) {
994 # Do not import if the importing wiki user cannot create this page
995 $this->notice( 'import-error-create', $title->getPrefixedText() );
996 return false;
999 return array( $title, $foreignTitle );
1003 /** This is a horrible hack used to keep source compatibility */
1004 class UploadSourceAdapter {
1005 /** @var array */
1006 public static $sourceRegistrations = array();
1008 /** @var string */
1009 private $mSource;
1011 /** @var string */
1012 private $mBuffer;
1014 /** @var int */
1015 private $mPosition;
1018 * @param ImportSource $source
1019 * @return string
1021 static function registerSource( ImportSource $source ) {
1022 $id = wfRandomString();
1024 self::$sourceRegistrations[$id] = $source;
1026 return $id;
1030 * @param string $path
1031 * @param string $mode
1032 * @param array $options
1033 * @param string $opened_path
1034 * @return bool
1036 function stream_open( $path, $mode, $options, &$opened_path ) {
1037 $url = parse_url( $path );
1038 $id = $url['host'];
1040 if ( !isset( self::$sourceRegistrations[$id] ) ) {
1041 return false;
1044 $this->mSource = self::$sourceRegistrations[$id];
1046 return true;
1050 * @param int $count
1051 * @return string
1053 function stream_read( $count ) {
1054 $return = '';
1055 $leave = false;
1057 while ( !$leave && !$this->mSource->atEnd() &&
1058 strlen( $this->mBuffer ) < $count ) {
1059 $read = $this->mSource->readChunk();
1061 if ( !strlen( $read ) ) {
1062 $leave = true;
1065 $this->mBuffer .= $read;
1068 if ( strlen( $this->mBuffer ) ) {
1069 $return = substr( $this->mBuffer, 0, $count );
1070 $this->mBuffer = substr( $this->mBuffer, $count );
1073 $this->mPosition += strlen( $return );
1075 return $return;
1079 * @param string $data
1080 * @return bool
1082 function stream_write( $data ) {
1083 return false;
1087 * @return mixed
1089 function stream_tell() {
1090 return $this->mPosition;
1094 * @return bool
1096 function stream_eof() {
1097 return $this->mSource->atEnd();
1101 * @return array
1103 function url_stat() {
1104 $result = array();
1106 $result['dev'] = $result[0] = 0;
1107 $result['ino'] = $result[1] = 0;
1108 $result['mode'] = $result[2] = 0;
1109 $result['nlink'] = $result[3] = 0;
1110 $result['uid'] = $result[4] = 0;
1111 $result['gid'] = $result[5] = 0;
1112 $result['rdev'] = $result[6] = 0;
1113 $result['size'] = $result[7] = 0;
1114 $result['atime'] = $result[8] = 0;
1115 $result['mtime'] = $result[9] = 0;
1116 $result['ctime'] = $result[10] = 0;
1117 $result['blksize'] = $result[11] = 0;
1118 $result['blocks'] = $result[12] = 0;
1120 return $result;
1125 * @todo document (e.g. one-sentence class description).
1126 * @ingroup SpecialPage
1128 class WikiRevision {
1129 /** @todo Unused? */
1130 public $importer = null;
1132 /** @var Title */
1133 public $title = null;
1135 /** @var int */
1136 public $id = 0;
1138 /** @var string */
1139 public $timestamp = "20010115000000";
1142 * @var int
1143 * @todo Can't find any uses. Public, because that's suspicious. Get clarity. */
1144 public $user = 0;
1146 /** @var string */
1147 public $user_text = "";
1149 /** @var string */
1150 public $model = null;
1152 /** @var string */
1153 public $format = null;
1155 /** @var string */
1156 public $text = "";
1158 /** @var int */
1159 protected $size;
1161 /** @var Content */
1162 public $content = null;
1164 /** @var ContentHandler */
1165 protected $contentHandler = null;
1167 /** @var string */
1168 public $comment = "";
1170 /** @var bool */
1171 public $minor = false;
1173 /** @var string */
1174 public $type = "";
1176 /** @var string */
1177 public $action = "";
1179 /** @var string */
1180 public $params = "";
1182 /** @var string */
1183 public $fileSrc = '';
1185 /** @var bool|string */
1186 public $sha1base36 = false;
1189 * @var bool
1190 * @todo Unused?
1192 public $isTemp = false;
1194 /** @var string */
1195 public $archiveName = '';
1197 protected $filename;
1199 /** @var mixed */
1200 protected $src;
1202 /** @todo Unused? */
1203 public $fileIsTemp;
1205 /** @var bool */
1206 private $mNoUpdates = false;
1208 /** @var Config $config */
1209 private $config;
1211 public function __construct( Config $config ) {
1212 $this->config = $config;
1216 * @param Title $title
1217 * @throws MWException
1219 function setTitle( $title ) {
1220 if ( is_object( $title ) ) {
1221 $this->title = $title;
1222 } elseif ( is_null( $title ) ) {
1223 throw new MWException( "WikiRevision given a null title in import. "
1224 . "You may need to adjust \$wgLegalTitleChars." );
1225 } else {
1226 throw new MWException( "WikiRevision given non-object title in import." );
1231 * @param int $id
1233 function setID( $id ) {
1234 $this->id = $id;
1238 * @param string $ts
1240 function setTimestamp( $ts ) {
1241 # 2003-08-05T18:30:02Z
1242 $this->timestamp = wfTimestamp( TS_MW, $ts );
1246 * @param string $user
1248 function setUsername( $user ) {
1249 $this->user_text = $user;
1253 * @param string $ip
1255 function setUserIP( $ip ) {
1256 $this->user_text = $ip;
1260 * @param string $model
1262 function setModel( $model ) {
1263 $this->model = $model;
1267 * @param string $format
1269 function setFormat( $format ) {
1270 $this->format = $format;
1274 * @param string $text
1276 function setText( $text ) {
1277 $this->text = $text;
1281 * @param string $text
1283 function setComment( $text ) {
1284 $this->comment = $text;
1288 * @param bool $minor
1290 function setMinor( $minor ) {
1291 $this->minor = (bool)$minor;
1295 * @param mixed $src
1297 function setSrc( $src ) {
1298 $this->src = $src;
1302 * @param string $src
1303 * @param bool $isTemp
1305 function setFileSrc( $src, $isTemp ) {
1306 $this->fileSrc = $src;
1307 $this->fileIsTemp = $isTemp;
1311 * @param string $sha1base36
1313 function setSha1Base36( $sha1base36 ) {
1314 $this->sha1base36 = $sha1base36;
1318 * @param string $filename
1320 function setFilename( $filename ) {
1321 $this->filename = $filename;
1325 * @param string $archiveName
1327 function setArchiveName( $archiveName ) {
1328 $this->archiveName = $archiveName;
1332 * @param int $size
1334 function setSize( $size ) {
1335 $this->size = intval( $size );
1339 * @param string $type
1341 function setType( $type ) {
1342 $this->type = $type;
1346 * @param string $action
1348 function setAction( $action ) {
1349 $this->action = $action;
1353 * @param array $params
1355 function setParams( $params ) {
1356 $this->params = $params;
1360 * @param bool $noupdates
1362 public function setNoUpdates( $noupdates ) {
1363 $this->mNoUpdates = $noupdates;
1367 * @return Title
1369 function getTitle() {
1370 return $this->title;
1374 * @return int
1376 function getID() {
1377 return $this->id;
1381 * @return string
1383 function getTimestamp() {
1384 return $this->timestamp;
1388 * @return string
1390 function getUser() {
1391 return $this->user_text;
1395 * @return string
1397 * @deprecated Since 1.21, use getContent() instead.
1399 function getText() {
1400 ContentHandler::deprecated( __METHOD__, '1.21' );
1402 return $this->text;
1406 * @return ContentHandler
1408 function getContentHandler() {
1409 if ( is_null( $this->contentHandler ) ) {
1410 $this->contentHandler = ContentHandler::getForModelID( $this->getModel() );
1413 return $this->contentHandler;
1417 * @return Content
1419 function getContent() {
1420 if ( is_null( $this->content ) ) {
1421 $handler = $this->getContentHandler();
1422 $this->content = $handler->unserializeContent( $this->text, $this->getFormat() );
1425 return $this->content;
1429 * @return string
1431 function getModel() {
1432 if ( is_null( $this->model ) ) {
1433 $this->model = $this->getTitle()->getContentModel();
1436 return $this->model;
1440 * @return string
1442 function getFormat() {
1443 if ( is_null( $this->format ) ) {
1444 $this->format = $this->getContentHandler()->getDefaultFormat();
1447 return $this->format;
1451 * @return string
1453 function getComment() {
1454 return $this->comment;
1458 * @return bool
1460 function getMinor() {
1461 return $this->minor;
1465 * @return mixed
1467 function getSrc() {
1468 return $this->src;
1472 * @return bool|string
1474 function getSha1() {
1475 if ( $this->sha1base36 ) {
1476 return wfBaseConvert( $this->sha1base36, 36, 16 );
1478 return false;
1482 * @return string
1484 function getFileSrc() {
1485 return $this->fileSrc;
1489 * @return bool
1491 function isTempSrc() {
1492 return $this->isTemp;
1496 * @return mixed
1498 function getFilename() {
1499 return $this->filename;
1503 * @return string
1505 function getArchiveName() {
1506 return $this->archiveName;
1510 * @return mixed
1512 function getSize() {
1513 return $this->size;
1517 * @return string
1519 function getType() {
1520 return $this->type;
1524 * @return string
1526 function getAction() {
1527 return $this->action;
1531 * @return string
1533 function getParams() {
1534 return $this->params;
1538 * @return bool
1540 function importOldRevision() {
1541 $dbw = wfGetDB( DB_MASTER );
1543 # Sneak a single revision into place
1544 $user = User::newFromName( $this->getUser() );
1545 if ( $user ) {
1546 $userId = intval( $user->getId() );
1547 $userText = $user->getName();
1548 $userObj = $user;
1549 } else {
1550 $userId = 0;
1551 $userText = $this->getUser();
1552 $userObj = new User;
1555 // avoid memory leak...?
1556 $linkCache = LinkCache::singleton();
1557 $linkCache->clear();
1559 $page = WikiPage::factory( $this->title );
1560 $page->loadPageData( 'fromdbmaster' );
1561 if ( !$page->exists() ) {
1562 # must create the page...
1563 $pageId = $page->insertOn( $dbw );
1564 $created = true;
1565 $oldcountable = null;
1566 } else {
1567 $pageId = $page->getId();
1568 $created = false;
1570 $prior = $dbw->selectField( 'revision', '1',
1571 array( 'rev_page' => $pageId,
1572 'rev_timestamp' => $dbw->timestamp( $this->timestamp ),
1573 'rev_user_text' => $userText,
1574 'rev_comment' => $this->getComment() ),
1575 __METHOD__
1577 if ( $prior ) {
1578 // @todo FIXME: This could fail slightly for multiple matches :P
1579 wfDebug( __METHOD__ . ": skipping existing revision for [[" .
1580 $this->title->getPrefixedText() . "]], timestamp " . $this->timestamp . "\n" );
1581 return false;
1585 # @todo FIXME: Use original rev_id optionally (better for backups)
1586 # Insert the row
1587 $revision = new Revision( array(
1588 'title' => $this->title,
1589 'page' => $pageId,
1590 'content_model' => $this->getModel(),
1591 'content_format' => $this->getFormat(),
1592 //XXX: just set 'content' => $this->getContent()?
1593 'text' => $this->getContent()->serialize( $this->getFormat() ),
1594 'comment' => $this->getComment(),
1595 'user' => $userId,
1596 'user_text' => $userText,
1597 'timestamp' => $this->timestamp,
1598 'minor_edit' => $this->minor,
1599 ) );
1600 $revision->insertOn( $dbw );
1601 $changed = $page->updateIfNewerOn( $dbw, $revision );
1603 if ( $changed !== false && !$this->mNoUpdates ) {
1604 wfDebug( __METHOD__ . ": running updates\n" );
1605 // countable/oldcountable stuff is handled in WikiImporter::finishImportPage
1606 $page->doEditUpdates(
1607 $revision,
1608 $userObj,
1609 array( 'created' => $created, 'oldcountable' => 'no-change' )
1613 return true;
1616 function importLogItem() {
1617 $dbw = wfGetDB( DB_MASTER );
1618 # @todo FIXME: This will not record autoblocks
1619 if ( !$this->getTitle() ) {
1620 wfDebug( __METHOD__ . ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1621 $this->timestamp . "\n" );
1622 return;
1624 # Check if it exists already
1625 // @todo FIXME: Use original log ID (better for backups)
1626 $prior = $dbw->selectField( 'logging', '1',
1627 array( 'log_type' => $this->getType(),
1628 'log_action' => $this->getAction(),
1629 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
1630 'log_namespace' => $this->getTitle()->getNamespace(),
1631 'log_title' => $this->getTitle()->getDBkey(),
1632 'log_comment' => $this->getComment(),
1633 #'log_user_text' => $this->user_text,
1634 'log_params' => $this->params ),
1635 __METHOD__
1637 // @todo FIXME: This could fail slightly for multiple matches :P
1638 if ( $prior ) {
1639 wfDebug( __METHOD__
1640 . ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp "
1641 . $this->timestamp . "\n" );
1642 return;
1644 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1645 $data = array(
1646 'log_id' => $log_id,
1647 'log_type' => $this->type,
1648 'log_action' => $this->action,
1649 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
1650 'log_user' => User::idFromName( $this->user_text ),
1651 #'log_user_text' => $this->user_text,
1652 'log_namespace' => $this->getTitle()->getNamespace(),
1653 'log_title' => $this->getTitle()->getDBkey(),
1654 'log_comment' => $this->getComment(),
1655 'log_params' => $this->params
1657 $dbw->insert( 'logging', $data, __METHOD__ );
1661 * @return bool
1663 function importUpload() {
1664 # Construct a file
1665 $archiveName = $this->getArchiveName();
1666 if ( $archiveName ) {
1667 wfDebug( __METHOD__ . "Importing archived file as $archiveName\n" );
1668 $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
1669 RepoGroup::singleton()->getLocalRepo(), $archiveName );
1670 } else {
1671 $file = wfLocalFile( $this->getTitle() );
1672 wfDebug( __METHOD__ . 'Importing new file as ' . $file->getName() . "\n" );
1673 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1674 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1675 $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
1676 RepoGroup::singleton()->getLocalRepo(), $archiveName );
1677 wfDebug( __METHOD__ . "File already exists; importing as $archiveName\n" );
1680 if ( !$file ) {
1681 wfDebug( __METHOD__ . ': Bad file for ' . $this->getTitle() . "\n" );
1682 return false;
1685 # Get the file source or download if necessary
1686 $source = $this->getFileSrc();
1687 $flags = $this->isTempSrc() ? File::DELETE_SOURCE : 0;
1688 if ( !$source ) {
1689 $source = $this->downloadSource();
1690 $flags |= File::DELETE_SOURCE;
1692 if ( !$source ) {
1693 wfDebug( __METHOD__ . ": Could not fetch remote file.\n" );
1694 return false;
1696 $sha1 = $this->getSha1();
1697 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1698 if ( $flags & File::DELETE_SOURCE ) {
1699 # Broken file; delete it if it is a temporary file
1700 unlink( $source );
1702 wfDebug( __METHOD__ . ": Corrupt file $source.\n" );
1703 return false;
1706 $user = User::newFromName( $this->user_text );
1708 # Do the actual upload
1709 if ( $archiveName ) {
1710 $status = $file->uploadOld( $source, $archiveName,
1711 $this->getTimestamp(), $this->getComment(), $user, $flags );
1712 } else {
1713 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1714 $flags, false, $this->getTimestamp(), $user );
1717 if ( $status->isGood() ) {
1718 wfDebug( __METHOD__ . ": Successful\n" );
1719 return true;
1720 } else {
1721 wfDebug( __METHOD__ . ': failed: ' . $status->getHTML() . "\n" );
1722 return false;
1727 * @return bool|string
1729 function downloadSource() {
1730 if ( !$this->config->get( 'EnableUploads' ) ) {
1731 return false;
1734 $tempo = tempnam( wfTempDir(), 'download' );
1735 $f = fopen( $tempo, 'wb' );
1736 if ( !$f ) {
1737 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1738 return false;
1741 // @todo FIXME!
1742 $src = $this->getSrc();
1743 $data = Http::get( $src );
1744 if ( !$data ) {
1745 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1746 fclose( $f );
1747 unlink( $tempo );
1748 return false;
1751 fwrite( $f, $data );
1752 fclose( $f );
1754 return $tempo;
1760 * Source interface for XML import.
1762 interface ImportSource {
1765 * Indicates whether the end of the input has been reached.
1766 * Will return true after a finite number of calls to readChunk.
1768 * @return bool true if there is no more input, false otherwise.
1770 function atEnd();
1773 * Return a chunk of the input, as a (possibly empty) string.
1774 * When the end of input is reached, readChunk() returns false.
1775 * If atEnd() returns false, readChunk() will return a string.
1776 * If atEnd() returns true, readChunk() will return false.
1778 * @return bool|string
1780 function readChunk();
1784 * Used for importing XML dumps where the content of the dump is in a string.
1785 * This class is ineffecient, and should only be used for small dumps.
1786 * For larger dumps, ImportStreamSource should be used instead.
1788 * @ingroup SpecialPage
1790 class ImportStringSource implements ImportSource {
1791 function __construct( $string ) {
1792 $this->mString = $string;
1793 $this->mRead = false;
1797 * @return bool
1799 function atEnd() {
1800 return $this->mRead;
1804 * @return bool|string
1806 function readChunk() {
1807 if ( $this->atEnd() ) {
1808 return false;
1810 $this->mRead = true;
1811 return $this->mString;
1816 * Imports a XML dump from a file (either from file upload, files on disk, or HTTP)
1817 * @ingroup SpecialPage
1819 class ImportStreamSource implements ImportSource {
1820 function __construct( $handle ) {
1821 $this->mHandle = $handle;
1825 * @return bool
1827 function atEnd() {
1828 return feof( $this->mHandle );
1832 * @return string
1834 function readChunk() {
1835 return fread( $this->mHandle, 32768 );
1839 * @param string $filename
1840 * @return Status
1842 static function newFromFile( $filename ) {
1843 wfSuppressWarnings();
1844 $file = fopen( $filename, 'rt' );
1845 wfRestoreWarnings();
1846 if ( !$file ) {
1847 return Status::newFatal( "importcantopen" );
1849 return Status::newGood( new ImportStreamSource( $file ) );
1853 * @param string $fieldname
1854 * @return Status
1856 static function newFromUpload( $fieldname = "xmlimport" ) {
1857 $upload =& $_FILES[$fieldname];
1859 if ( $upload === null || !$upload['name'] ) {
1860 return Status::newFatal( 'importnofile' );
1862 if ( !empty( $upload['error'] ) ) {
1863 switch ( $upload['error'] ) {
1864 case 1:
1865 # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1866 return Status::newFatal( 'importuploaderrorsize' );
1867 case 2:
1868 # The uploaded file exceeds the MAX_FILE_SIZE directive that
1869 # was specified in the HTML form.
1870 return Status::newFatal( 'importuploaderrorsize' );
1871 case 3:
1872 # The uploaded file was only partially uploaded
1873 return Status::newFatal( 'importuploaderrorpartial' );
1874 case 6:
1875 # Missing a temporary folder.
1876 return Status::newFatal( 'importuploaderrortemp' );
1877 # case else: # Currently impossible
1881 $fname = $upload['tmp_name'];
1882 if ( is_uploaded_file( $fname ) ) {
1883 return ImportStreamSource::newFromFile( $fname );
1884 } else {
1885 return Status::newFatal( 'importnofile' );
1890 * @param string $url
1891 * @param string $method
1892 * @return Status
1894 static function newFromURL( $url, $method = 'GET' ) {
1895 wfDebug( __METHOD__ . ": opening $url\n" );
1896 # Use the standard HTTP fetch function; it times out
1897 # quicker and sorts out user-agent problems which might
1898 # otherwise prevent importing from large sites, such
1899 # as the Wikimedia cluster, etc.
1900 $data = Http::request( $method, $url, array( 'followRedirects' => true ) );
1901 if ( $data !== false ) {
1902 $file = tmpfile();
1903 fwrite( $file, $data );
1904 fflush( $file );
1905 fseek( $file, 0 );
1906 return Status::newGood( new ImportStreamSource( $file ) );
1907 } else {
1908 return Status::newFatal( 'importcantopen' );
1913 * @param string $interwiki
1914 * @param string $page
1915 * @param bool $history
1916 * @param bool $templates
1917 * @param int $pageLinkDepth
1918 * @return Status
1920 public static function newFromInterwiki( $interwiki, $page, $history = false,
1921 $templates = false, $pageLinkDepth = 0
1923 if ( $page == '' ) {
1924 return Status::newFatal( 'import-noarticle' );
1926 $link = Title::newFromText( "$interwiki:Special:Export/$page" );
1927 if ( is_null( $link ) || !$link->isExternal() ) {
1928 return Status::newFatal( 'importbadinterwiki' );
1929 } else {
1930 $params = array();
1931 if ( $history ) {
1932 $params['history'] = 1;
1934 if ( $templates ) {
1935 $params['templates'] = 1;
1937 if ( $pageLinkDepth ) {
1938 $params['pagelink-depth'] = $pageLinkDepth;
1940 $url = $link->getFullURL( $params );
1941 # For interwikis, use POST to avoid redirects.
1942 return ImportStreamSource::newFromURL( $url, "POST" );