Implement extension registration from an extension.json file
[mediawiki.git] / includes / Import.php
blobc3caeccffa490052dfe74b19ae33c2f71197c20d
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;
46 /**
47 * Creates an ImportXMLReader drawing from the source provided
48 * @param ImportStreamSource $source
49 * @param Config $config
51 function __construct( ImportStreamSource $source, Config $config = null ) {
52 $this->reader = new XMLReader();
53 if ( !$config ) {
54 wfDeprecated( __METHOD__ . ' without a Config instance', '1.25' );
55 $config = ConfigFactory::getDefaultInstance()->makeConfig( 'main' );
57 $this->config = $config;
59 if ( !in_array( 'uploadsource', stream_get_wrappers() ) ) {
60 stream_wrapper_register( 'uploadsource', 'UploadSourceAdapter' );
62 $id = UploadSourceAdapter::registerSource( $source );
63 if ( defined( 'LIBXML_PARSEHUGE' ) ) {
64 $this->reader->open( "uploadsource://$id", null, LIBXML_PARSEHUGE );
65 } else {
66 $this->reader->open( "uploadsource://$id" );
69 // Default callbacks
70 $this->setRevisionCallback( array( $this, "importRevision" ) );
71 $this->setUploadCallback( array( $this, 'importUpload' ) );
72 $this->setLogItemCallback( array( $this, 'importLogItem' ) );
73 $this->setPageOutCallback( array( $this, 'finishImportPage' ) );
75 $this->importTitleFactory = new NaiveImportTitleFactory();
78 /**
79 * @return null|XMLReader
81 public function getReader() {
82 return $this->reader;
85 public function throwXmlError( $err ) {
86 $this->debug( "FAILURE: $err" );
87 wfDebug( "WikiImporter XML error: $err\n" );
90 public function debug( $data ) {
91 if ( $this->mDebug ) {
92 wfDebug( "IMPORT: $data\n" );
96 public function warn( $data ) {
97 wfDebug( "IMPORT: $data\n" );
100 public function notice( $msg /*, $param, ...*/ ) {
101 $params = func_get_args();
102 array_shift( $params );
104 if ( is_callable( $this->mNoticeCallback ) ) {
105 call_user_func( $this->mNoticeCallback, $msg, $params );
106 } else { # No ImportReporter -> CLI
107 echo wfMessage( $msg, $params )->text() . "\n";
112 * Set debug mode...
113 * @param bool $debug
115 function setDebug( $debug ) {
116 $this->mDebug = $debug;
120 * Set 'no updates' mode. In this mode, the link tables will not be updated by the importer
121 * @param bool $noupdates
123 function setNoUpdates( $noupdates ) {
124 $this->mNoUpdates = $noupdates;
128 * Set a callback that displays notice messages
130 * @param callable $callback
131 * @return callable
133 public function setNoticeCallback( $callback ) {
134 return wfSetVar( $this->mNoticeCallback, $callback );
138 * Sets the action to perform as each new page in the stream is reached.
139 * @param callable $callback
140 * @return callable
142 public function setPageCallback( $callback ) {
143 $previous = $this->mPageCallback;
144 $this->mPageCallback = $callback;
145 return $previous;
149 * Sets the action to perform as each page in the stream is completed.
150 * Callback accepts the page title (as a Title object), a second object
151 * with the original title form (in case it's been overridden into a
152 * local namespace), and a count of revisions.
154 * @param callable $callback
155 * @return callable
157 public function setPageOutCallback( $callback ) {
158 $previous = $this->mPageOutCallback;
159 $this->mPageOutCallback = $callback;
160 return $previous;
164 * Sets the action to perform as each page revision is reached.
165 * @param callable $callback
166 * @return callable
168 public function setRevisionCallback( $callback ) {
169 $previous = $this->mRevisionCallback;
170 $this->mRevisionCallback = $callback;
171 return $previous;
175 * Sets the action to perform as each file upload version is reached.
176 * @param callable $callback
177 * @return callable
179 public function setUploadCallback( $callback ) {
180 $previous = $this->mUploadCallback;
181 $this->mUploadCallback = $callback;
182 return $previous;
186 * Sets the action to perform as each log item reached.
187 * @param callable $callback
188 * @return callable
190 public function setLogItemCallback( $callback ) {
191 $previous = $this->mLogItemCallback;
192 $this->mLogItemCallback = $callback;
193 return $previous;
197 * Sets the action to perform when site info is encountered
198 * @param callable $callback
199 * @return callable
201 public function setSiteInfoCallback( $callback ) {
202 $previous = $this->mSiteInfoCallback;
203 $this->mSiteInfoCallback = $callback;
204 return $previous;
208 * Sets the factory object to use to convert ForeignTitle objects into local
209 * Title objects
210 * @param ImportTitleFactory $factory
212 public function setImportTitleFactory( $factory ) {
213 $this->importTitleFactory = $factory;
217 * Set a target namespace to override the defaults
218 * @param null|int $namespace
219 * @return bool
221 public function setTargetNamespace( $namespace ) {
222 if ( is_null( $namespace ) ) {
223 // Don't override namespaces
224 $this->mTargetNamespace = null;
225 $this->setImportTitleFactory( new NaiveImportTitleFactory() );
226 return true;
227 } elseif (
228 $namespace >= 0 &&
229 MWNamespace::exists( intval( $namespace ) )
231 $namespace = intval( $namespace );
232 $this->mTargetNamespace = $namespace;
233 $this->setImportTitleFactory( new NamespaceImportTitleFactory( $namespace ) );
234 return true;
235 } else {
236 return false;
241 * Set a target root page under which all pages are imported
242 * @param null|string $rootpage
243 * @return Status
245 public function setTargetRootPage( $rootpage ) {
246 $status = Status::newGood();
247 if ( is_null( $rootpage ) ) {
248 // No rootpage
249 $this->setImportTitleFactory( new NaiveImportTitleFactory() );
250 } elseif ( $rootpage !== '' ) {
251 $rootpage = rtrim( $rootpage, '/' ); //avoid double slashes
252 $title = Title::newFromText( $rootpage, !is_null( $this->mTargetNamespace )
253 ? $this->mTargetNamespace
254 : NS_MAIN
257 if ( !$title || $title->isExternal() ) {
258 $status->fatal( 'import-rootpage-invalid' );
259 } else {
260 if ( !MWNamespace::hasSubpages( $title->getNamespace() ) ) {
261 global $wgContLang;
263 $displayNSText = $title->getNamespace() == NS_MAIN
264 ? wfMessage( 'blanknamespace' )->text()
265 : $wgContLang->getNsText( $title->getNamespace() );
266 $status->fatal( 'import-rootpage-nosubpage', $displayNSText );
267 } else {
268 // set namespace to 'all', so the namespace check in processTitle() can pass
269 $this->setTargetNamespace( null );
270 $this->setImportTitleFactory( new SubpageImportTitleFactory( $title ) );
274 return $status;
278 * @param string $dir
280 public function setImageBasePath( $dir ) {
281 $this->mImageBasePath = $dir;
285 * @param bool $import
287 public function setImportUploads( $import ) {
288 $this->mImportUploads = $import;
292 * Default per-revision callback, performs the import.
293 * @param WikiRevision $revision
294 * @return bool
296 public function importRevision( $revision ) {
297 if ( !$revision->getContentHandler()->canBeUsedOn( $revision->getTitle() ) ) {
298 $this->notice( 'import-error-bad-location',
299 $revision->getTitle()->getPrefixedText(),
300 $revision->getID(),
301 $revision->getModel(),
302 $revision->getFormat() );
304 return false;
307 try {
308 $dbw = wfGetDB( DB_MASTER );
309 return $dbw->deadlockLoop( array( $revision, 'importOldRevision' ) );
310 } catch ( MWContentSerializationException $ex ) {
311 $this->notice( 'import-error-unserialize',
312 $revision->getTitle()->getPrefixedText(),
313 $revision->getID(),
314 $revision->getModel(),
315 $revision->getFormat() );
318 return false;
322 * Default per-revision callback, performs the import.
323 * @param WikiRevision $revision
324 * @return bool
326 public function importLogItem( $revision ) {
327 $dbw = wfGetDB( DB_MASTER );
328 return $dbw->deadlockLoop( array( $revision, 'importLogItem' ) );
332 * Dummy for now...
333 * @param WikiRevision $revision
334 * @return bool
336 public function importUpload( $revision ) {
337 $dbw = wfGetDB( DB_MASTER );
338 return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
342 * Mostly for hook use
343 * @param Title $title
344 * @param ForeignTitle $foreignTitle
345 * @param int $revCount
346 * @param int $sRevCount
347 * @param array $pageInfo
348 * @return bool
350 public function finishImportPage( $title, $foreignTitle, $revCount,
351 $sRevCount, $pageInfo ) {
352 $args = func_get_args();
353 return Hooks::run( 'AfterImportPage', $args );
357 * Alternate per-revision callback, for debugging.
358 * @param WikiRevision $revision
360 public function debugRevisionHandler( &$revision ) {
361 $this->debug( "Got revision:" );
362 if ( is_object( $revision->title ) ) {
363 $this->debug( "-- Title: " . $revision->title->getPrefixedText() );
364 } else {
365 $this->debug( "-- Title: <invalid>" );
367 $this->debug( "-- User: " . $revision->user_text );
368 $this->debug( "-- Timestamp: " . $revision->timestamp );
369 $this->debug( "-- Comment: " . $revision->comment );
370 $this->debug( "-- Text: " . $revision->text );
374 * Notify the callback function of site info
375 * @param array $siteInfo
376 * @return bool|mixed
378 private function siteInfoCallback( $siteInfo ) {
379 if ( isset( $this->mSiteInfoCallback ) ) {
380 return call_user_func_array( $this->mSiteInfoCallback,
381 array( $siteInfo, $this ) );
382 } else {
383 return false;
388 * Notify the callback function when a new "<page>" is reached.
389 * @param Title $title
391 function pageCallback( $title ) {
392 if ( isset( $this->mPageCallback ) ) {
393 call_user_func( $this->mPageCallback, $title );
398 * Notify the callback function when a "</page>" is closed.
399 * @param Title $title
400 * @param ForeignTitle $foreignTitle
401 * @param int $revCount
402 * @param int $sucCount Number of revisions for which callback returned true
403 * @param array $pageInfo Associative array of page information
405 private function pageOutCallback( $title, $foreignTitle, $revCount,
406 $sucCount, $pageInfo ) {
407 if ( isset( $this->mPageOutCallback ) ) {
408 $args = func_get_args();
409 call_user_func_array( $this->mPageOutCallback, $args );
414 * Notify the callback function of a revision
415 * @param WikiRevision $revision
416 * @return bool|mixed
418 private function revisionCallback( $revision ) {
419 if ( isset( $this->mRevisionCallback ) ) {
420 return call_user_func_array( $this->mRevisionCallback,
421 array( $revision, $this ) );
422 } else {
423 return false;
428 * Notify the callback function of a new log item
429 * @param WikiRevision $revision
430 * @return bool|mixed
432 private function logItemCallback( $revision ) {
433 if ( isset( $this->mLogItemCallback ) ) {
434 return call_user_func_array( $this->mLogItemCallback,
435 array( $revision, $this ) );
436 } else {
437 return false;
442 * Retrieves the contents of the named attribute of the current element.
443 * @param string $attr The name of the attribute
444 * @return string The value of the attribute or an empty string if it is not set in the current element.
446 public function nodeAttribute( $attr ) {
447 return $this->reader->getAttribute( $attr );
451 * Shouldn't something like this be built-in to XMLReader?
452 * Fetches text contents of the current element, assuming
453 * no sub-elements or such scary things.
454 * @return string
455 * @access private
457 public function nodeContents() {
458 if ( $this->reader->isEmptyElement ) {
459 return "";
461 $buffer = "";
462 while ( $this->reader->read() ) {
463 switch ( $this->reader->nodeType ) {
464 case XMLReader::TEXT:
465 case XMLReader::SIGNIFICANT_WHITESPACE:
466 $buffer .= $this->reader->value;
467 break;
468 case XMLReader::END_ELEMENT:
469 return $buffer;
473 $this->reader->close();
474 return '';
478 * Primary entry point
479 * @throws MWException
480 * @return bool
482 public function doImport() {
483 // Calls to reader->read need to be wrapped in calls to
484 // libxml_disable_entity_loader() to avoid local file
485 // inclusion attacks (bug 46932).
486 $oldDisable = libxml_disable_entity_loader( true );
487 $this->reader->read();
489 if ( $this->reader->name != 'mediawiki' ) {
490 libxml_disable_entity_loader( $oldDisable );
491 throw new MWException( "Expected <mediawiki> tag, got " .
492 $this->reader->name );
494 $this->debug( "<mediawiki> tag is correct." );
496 $this->debug( "Starting primary dump processing loop." );
498 $keepReading = $this->reader->read();
499 $skip = false;
500 while ( $keepReading ) {
501 $tag = $this->reader->name;
502 $type = $this->reader->nodeType;
504 if ( !Hooks::run( 'ImportHandleToplevelXMLTag', array( $this ) ) ) {
505 // Do nothing
506 } elseif ( $tag == 'mediawiki' && $type == XMLReader::END_ELEMENT ) {
507 break;
508 } elseif ( $tag == 'siteinfo' ) {
509 $this->handleSiteInfo();
510 } elseif ( $tag == 'page' ) {
511 $this->handlePage();
512 } elseif ( $tag == 'logitem' ) {
513 $this->handleLogItem();
514 } elseif ( $tag != '#text' ) {
515 $this->warn( "Unhandled top-level XML tag $tag" );
517 $skip = true;
520 if ( $skip ) {
521 $keepReading = $this->reader->next();
522 $skip = false;
523 $this->debug( "Skip" );
524 } else {
525 $keepReading = $this->reader->read();
529 libxml_disable_entity_loader( $oldDisable );
530 return true;
533 private function handleSiteInfo() {
534 $this->debug( "Enter site info handler." );
535 $siteInfo = array();
537 // Fields that can just be stuffed in the siteInfo object
538 $normalFields = array( 'sitename', 'base', 'generator', 'case' );
540 while ( $this->reader->read() ) {
541 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
542 $this->reader->name == 'siteinfo' ) {
543 break;
546 $tag = $this->reader->name;
548 if ( $tag == 'namespace' ) {
549 $this->foreignNamespaces[ $this->nodeAttribute( 'key' ) ] =
550 $this->nodeContents();
551 } elseif ( in_array( $tag, $normalFields ) ) {
552 $siteInfo[$tag] = $this->nodeContents();
556 $siteInfo['_namespaces'] = $this->foreignNamespaces;
557 $this->siteInfoCallback( $siteInfo );
560 private function handleLogItem() {
561 $this->debug( "Enter log item handler." );
562 $logInfo = array();
564 // Fields that can just be stuffed in the pageInfo object
565 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
566 'logtitle', 'params' );
568 while ( $this->reader->read() ) {
569 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
570 $this->reader->name == 'logitem' ) {
571 break;
574 $tag = $this->reader->name;
576 if ( !Hooks::run( 'ImportHandleLogItemXMLTag', array(
577 $this, $logInfo
578 ) ) ) {
579 // Do nothing
580 } elseif ( in_array( $tag, $normalFields ) ) {
581 $logInfo[$tag] = $this->nodeContents();
582 } elseif ( $tag == 'contributor' ) {
583 $logInfo['contributor'] = $this->handleContributor();
584 } elseif ( $tag != '#text' ) {
585 $this->warn( "Unhandled log-item XML tag $tag" );
589 $this->processLogItem( $logInfo );
593 * @param array $logInfo
594 * @return bool|mixed
596 private function processLogItem( $logInfo ) {
597 $revision = new WikiRevision( $this->config );
599 $revision->setID( $logInfo['id'] );
600 $revision->setType( $logInfo['type'] );
601 $revision->setAction( $logInfo['action'] );
602 $revision->setTimestamp( $logInfo['timestamp'] );
603 $revision->setParams( $logInfo['params'] );
604 $revision->setTitle( Title::newFromText( $logInfo['logtitle'] ) );
605 $revision->setNoUpdates( $this->mNoUpdates );
607 if ( isset( $logInfo['comment'] ) ) {
608 $revision->setComment( $logInfo['comment'] );
611 if ( isset( $logInfo['contributor']['ip'] ) ) {
612 $revision->setUserIP( $logInfo['contributor']['ip'] );
614 if ( isset( $logInfo['contributor']['username'] ) ) {
615 $revision->setUserName( $logInfo['contributor']['username'] );
618 return $this->logItemCallback( $revision );
621 private function handlePage() {
622 // Handle page data.
623 $this->debug( "Enter page handler." );
624 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
626 // Fields that can just be stuffed in the pageInfo object
627 $normalFields = array( 'title', 'ns', 'id', 'redirect', 'restrictions' );
629 $skip = false;
630 $badTitle = false;
632 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
633 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
634 $this->reader->name == 'page' ) {
635 break;
638 $skip = false;
640 $tag = $this->reader->name;
642 if ( $badTitle ) {
643 // The title is invalid, bail out of this page
644 $skip = true;
645 } elseif ( !Hooks::run( 'ImportHandlePageXMLTag', array( $this,
646 &$pageInfo ) ) ) {
647 // Do nothing
648 } elseif ( in_array( $tag, $normalFields ) ) {
649 // An XML snippet:
650 // <page>
651 // <id>123</id>
652 // <title>Page</title>
653 // <redirect title="NewTitle"/>
654 // ...
655 // Because the redirect tag is built differently, we need special handling for that case.
656 if ( $tag == 'redirect' ) {
657 $pageInfo[$tag] = $this->nodeAttribute( 'title' );
658 } else {
659 $pageInfo[$tag] = $this->nodeContents();
661 } elseif ( $tag == 'revision' || $tag == 'upload' ) {
662 if ( !isset( $title ) ) {
663 $title = $this->processTitle( $pageInfo['title'],
664 isset( $pageInfo['ns'] ) ? $pageInfo['ns'] : null );
666 if ( !$title ) {
667 $badTitle = true;
668 $skip = true;
671 $this->pageCallback( $title );
672 list( $pageInfo['_title'], $foreignTitle ) = $title;
675 if ( $title ) {
676 if ( $tag == 'revision' ) {
677 $this->handleRevision( $pageInfo );
678 } else {
679 $this->handleUpload( $pageInfo );
682 } elseif ( $tag != '#text' ) {
683 $this->warn( "Unhandled page XML tag $tag" );
684 $skip = true;
688 $this->pageOutCallback( $pageInfo['_title'], $foreignTitle,
689 $pageInfo['revisionCount'],
690 $pageInfo['successfulRevisionCount'],
691 $pageInfo );
695 * @param array $pageInfo
697 private function handleRevision( &$pageInfo ) {
698 $this->debug( "Enter revision handler" );
699 $revisionInfo = array();
701 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'model', 'format', 'text' );
703 $skip = false;
705 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
706 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
707 $this->reader->name == 'revision' ) {
708 break;
711 $tag = $this->reader->name;
713 if ( !Hooks::run( 'ImportHandleRevisionXMLTag', array(
714 $this, $pageInfo, $revisionInfo
715 ) ) ) {
716 // Do nothing
717 } elseif ( in_array( $tag, $normalFields ) ) {
718 $revisionInfo[$tag] = $this->nodeContents();
719 } elseif ( $tag == 'contributor' ) {
720 $revisionInfo['contributor'] = $this->handleContributor();
721 } elseif ( $tag != '#text' ) {
722 $this->warn( "Unhandled revision XML tag $tag" );
723 $skip = true;
727 $pageInfo['revisionCount']++;
728 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
729 $pageInfo['successfulRevisionCount']++;
734 * @param array $pageInfo
735 * @param array $revisionInfo
736 * @return bool|mixed
738 private function processRevision( $pageInfo, $revisionInfo ) {
739 $revision = new WikiRevision( $this->config );
741 if ( isset( $revisionInfo['id'] ) ) {
742 $revision->setID( $revisionInfo['id'] );
744 if ( isset( $revisionInfo['model'] ) ) {
745 $revision->setModel( $revisionInfo['model'] );
747 if ( isset( $revisionInfo['format'] ) ) {
748 $revision->setFormat( $revisionInfo['format'] );
750 $revision->setTitle( $pageInfo['_title'] );
752 if ( isset( $revisionInfo['text'] ) ) {
753 $handler = $revision->getContentHandler();
754 $text = $handler->importTransform(
755 $revisionInfo['text'],
756 $revision->getFormat() );
758 $revision->setText( $text );
760 if ( isset( $revisionInfo['timestamp'] ) ) {
761 $revision->setTimestamp( $revisionInfo['timestamp'] );
762 } else {
763 $revision->setTimestamp( wfTimestampNow() );
766 if ( isset( $revisionInfo['comment'] ) ) {
767 $revision->setComment( $revisionInfo['comment'] );
770 if ( isset( $revisionInfo['minor'] ) ) {
771 $revision->setMinor( true );
773 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
774 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
776 if ( isset( $revisionInfo['contributor']['username'] ) ) {
777 $revision->setUserName( $revisionInfo['contributor']['username'] );
779 $revision->setNoUpdates( $this->mNoUpdates );
781 return $this->revisionCallback( $revision );
785 * @param array $pageInfo
786 * @return mixed
788 private function handleUpload( &$pageInfo ) {
789 $this->debug( "Enter upload handler" );
790 $uploadInfo = array();
792 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
793 'src', 'size', 'sha1base36', 'archivename', 'rel' );
795 $skip = false;
797 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
798 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
799 $this->reader->name == 'upload' ) {
800 break;
803 $tag = $this->reader->name;
805 if ( !Hooks::run( 'ImportHandleUploadXMLTag', array(
806 $this, $pageInfo
807 ) ) ) {
808 // Do nothing
809 } elseif ( in_array( $tag, $normalFields ) ) {
810 $uploadInfo[$tag] = $this->nodeContents();
811 } elseif ( $tag == 'contributor' ) {
812 $uploadInfo['contributor'] = $this->handleContributor();
813 } elseif ( $tag == 'contents' ) {
814 $contents = $this->nodeContents();
815 $encoding = $this->reader->getAttribute( 'encoding' );
816 if ( $encoding === 'base64' ) {
817 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
818 $uploadInfo['isTempSrc'] = true;
820 } elseif ( $tag != '#text' ) {
821 $this->warn( "Unhandled upload XML tag $tag" );
822 $skip = true;
826 if ( $this->mImageBasePath && isset( $uploadInfo['rel'] ) ) {
827 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
828 if ( file_exists( $path ) ) {
829 $uploadInfo['fileSrc'] = $path;
830 $uploadInfo['isTempSrc'] = false;
834 if ( $this->mImportUploads ) {
835 return $this->processUpload( $pageInfo, $uploadInfo );
840 * @param string $contents
841 * @return string
843 private function dumpTemp( $contents ) {
844 $filename = tempnam( wfTempDir(), 'importupload' );
845 file_put_contents( $filename, $contents );
846 return $filename;
850 * @param array $pageInfo
851 * @param array $uploadInfo
852 * @return mixed
854 private function processUpload( $pageInfo, $uploadInfo ) {
855 $revision = new WikiRevision( $this->config );
856 $text = isset( $uploadInfo['text'] ) ? $uploadInfo['text'] : '';
858 $revision->setTitle( $pageInfo['_title'] );
859 $revision->setID( $pageInfo['id'] );
860 $revision->setTimestamp( $uploadInfo['timestamp'] );
861 $revision->setText( $text );
862 $revision->setFilename( $uploadInfo['filename'] );
863 if ( isset( $uploadInfo['archivename'] ) ) {
864 $revision->setArchiveName( $uploadInfo['archivename'] );
866 $revision->setSrc( $uploadInfo['src'] );
867 if ( isset( $uploadInfo['fileSrc'] ) ) {
868 $revision->setFileSrc( $uploadInfo['fileSrc'],
869 !empty( $uploadInfo['isTempSrc'] ) );
871 if ( isset( $uploadInfo['sha1base36'] ) ) {
872 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
874 $revision->setSize( intval( $uploadInfo['size'] ) );
875 $revision->setComment( $uploadInfo['comment'] );
877 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
878 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
880 if ( isset( $uploadInfo['contributor']['username'] ) ) {
881 $revision->setUserName( $uploadInfo['contributor']['username'] );
883 $revision->setNoUpdates( $this->mNoUpdates );
885 return call_user_func( $this->mUploadCallback, $revision );
889 * @return array
891 private function handleContributor() {
892 $fields = array( 'id', 'ip', 'username' );
893 $info = array();
895 while ( $this->reader->read() ) {
896 if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
897 $this->reader->name == 'contributor' ) {
898 break;
901 $tag = $this->reader->name;
903 if ( in_array( $tag, $fields ) ) {
904 $info[$tag] = $this->nodeContents();
908 return $info;
912 * @param string $text
913 * @param string|null $ns
914 * @return array|bool
916 private function processTitle( $text, $ns = null ) {
917 if ( is_null( $this->foreignNamespaces ) ) {
918 $foreignTitleFactory = new NaiveForeignTitleFactory();
919 } else {
920 $foreignTitleFactory = new NamespaceAwareForeignTitleFactory(
921 $this->foreignNamespaces );
924 $foreignTitle = $foreignTitleFactory->createForeignTitle( $text,
925 intval( $ns ) );
927 $title = $this->importTitleFactory->createTitleFromForeignTitle(
928 $foreignTitle );
930 $commandLineMode = $this->config->get( 'CommandLineMode' );
931 if ( is_null( $title ) ) {
932 # Invalid page title? Ignore the page
933 $this->notice( 'import-error-invalid', $foreignTitle->getFullText() );
934 return false;
935 } elseif ( $title->isExternal() ) {
936 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
937 return false;
938 } elseif ( !$title->canExist() ) {
939 $this->notice( 'import-error-special', $title->getPrefixedText() );
940 return false;
941 } elseif ( !$title->userCan( 'edit' ) && !$commandLineMode ) {
942 # Do not import if the importing wiki user cannot edit this page
943 $this->notice( 'import-error-edit', $title->getPrefixedText() );
944 return false;
945 } elseif ( !$title->exists() && !$title->userCan( 'create' ) && !$commandLineMode ) {
946 # Do not import if the importing wiki user cannot create this page
947 $this->notice( 'import-error-create', $title->getPrefixedText() );
948 return false;
951 return array( $title, $foreignTitle );
955 /** This is a horrible hack used to keep source compatibility */
956 class UploadSourceAdapter {
957 /** @var array */
958 public static $sourceRegistrations = array();
960 /** @var string */
961 private $mSource;
963 /** @var string */
964 private $mBuffer;
966 /** @var int */
967 private $mPosition;
970 * @param ImportStreamSource $source
971 * @return string
973 static function registerSource( ImportStreamSource $source ) {
974 $id = wfRandomString();
976 self::$sourceRegistrations[$id] = $source;
978 return $id;
982 * @param string $path
983 * @param string $mode
984 * @param array $options
985 * @param string $opened_path
986 * @return bool
988 function stream_open( $path, $mode, $options, &$opened_path ) {
989 $url = parse_url( $path );
990 $id = $url['host'];
992 if ( !isset( self::$sourceRegistrations[$id] ) ) {
993 return false;
996 $this->mSource = self::$sourceRegistrations[$id];
998 return true;
1002 * @param int $count
1003 * @return string
1005 function stream_read( $count ) {
1006 $return = '';
1007 $leave = false;
1009 while ( !$leave && !$this->mSource->atEnd() &&
1010 strlen( $this->mBuffer ) < $count ) {
1011 $read = $this->mSource->readChunk();
1013 if ( !strlen( $read ) ) {
1014 $leave = true;
1017 $this->mBuffer .= $read;
1020 if ( strlen( $this->mBuffer ) ) {
1021 $return = substr( $this->mBuffer, 0, $count );
1022 $this->mBuffer = substr( $this->mBuffer, $count );
1025 $this->mPosition += strlen( $return );
1027 return $return;
1031 * @param string $data
1032 * @return bool
1034 function stream_write( $data ) {
1035 return false;
1039 * @return mixed
1041 function stream_tell() {
1042 return $this->mPosition;
1046 * @return bool
1048 function stream_eof() {
1049 return $this->mSource->atEnd();
1053 * @return array
1055 function url_stat() {
1056 $result = array();
1058 $result['dev'] = $result[0] = 0;
1059 $result['ino'] = $result[1] = 0;
1060 $result['mode'] = $result[2] = 0;
1061 $result['nlink'] = $result[3] = 0;
1062 $result['uid'] = $result[4] = 0;
1063 $result['gid'] = $result[5] = 0;
1064 $result['rdev'] = $result[6] = 0;
1065 $result['size'] = $result[7] = 0;
1066 $result['atime'] = $result[8] = 0;
1067 $result['mtime'] = $result[9] = 0;
1068 $result['ctime'] = $result[10] = 0;
1069 $result['blksize'] = $result[11] = 0;
1070 $result['blocks'] = $result[12] = 0;
1072 return $result;
1077 * @todo document (e.g. one-sentence class description).
1078 * @ingroup SpecialPage
1080 class WikiRevision {
1081 /** @todo Unused? */
1082 public $importer = null;
1084 /** @var Title */
1085 public $title = null;
1087 /** @var int */
1088 public $id = 0;
1090 /** @var string */
1091 public $timestamp = "20010115000000";
1094 * @var int
1095 * @todo Can't find any uses. Public, because that's suspicious. Get clarity. */
1096 public $user = 0;
1098 /** @var string */
1099 public $user_text = "";
1101 /** @var string */
1102 public $model = null;
1104 /** @var string */
1105 public $format = null;
1107 /** @var string */
1108 public $text = "";
1110 /** @var int */
1111 protected $size;
1113 /** @var Content */
1114 public $content = null;
1116 /** @var ContentHandler */
1117 protected $contentHandler = null;
1119 /** @var string */
1120 public $comment = "";
1122 /** @var bool */
1123 public $minor = false;
1125 /** @var string */
1126 public $type = "";
1128 /** @var string */
1129 public $action = "";
1131 /** @var string */
1132 public $params = "";
1134 /** @var string */
1135 public $fileSrc = '';
1137 /** @var bool|string */
1138 public $sha1base36 = false;
1141 * @var bool
1142 * @todo Unused?
1144 public $isTemp = false;
1146 /** @var string */
1147 public $archiveName = '';
1149 protected $filename;
1151 /** @var mixed */
1152 protected $src;
1154 /** @todo Unused? */
1155 public $fileIsTemp;
1157 /** @var bool */
1158 private $mNoUpdates = false;
1160 /** @var Config $config */
1161 private $config;
1163 public function __construct( Config $config ) {
1164 $this->config = $config;
1168 * @param Title $title
1169 * @throws MWException
1171 function setTitle( $title ) {
1172 if ( is_object( $title ) ) {
1173 $this->title = $title;
1174 } elseif ( is_null( $title ) ) {
1175 throw new MWException( "WikiRevision given a null title in import. "
1176 . "You may need to adjust \$wgLegalTitleChars." );
1177 } else {
1178 throw new MWException( "WikiRevision given non-object title in import." );
1183 * @param int $id
1185 function setID( $id ) {
1186 $this->id = $id;
1190 * @param string $ts
1192 function setTimestamp( $ts ) {
1193 # 2003-08-05T18:30:02Z
1194 $this->timestamp = wfTimestamp( TS_MW, $ts );
1198 * @param string $user
1200 function setUsername( $user ) {
1201 $this->user_text = $user;
1205 * @param string $ip
1207 function setUserIP( $ip ) {
1208 $this->user_text = $ip;
1212 * @param string $model
1214 function setModel( $model ) {
1215 $this->model = $model;
1219 * @param string $format
1221 function setFormat( $format ) {
1222 $this->format = $format;
1226 * @param string $text
1228 function setText( $text ) {
1229 $this->text = $text;
1233 * @param string $text
1235 function setComment( $text ) {
1236 $this->comment = $text;
1240 * @param bool $minor
1242 function setMinor( $minor ) {
1243 $this->minor = (bool)$minor;
1247 * @param mixed $src
1249 function setSrc( $src ) {
1250 $this->src = $src;
1254 * @param string $src
1255 * @param bool $isTemp
1257 function setFileSrc( $src, $isTemp ) {
1258 $this->fileSrc = $src;
1259 $this->fileIsTemp = $isTemp;
1263 * @param string $sha1base36
1265 function setSha1Base36( $sha1base36 ) {
1266 $this->sha1base36 = $sha1base36;
1270 * @param string $filename
1272 function setFilename( $filename ) {
1273 $this->filename = $filename;
1277 * @param string $archiveName
1279 function setArchiveName( $archiveName ) {
1280 $this->archiveName = $archiveName;
1284 * @param int $size
1286 function setSize( $size ) {
1287 $this->size = intval( $size );
1291 * @param string $type
1293 function setType( $type ) {
1294 $this->type = $type;
1298 * @param string $action
1300 function setAction( $action ) {
1301 $this->action = $action;
1305 * @param array $params
1307 function setParams( $params ) {
1308 $this->params = $params;
1312 * @param bool $noupdates
1314 public function setNoUpdates( $noupdates ) {
1315 $this->mNoUpdates = $noupdates;
1319 * @return Title
1321 function getTitle() {
1322 return $this->title;
1326 * @return int
1328 function getID() {
1329 return $this->id;
1333 * @return string
1335 function getTimestamp() {
1336 return $this->timestamp;
1340 * @return string
1342 function getUser() {
1343 return $this->user_text;
1347 * @return string
1349 * @deprecated Since 1.21, use getContent() instead.
1351 function getText() {
1352 ContentHandler::deprecated( __METHOD__, '1.21' );
1354 return $this->text;
1358 * @return ContentHandler
1360 function getContentHandler() {
1361 if ( is_null( $this->contentHandler ) ) {
1362 $this->contentHandler = ContentHandler::getForModelID( $this->getModel() );
1365 return $this->contentHandler;
1369 * @return Content
1371 function getContent() {
1372 if ( is_null( $this->content ) ) {
1373 $handler = $this->getContentHandler();
1374 $this->content = $handler->unserializeContent( $this->text, $this->getFormat() );
1377 return $this->content;
1381 * @return string
1383 function getModel() {
1384 if ( is_null( $this->model ) ) {
1385 $this->model = $this->getTitle()->getContentModel();
1388 return $this->model;
1392 * @return string
1394 function getFormat() {
1395 if ( is_null( $this->format ) ) {
1396 $this->format = $this->getContentHandler()->getDefaultFormat();
1399 return $this->format;
1403 * @return string
1405 function getComment() {
1406 return $this->comment;
1410 * @return bool
1412 function getMinor() {
1413 return $this->minor;
1417 * @return mixed
1419 function getSrc() {
1420 return $this->src;
1424 * @return bool|string
1426 function getSha1() {
1427 if ( $this->sha1base36 ) {
1428 return wfBaseConvert( $this->sha1base36, 36, 16 );
1430 return false;
1434 * @return string
1436 function getFileSrc() {
1437 return $this->fileSrc;
1441 * @return bool
1443 function isTempSrc() {
1444 return $this->isTemp;
1448 * @return mixed
1450 function getFilename() {
1451 return $this->filename;
1455 * @return string
1457 function getArchiveName() {
1458 return $this->archiveName;
1462 * @return mixed
1464 function getSize() {
1465 return $this->size;
1469 * @return string
1471 function getType() {
1472 return $this->type;
1476 * @return string
1478 function getAction() {
1479 return $this->action;
1483 * @return string
1485 function getParams() {
1486 return $this->params;
1490 * @return bool
1492 function importOldRevision() {
1493 $dbw = wfGetDB( DB_MASTER );
1495 # Sneak a single revision into place
1496 $user = User::newFromName( $this->getUser() );
1497 if ( $user ) {
1498 $userId = intval( $user->getId() );
1499 $userText = $user->getName();
1500 $userObj = $user;
1501 } else {
1502 $userId = 0;
1503 $userText = $this->getUser();
1504 $userObj = new User;
1507 // avoid memory leak...?
1508 $linkCache = LinkCache::singleton();
1509 $linkCache->clear();
1511 $page = WikiPage::factory( $this->title );
1512 $page->loadPageData( 'fromdbmaster' );
1513 if ( !$page->exists() ) {
1514 # must create the page...
1515 $pageId = $page->insertOn( $dbw );
1516 $created = true;
1517 $oldcountable = null;
1518 } else {
1519 $pageId = $page->getId();
1520 $created = false;
1522 $prior = $dbw->selectField( 'revision', '1',
1523 array( 'rev_page' => $pageId,
1524 'rev_timestamp' => $dbw->timestamp( $this->timestamp ),
1525 'rev_user_text' => $userText,
1526 'rev_comment' => $this->getComment() ),
1527 __METHOD__
1529 if ( $prior ) {
1530 // @todo FIXME: This could fail slightly for multiple matches :P
1531 wfDebug( __METHOD__ . ": skipping existing revision for [[" .
1532 $this->title->getPrefixedText() . "]], timestamp " . $this->timestamp . "\n" );
1533 return false;
1535 $oldcountable = $page->isCountable();
1538 # @todo FIXME: Use original rev_id optionally (better for backups)
1539 # Insert the row
1540 $revision = new Revision( array(
1541 'title' => $this->title,
1542 'page' => $pageId,
1543 'content_model' => $this->getModel(),
1544 'content_format' => $this->getFormat(),
1545 //XXX: just set 'content' => $this->getContent()?
1546 'text' => $this->getContent()->serialize( $this->getFormat() ),
1547 'comment' => $this->getComment(),
1548 'user' => $userId,
1549 'user_text' => $userText,
1550 'timestamp' => $this->timestamp,
1551 'minor_edit' => $this->minor,
1552 ) );
1553 $revision->insertOn( $dbw );
1554 $changed = $page->updateIfNewerOn( $dbw, $revision );
1556 if ( $changed !== false && !$this->mNoUpdates ) {
1557 wfDebug( __METHOD__ . ": running updates\n" );
1558 $page->doEditUpdates(
1559 $revision,
1560 $userObj,
1561 array( 'created' => $created, 'oldcountable' => $oldcountable )
1565 return true;
1568 function importLogItem() {
1569 $dbw = wfGetDB( DB_MASTER );
1570 # @todo FIXME: This will not record autoblocks
1571 if ( !$this->getTitle() ) {
1572 wfDebug( __METHOD__ . ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1573 $this->timestamp . "\n" );
1574 return;
1576 # Check if it exists already
1577 // @todo FIXME: Use original log ID (better for backups)
1578 $prior = $dbw->selectField( 'logging', '1',
1579 array( 'log_type' => $this->getType(),
1580 'log_action' => $this->getAction(),
1581 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
1582 'log_namespace' => $this->getTitle()->getNamespace(),
1583 'log_title' => $this->getTitle()->getDBkey(),
1584 'log_comment' => $this->getComment(),
1585 #'log_user_text' => $this->user_text,
1586 'log_params' => $this->params ),
1587 __METHOD__
1589 // @todo FIXME: This could fail slightly for multiple matches :P
1590 if ( $prior ) {
1591 wfDebug( __METHOD__
1592 . ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp "
1593 . $this->timestamp . "\n" );
1594 return;
1596 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1597 $data = array(
1598 'log_id' => $log_id,
1599 'log_type' => $this->type,
1600 'log_action' => $this->action,
1601 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
1602 'log_user' => User::idFromName( $this->user_text ),
1603 #'log_user_text' => $this->user_text,
1604 'log_namespace' => $this->getTitle()->getNamespace(),
1605 'log_title' => $this->getTitle()->getDBkey(),
1606 'log_comment' => $this->getComment(),
1607 'log_params' => $this->params
1609 $dbw->insert( 'logging', $data, __METHOD__ );
1613 * @return bool
1615 function importUpload() {
1616 # Construct a file
1617 $archiveName = $this->getArchiveName();
1618 if ( $archiveName ) {
1619 wfDebug( __METHOD__ . "Importing archived file as $archiveName\n" );
1620 $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
1621 RepoGroup::singleton()->getLocalRepo(), $archiveName );
1622 } else {
1623 $file = wfLocalFile( $this->getTitle() );
1624 wfDebug( __METHOD__ . 'Importing new file as ' . $file->getName() . "\n" );
1625 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1626 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1627 $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
1628 RepoGroup::singleton()->getLocalRepo(), $archiveName );
1629 wfDebug( __METHOD__ . "File already exists; importing as $archiveName\n" );
1632 if ( !$file ) {
1633 wfDebug( __METHOD__ . ': Bad file for ' . $this->getTitle() . "\n" );
1634 return false;
1637 # Get the file source or download if necessary
1638 $source = $this->getFileSrc();
1639 $flags = $this->isTempSrc() ? File::DELETE_SOURCE : 0;
1640 if ( !$source ) {
1641 $source = $this->downloadSource();
1642 $flags |= File::DELETE_SOURCE;
1644 if ( !$source ) {
1645 wfDebug( __METHOD__ . ": Could not fetch remote file.\n" );
1646 return false;
1648 $sha1 = $this->getSha1();
1649 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1650 if ( $flags & File::DELETE_SOURCE ) {
1651 # Broken file; delete it if it is a temporary file
1652 unlink( $source );
1654 wfDebug( __METHOD__ . ": Corrupt file $source.\n" );
1655 return false;
1658 $user = User::newFromName( $this->user_text );
1660 # Do the actual upload
1661 if ( $archiveName ) {
1662 $status = $file->uploadOld( $source, $archiveName,
1663 $this->getTimestamp(), $this->getComment(), $user, $flags );
1664 } else {
1665 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1666 $flags, false, $this->getTimestamp(), $user );
1669 if ( $status->isGood() ) {
1670 wfDebug( __METHOD__ . ": Successful\n" );
1671 return true;
1672 } else {
1673 wfDebug( __METHOD__ . ': failed: ' . $status->getXml() . "\n" );
1674 return false;
1679 * @return bool|string
1681 function downloadSource() {
1682 if ( !$this->config->get( 'EnableUploads' ) ) {
1683 return false;
1686 $tempo = tempnam( wfTempDir(), 'download' );
1687 $f = fopen( $tempo, 'wb' );
1688 if ( !$f ) {
1689 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1690 return false;
1693 // @todo FIXME!
1694 $src = $this->getSrc();
1695 $data = Http::get( $src );
1696 if ( !$data ) {
1697 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1698 fclose( $f );
1699 unlink( $tempo );
1700 return false;
1703 fwrite( $f, $data );
1704 fclose( $f );
1706 return $tempo;
1712 * Used for importing XML dumps where the content of the dump is in a string.
1713 * This class is ineffecient, and should only be used for small dumps.
1714 * For larger dumps, ImportStreamSource should be used instead.
1716 * @ingroup SpecialPage
1718 class ImportStringSource {
1719 function __construct( $string ) {
1720 $this->mString = $string;
1721 $this->mRead = false;
1725 * @return bool
1727 function atEnd() {
1728 return $this->mRead;
1732 * @return bool|string
1734 function readChunk() {
1735 if ( $this->atEnd() ) {
1736 return false;
1738 $this->mRead = true;
1739 return $this->mString;
1744 * Imports a XML dump from a file (either from file upload, files on disk, or HTTP)
1745 * @ingroup SpecialPage
1747 class ImportStreamSource {
1748 function __construct( $handle ) {
1749 $this->mHandle = $handle;
1753 * @return bool
1755 function atEnd() {
1756 return feof( $this->mHandle );
1760 * @return string
1762 function readChunk() {
1763 return fread( $this->mHandle, 32768 );
1767 * @param string $filename
1768 * @return Status
1770 static function newFromFile( $filename ) {
1771 wfSuppressWarnings();
1772 $file = fopen( $filename, 'rt' );
1773 wfRestoreWarnings();
1774 if ( !$file ) {
1775 return Status::newFatal( "importcantopen" );
1777 return Status::newGood( new ImportStreamSource( $file ) );
1781 * @param string $fieldname
1782 * @return Status
1784 static function newFromUpload( $fieldname = "xmlimport" ) {
1785 $upload =& $_FILES[$fieldname];
1787 if ( $upload === null || !$upload['name'] ) {
1788 return Status::newFatal( 'importnofile' );
1790 if ( !empty( $upload['error'] ) ) {
1791 switch ( $upload['error'] ) {
1792 case 1:
1793 # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1794 return Status::newFatal( 'importuploaderrorsize' );
1795 case 2:
1796 # The uploaded file exceeds the MAX_FILE_SIZE directive that
1797 # was specified in the HTML form.
1798 return Status::newFatal( 'importuploaderrorsize' );
1799 case 3:
1800 # The uploaded file was only partially uploaded
1801 return Status::newFatal( 'importuploaderrorpartial' );
1802 case 6:
1803 # Missing a temporary folder.
1804 return Status::newFatal( 'importuploaderrortemp' );
1805 # case else: # Currently impossible
1809 $fname = $upload['tmp_name'];
1810 if ( is_uploaded_file( $fname ) ) {
1811 return ImportStreamSource::newFromFile( $fname );
1812 } else {
1813 return Status::newFatal( 'importnofile' );
1818 * @param string $url
1819 * @param string $method
1820 * @return Status
1822 static function newFromURL( $url, $method = 'GET' ) {
1823 wfDebug( __METHOD__ . ": opening $url\n" );
1824 # Use the standard HTTP fetch function; it times out
1825 # quicker and sorts out user-agent problems which might
1826 # otherwise prevent importing from large sites, such
1827 # as the Wikimedia cluster, etc.
1828 $data = Http::request( $method, $url, array( 'followRedirects' => true ) );
1829 if ( $data !== false ) {
1830 $file = tmpfile();
1831 fwrite( $file, $data );
1832 fflush( $file );
1833 fseek( $file, 0 );
1834 return Status::newGood( new ImportStreamSource( $file ) );
1835 } else {
1836 return Status::newFatal( 'importcantopen' );
1841 * @param string $interwiki
1842 * @param string $page
1843 * @param bool $history
1844 * @param bool $templates
1845 * @param int $pageLinkDepth
1846 * @return Status
1848 public static function newFromInterwiki( $interwiki, $page, $history = false,
1849 $templates = false, $pageLinkDepth = 0
1851 if ( $page == '' ) {
1852 return Status::newFatal( 'import-noarticle' );
1854 $link = Title::newFromText( "$interwiki:Special:Export/$page" );
1855 if ( is_null( $link ) || !$link->isExternal() ) {
1856 return Status::newFatal( 'importbadinterwiki' );
1857 } else {
1858 $params = array();
1859 if ( $history ) {
1860 $params['history'] = 1;
1862 if ( $templates ) {
1863 $params['templates'] = 1;
1865 if ( $pageLinkDepth ) {
1866 $params['pagelink-depth'] = $pageLinkDepth;
1868 $url = $link->getFullURL( $params );
1869 # For interwikis, use POST to avoid redirects.
1870 return ImportStreamSource::newFromURL( $url, "POST" );