Move Modern and CologneBlue out of core
[mediawiki.git] / includes / Import.php
blob1a3e05aa344a989e9594ff377af4305e420f5a78
1 <?php
2 /**
3 * MediaWiki page data importer.
5 * Copyright © 2003,2005 Brion Vibber <brion@pobox.com>
6 * https://www.mediawiki.org/
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
23 * @file
24 * @ingroup SpecialPage
27 /**
28 * XML file reader for the page data importer
30 * implements Special:Import
31 * @ingroup SpecialPage
33 class WikiImporter {
34 private $reader = null;
35 private $mLogItemCallback, $mUploadCallback, $mRevisionCallback, $mPageCallback;
36 private $mSiteInfoCallback, $mTargetNamespace, $mTargetRootPage, $mPageOutCallback;
37 private $mNoticeCallback, $mDebug;
38 private $mImportUploads, $mImageBasePath;
39 private $mNoUpdates = false;
41 /**
42 * Creates an ImportXMLReader drawing from the source provided
43 * @param string $source
45 function __construct( $source ) {
46 $this->reader = new XMLReader();
48 if ( !in_array( 'uploadsource', stream_get_wrappers() ) ) {
49 stream_wrapper_register( 'uploadsource', 'UploadSourceAdapter' );
51 $id = UploadSourceAdapter::registerSource( $source );
52 if ( defined( 'LIBXML_PARSEHUGE' ) ) {
53 $this->reader->open( "uploadsource://$id", null, LIBXML_PARSEHUGE );
54 } else {
55 $this->reader->open( "uploadsource://$id" );
58 // Default callbacks
59 $this->setRevisionCallback( array( $this, "importRevision" ) );
60 $this->setUploadCallback( array( $this, 'importUpload' ) );
61 $this->setLogItemCallback( array( $this, 'importLogItem' ) );
62 $this->setPageOutCallback( array( $this, 'finishImportPage' ) );
65 /**
66 * @return null|XMLReader
68 public function getReader() {
69 return $this->reader;
72 public function throwXmlError( $err ) {
73 $this->debug( "FAILURE: $err" );
74 wfDebug( "WikiImporter XML error: $err\n" );
77 public function debug( $data ) {
78 if ( $this->mDebug ) {
79 wfDebug( "IMPORT: $data\n" );
83 public function warn( $data ) {
84 wfDebug( "IMPORT: $data\n" );
87 public function notice( $msg /*, $param, ...*/ ) {
88 $params = func_get_args();
89 array_shift( $params );
91 if ( is_callable( $this->mNoticeCallback ) ) {
92 call_user_func( $this->mNoticeCallback, $msg, $params );
93 } else { # No ImportReporter -> CLI
94 echo wfMessage( $msg, $params )->text() . "\n";
98 /**
99 * Set debug mode...
100 * @param bool $debug
102 function setDebug( $debug ) {
103 $this->mDebug = $debug;
107 * Set 'no updates' mode. In this mode, the link tables will not be updated by the importer
108 * @param bool $noupdates
110 function setNoUpdates( $noupdates ) {
111 $this->mNoUpdates = $noupdates;
115 * Set a callback that displays notice messages
117 * @param callable $callback
118 * @return callable
120 public function setNoticeCallback( $callback ) {
121 return wfSetVar( $this->mNoticeCallback, $callback );
125 * Sets the action to perform as each new page in the stream is reached.
126 * @param callable $callback
127 * @return callable
129 public function setPageCallback( $callback ) {
130 $previous = $this->mPageCallback;
131 $this->mPageCallback = $callback;
132 return $previous;
136 * Sets the action to perform as each page in the stream is completed.
137 * Callback accepts the page title (as a Title object), a second object
138 * with the original title form (in case it's been overridden into a
139 * local namespace), and a count of revisions.
141 * @param callable $callback
142 * @return callable
144 public function setPageOutCallback( $callback ) {
145 $previous = $this->mPageOutCallback;
146 $this->mPageOutCallback = $callback;
147 return $previous;
151 * Sets the action to perform as each page revision is reached.
152 * @param callable $callback
153 * @return callable
155 public function setRevisionCallback( $callback ) {
156 $previous = $this->mRevisionCallback;
157 $this->mRevisionCallback = $callback;
158 return $previous;
162 * Sets the action to perform as each file upload version is reached.
163 * @param callable $callback
164 * @return callable
166 public function setUploadCallback( $callback ) {
167 $previous = $this->mUploadCallback;
168 $this->mUploadCallback = $callback;
169 return $previous;
173 * Sets the action to perform as each log item reached.
174 * @param callable $callback
175 * @return callable
177 public function setLogItemCallback( $callback ) {
178 $previous = $this->mLogItemCallback;
179 $this->mLogItemCallback = $callback;
180 return $previous;
184 * Sets the action to perform when site info is encountered
185 * @param callable $callback
186 * @return callable
188 public function setSiteInfoCallback( $callback ) {
189 $previous = $this->mSiteInfoCallback;
190 $this->mSiteInfoCallback = $callback;
191 return $previous;
195 * Set a target namespace to override the defaults
196 * @param null|int $namespace
197 * @return bool
199 public function setTargetNamespace( $namespace ) {
200 if ( is_null( $namespace ) ) {
201 // Don't override namespaces
202 $this->mTargetNamespace = null;
203 } elseif ( $namespace >= 0 ) {
204 // @todo FIXME: Check for validity
205 $this->mTargetNamespace = intval( $namespace );
206 } else {
207 return false;
212 * Set a target root page under which all pages are imported
213 * @param null|string $rootpage
214 * @return Status
216 public function setTargetRootPage( $rootpage ) {
217 $status = Status::newGood();
218 if ( is_null( $rootpage ) ) {
219 // No rootpage
220 $this->mTargetRootPage = null;
221 } elseif ( $rootpage !== '' ) {
222 $rootpage = rtrim( $rootpage, '/' ); //avoid double slashes
223 $title = Title::newFromText( $rootpage, !is_null( $this->mTargetNamespace )
224 ? $this->mTargetNamespace
225 : NS_MAIN
228 if ( !$title || $title->isExternal() ) {
229 $status->fatal( 'import-rootpage-invalid' );
230 } else {
231 if ( !MWNamespace::hasSubpages( $title->getNamespace() ) ) {
232 global $wgContLang;
234 $displayNSText = $title->getNamespace() == NS_MAIN
235 ? wfMessage( 'blanknamespace' )->text()
236 : $wgContLang->getNsText( $title->getNamespace() );
237 $status->fatal( 'import-rootpage-nosubpage', $displayNSText );
238 } else {
239 // set namespace to 'all', so the namespace check in processTitle() can passed
240 $this->setTargetNamespace( null );
241 $this->mTargetRootPage = $title->getPrefixedDBkey();
245 return $status;
249 * @param string $dir
251 public function setImageBasePath( $dir ) {
252 $this->mImageBasePath = $dir;
256 * @param bool $import
258 public function setImportUploads( $import ) {
259 $this->mImportUploads = $import;
263 * Default per-revision callback, performs the import.
264 * @param WikiRevision $revision
265 * @return bool
267 public function importRevision( $revision ) {
268 if ( !$revision->getContentHandler()->canBeUsedOn( $revision->getTitle() ) ) {
269 $this->notice( 'import-error-bad-location',
270 $revision->getTitle()->getPrefixedText(),
271 $revision->getID(),
272 $revision->getModel(),
273 $revision->getFormat() );
275 return false;
278 try {
279 $dbw = wfGetDB( DB_MASTER );
280 return $dbw->deadlockLoop( array( $revision, 'importOldRevision' ) );
281 } catch ( MWContentSerializationException $ex ) {
282 $this->notice( 'import-error-unserialize',
283 $revision->getTitle()->getPrefixedText(),
284 $revision->getID(),
285 $revision->getModel(),
286 $revision->getFormat() );
289 return false;
293 * Default per-revision callback, performs the import.
294 * @param WikiRevision $revision
295 * @return bool
297 public function importLogItem( $revision ) {
298 $dbw = wfGetDB( DB_MASTER );
299 return $dbw->deadlockLoop( array( $revision, 'importLogItem' ) );
303 * Dummy for now...
304 * @param WikiRevision $revision
305 * @return bool
307 public function importUpload( $revision ) {
308 $dbw = wfGetDB( DB_MASTER );
309 return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
313 * Mostly for hook use
314 * @param Title $title
315 * @param string $origTitle
316 * @param int $revCount
317 * @param int $sRevCount
318 * @param array $pageInfo
319 * @return bool
321 public function finishImportPage( $title, $origTitle, $revCount, $sRevCount, $pageInfo ) {
322 $args = func_get_args();
323 return wfRunHooks( 'AfterImportPage', $args );
327 * Alternate per-revision callback, for debugging.
328 * @param WikiRevision $revision
330 public function debugRevisionHandler( &$revision ) {
331 $this->debug( "Got revision:" );
332 if ( is_object( $revision->title ) ) {
333 $this->debug( "-- Title: " . $revision->title->getPrefixedText() );
334 } else {
335 $this->debug( "-- Title: <invalid>" );
337 $this->debug( "-- User: " . $revision->user_text );
338 $this->debug( "-- Timestamp: " . $revision->timestamp );
339 $this->debug( "-- Comment: " . $revision->comment );
340 $this->debug( "-- Text: " . $revision->text );
344 * Notify the callback function when a new "<page>" is reached.
345 * @param Title $title
347 function pageCallback( $title ) {
348 if ( isset( $this->mPageCallback ) ) {
349 call_user_func( $this->mPageCallback, $title );
354 * Notify the callback function when a "</page>" is closed.
355 * @param Title $title
356 * @param Title $origTitle
357 * @param int $revCount
358 * @param int $sucCount Number of revisions for which callback returned true
359 * @param array $pageInfo Associative array of page information
361 private function pageOutCallback( $title, $origTitle, $revCount, $sucCount, $pageInfo ) {
362 if ( isset( $this->mPageOutCallback ) ) {
363 $args = func_get_args();
364 call_user_func_array( $this->mPageOutCallback, $args );
369 * Notify the callback function of a revision
370 * @param WikiRevision $revision
371 * @return bool|mixed
373 private function revisionCallback( $revision ) {
374 if ( isset( $this->mRevisionCallback ) ) {
375 return call_user_func_array( $this->mRevisionCallback,
376 array( $revision, $this ) );
377 } else {
378 return false;
383 * Notify the callback function of a new log item
384 * @param WikiRevision $revision
385 * @return bool|mixed
387 private function logItemCallback( $revision ) {
388 if ( isset( $this->mLogItemCallback ) ) {
389 return call_user_func_array( $this->mLogItemCallback,
390 array( $revision, $this ) );
391 } else {
392 return false;
397 * Shouldn't something like this be built-in to XMLReader?
398 * Fetches text contents of the current element, assuming
399 * no sub-elements or such scary things.
400 * @return string
401 * @access private
403 public function nodeContents() {
404 if ( $this->reader->isEmptyElement ) {
405 return "";
407 $buffer = "";
408 while ( $this->reader->read() ) {
409 switch ( $this->reader->nodeType ) {
410 case XmlReader::TEXT:
411 case XmlReader::SIGNIFICANT_WHITESPACE:
412 $buffer .= $this->reader->value;
413 break;
414 case XmlReader::END_ELEMENT:
415 return $buffer;
419 $this->reader->close();
420 return '';
423 # --------------
425 /** Left in for debugging */
426 private function dumpElement() {
427 static $lookup = null;
428 if ( !$lookup ) {
429 $xmlReaderConstants = array(
430 "NONE",
431 "ELEMENT",
432 "ATTRIBUTE",
433 "TEXT",
434 "CDATA",
435 "ENTITY_REF",
436 "ENTITY",
437 "PI",
438 "COMMENT",
439 "DOC",
440 "DOC_TYPE",
441 "DOC_FRAGMENT",
442 "NOTATION",
443 "WHITESPACE",
444 "SIGNIFICANT_WHITESPACE",
445 "END_ELEMENT",
446 "END_ENTITY",
447 "XML_DECLARATION",
449 $lookup = array();
451 foreach ( $xmlReaderConstants as $name ) {
452 $lookup[constant( "XmlReader::$name" )] = $name;
456 print var_dump(
457 $lookup[$this->reader->nodeType],
458 $this->reader->name,
459 $this->reader->value
460 ) . "\n\n";
464 * Primary entry point
465 * @throws MWException
466 * @return bool
468 public function doImport() {
470 // Calls to reader->read need to be wrapped in calls to
471 // libxml_disable_entity_loader() to avoid local file
472 // inclusion attacks (bug 46932).
473 $oldDisable = libxml_disable_entity_loader( true );
474 $this->reader->read();
476 if ( $this->reader->name != 'mediawiki' ) {
477 libxml_disable_entity_loader( $oldDisable );
478 throw new MWException( "Expected <mediawiki> tag, got " .
479 $this->reader->name );
481 $this->debug( "<mediawiki> tag is correct." );
483 $this->debug( "Starting primary dump processing loop." );
485 $keepReading = $this->reader->read();
486 $skip = false;
487 while ( $keepReading ) {
488 $tag = $this->reader->name;
489 $type = $this->reader->nodeType;
491 if ( !wfRunHooks( 'ImportHandleToplevelXMLTag', array( $this ) ) ) {
492 // Do nothing
493 } elseif ( $tag == 'mediawiki' && $type == XmlReader::END_ELEMENT ) {
494 break;
495 } elseif ( $tag == 'siteinfo' ) {
496 $this->handleSiteInfo();
497 } elseif ( $tag == 'page' ) {
498 $this->handlePage();
499 } elseif ( $tag == 'logitem' ) {
500 $this->handleLogItem();
501 } elseif ( $tag != '#text' ) {
502 $this->warn( "Unhandled top-level XML tag $tag" );
504 $skip = true;
507 if ( $skip ) {
508 $keepReading = $this->reader->next();
509 $skip = false;
510 $this->debug( "Skip" );
511 } else {
512 $keepReading = $this->reader->read();
516 libxml_disable_entity_loader( $oldDisable );
517 return true;
521 * @return bool
522 * @throws MWException
524 private function handleSiteInfo() {
525 // Site info is useful, but not actually used for dump imports.
526 // Includes a quick short-circuit to save performance.
527 if ( ! $this->mSiteInfoCallback ) {
528 $this->reader->next();
529 return true;
531 throw new MWException( "SiteInfo tag is not yet handled, do not set mSiteInfoCallback" );
534 private function handleLogItem() {
535 $this->debug( "Enter log item handler." );
536 $logInfo = array();
538 // Fields that can just be stuffed in the pageInfo object
539 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
540 'logtitle', 'params' );
542 while ( $this->reader->read() ) {
543 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
544 $this->reader->name == 'logitem' ) {
545 break;
548 $tag = $this->reader->name;
550 if ( !wfRunHooks( 'ImportHandleLogItemXMLTag', array(
551 $this, $logInfo
552 ) ) ) {
553 // Do nothing
554 } elseif ( in_array( $tag, $normalFields ) ) {
555 $logInfo[$tag] = $this->nodeContents();
556 } elseif ( $tag == 'contributor' ) {
557 $logInfo['contributor'] = $this->handleContributor();
558 } elseif ( $tag != '#text' ) {
559 $this->warn( "Unhandled log-item XML tag $tag" );
563 $this->processLogItem( $logInfo );
567 * @param array $logInfo
568 * @return bool|mixed
570 private function processLogItem( $logInfo ) {
571 $revision = new WikiRevision;
573 $revision->setID( $logInfo['id'] );
574 $revision->setType( $logInfo['type'] );
575 $revision->setAction( $logInfo['action'] );
576 $revision->setTimestamp( $logInfo['timestamp'] );
577 $revision->setParams( $logInfo['params'] );
578 $revision->setTitle( Title::newFromText( $logInfo['logtitle'] ) );
579 $revision->setNoUpdates( $this->mNoUpdates );
581 if ( isset( $logInfo['comment'] ) ) {
582 $revision->setComment( $logInfo['comment'] );
585 if ( isset( $logInfo['contributor']['ip'] ) ) {
586 $revision->setUserIP( $logInfo['contributor']['ip'] );
588 if ( isset( $logInfo['contributor']['username'] ) ) {
589 $revision->setUserName( $logInfo['contributor']['username'] );
592 return $this->logItemCallback( $revision );
595 private function handlePage() {
596 // Handle page data.
597 $this->debug( "Enter page handler." );
598 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
600 // Fields that can just be stuffed in the pageInfo object
601 $normalFields = array( 'title', 'id', 'redirect', 'restrictions' );
603 $skip = false;
604 $badTitle = false;
606 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
607 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
608 $this->reader->name == 'page' ) {
609 break;
612 $tag = $this->reader->name;
614 if ( $badTitle ) {
615 // The title is invalid, bail out of this page
616 $skip = true;
617 } elseif ( !wfRunHooks( 'ImportHandlePageXMLTag', array( $this,
618 &$pageInfo ) ) ) {
619 // Do nothing
620 } elseif ( in_array( $tag, $normalFields ) ) {
621 $pageInfo[$tag] = $this->nodeContents();
622 if ( $tag == 'title' ) {
623 $title = $this->processTitle( $pageInfo['title'] );
625 if ( !$title ) {
626 $badTitle = true;
627 $skip = true;
630 $this->pageCallback( $title );
631 list( $pageInfo['_title'], $origTitle ) = $title;
633 } elseif ( $tag == 'revision' ) {
634 $this->handleRevision( $pageInfo );
635 } elseif ( $tag == 'upload' ) {
636 $this->handleUpload( $pageInfo );
637 } elseif ( $tag != '#text' ) {
638 $this->warn( "Unhandled page XML tag $tag" );
639 $skip = true;
643 $this->pageOutCallback( $pageInfo['_title'], $origTitle,
644 $pageInfo['revisionCount'],
645 $pageInfo['successfulRevisionCount'],
646 $pageInfo );
650 * @param array $pageInfo
652 private function handleRevision( &$pageInfo ) {
653 $this->debug( "Enter revision handler" );
654 $revisionInfo = array();
656 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'model', 'format', 'text' );
658 $skip = false;
660 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
661 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
662 $this->reader->name == 'revision' ) {
663 break;
666 $tag = $this->reader->name;
668 if ( !wfRunHooks( 'ImportHandleRevisionXMLTag', array(
669 $this, $pageInfo, $revisionInfo
670 ) ) ) {
671 // Do nothing
672 } elseif ( in_array( $tag, $normalFields ) ) {
673 $revisionInfo[$tag] = $this->nodeContents();
674 } elseif ( $tag == 'contributor' ) {
675 $revisionInfo['contributor'] = $this->handleContributor();
676 } elseif ( $tag != '#text' ) {
677 $this->warn( "Unhandled revision XML tag $tag" );
678 $skip = true;
682 $pageInfo['revisionCount']++;
683 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
684 $pageInfo['successfulRevisionCount']++;
689 * @param array $pageInfo
690 * @param array $revisionInfo
691 * @return bool|mixed
693 private function processRevision( $pageInfo, $revisionInfo ) {
694 $revision = new WikiRevision;
696 if ( isset( $revisionInfo['id'] ) ) {
697 $revision->setID( $revisionInfo['id'] );
699 if ( isset( $revisionInfo['model'] ) ) {
700 $revision->setModel( $revisionInfo['model'] );
702 if ( isset( $revisionInfo['format'] ) ) {
703 $revision->setFormat( $revisionInfo['format'] );
705 $revision->setTitle( $pageInfo['_title'] );
707 if ( isset( $revisionInfo['text'] ) ) {
708 $handler = $revision->getContentHandler();
709 $text = $handler->importTransform(
710 $revisionInfo['text'],
711 $revision->getFormat() );
713 $revision->setText( $text );
715 if ( isset( $revisionInfo['timestamp'] ) ) {
716 $revision->setTimestamp( $revisionInfo['timestamp'] );
717 } else {
718 $revision->setTimestamp( wfTimestampNow() );
721 if ( isset( $revisionInfo['comment'] ) ) {
722 $revision->setComment( $revisionInfo['comment'] );
725 if ( isset( $revisionInfo['minor'] ) ) {
726 $revision->setMinor( true );
728 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
729 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
731 if ( isset( $revisionInfo['contributor']['username'] ) ) {
732 $revision->setUserName( $revisionInfo['contributor']['username'] );
734 $revision->setNoUpdates( $this->mNoUpdates );
736 return $this->revisionCallback( $revision );
740 * @param array $pageInfo
741 * @return mixed
743 private function handleUpload( &$pageInfo ) {
744 $this->debug( "Enter upload handler" );
745 $uploadInfo = array();
747 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
748 'src', 'size', 'sha1base36', 'archivename', 'rel' );
750 $skip = false;
752 while ( $skip ? $this->reader->next() : $this->reader->read() ) {
753 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
754 $this->reader->name == 'upload' ) {
755 break;
758 $tag = $this->reader->name;
760 if ( !wfRunHooks( 'ImportHandleUploadXMLTag', array(
761 $this, $pageInfo
762 ) ) ) {
763 // Do nothing
764 } elseif ( in_array( $tag, $normalFields ) ) {
765 $uploadInfo[$tag] = $this->nodeContents();
766 } elseif ( $tag == 'contributor' ) {
767 $uploadInfo['contributor'] = $this->handleContributor();
768 } elseif ( $tag == 'contents' ) {
769 $contents = $this->nodeContents();
770 $encoding = $this->reader->getAttribute( 'encoding' );
771 if ( $encoding === 'base64' ) {
772 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
773 $uploadInfo['isTempSrc'] = true;
775 } elseif ( $tag != '#text' ) {
776 $this->warn( "Unhandled upload XML tag $tag" );
777 $skip = true;
781 if ( $this->mImageBasePath && isset( $uploadInfo['rel'] ) ) {
782 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
783 if ( file_exists( $path ) ) {
784 $uploadInfo['fileSrc'] = $path;
785 $uploadInfo['isTempSrc'] = false;
789 if ( $this->mImportUploads ) {
790 return $this->processUpload( $pageInfo, $uploadInfo );
795 * @param string $contents
796 * @return string
798 private function dumpTemp( $contents ) {
799 $filename = tempnam( wfTempDir(), 'importupload' );
800 file_put_contents( $filename, $contents );
801 return $filename;
805 * @param array $pageInfo
806 * @param array $uploadInfo
807 * @return mixed
809 private function processUpload( $pageInfo, $uploadInfo ) {
810 $revision = new WikiRevision;
811 $text = isset( $uploadInfo['text'] ) ? $uploadInfo['text'] : '';
813 $revision->setTitle( $pageInfo['_title'] );
814 $revision->setID( $pageInfo['id'] );
815 $revision->setTimestamp( $uploadInfo['timestamp'] );
816 $revision->setText( $text );
817 $revision->setFilename( $uploadInfo['filename'] );
818 if ( isset( $uploadInfo['archivename'] ) ) {
819 $revision->setArchiveName( $uploadInfo['archivename'] );
821 $revision->setSrc( $uploadInfo['src'] );
822 if ( isset( $uploadInfo['fileSrc'] ) ) {
823 $revision->setFileSrc( $uploadInfo['fileSrc'],
824 !empty( $uploadInfo['isTempSrc'] ) );
826 if ( isset( $uploadInfo['sha1base36'] ) ) {
827 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
829 $revision->setSize( intval( $uploadInfo['size'] ) );
830 $revision->setComment( $uploadInfo['comment'] );
832 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
833 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
835 if ( isset( $uploadInfo['contributor']['username'] ) ) {
836 $revision->setUserName( $uploadInfo['contributor']['username'] );
838 $revision->setNoUpdates( $this->mNoUpdates );
840 return call_user_func( $this->mUploadCallback, $revision );
844 * @return array
846 private function handleContributor() {
847 $fields = array( 'id', 'ip', 'username' );
848 $info = array();
850 while ( $this->reader->read() ) {
851 if ( $this->reader->nodeType == XmlReader::END_ELEMENT &&
852 $this->reader->name == 'contributor' ) {
853 break;
856 $tag = $this->reader->name;
858 if ( in_array( $tag, $fields ) ) {
859 $info[$tag] = $this->nodeContents();
863 return $info;
867 * @param string $text
868 * @return array|bool
870 private function processTitle( $text ) {
871 global $wgCommandLineMode;
873 $workTitle = $text;
874 $origTitle = Title::newFromText( $workTitle );
876 if ( !is_null( $this->mTargetNamespace ) && !is_null( $origTitle ) ) {
877 # makeTitleSafe, because $origTitle can have a interwiki (different setting of interwiki map)
878 # and than dbKey can begin with a lowercase char
879 $title = Title::makeTitleSafe( $this->mTargetNamespace,
880 $origTitle->getDBkey() );
881 } else {
882 if ( !is_null( $this->mTargetRootPage ) ) {
883 $workTitle = $this->mTargetRootPage . '/' . $workTitle;
885 $title = Title::newFromText( $workTitle );
888 if ( is_null( $title ) ) {
889 # Invalid page title? Ignore the page
890 $this->notice( 'import-error-invalid', $workTitle );
891 return false;
892 } elseif ( $title->isExternal() ) {
893 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
894 return false;
895 } elseif ( !$title->canExist() ) {
896 $this->notice( 'import-error-special', $title->getPrefixedText() );
897 return false;
898 } elseif ( !$title->userCan( 'edit' ) && !$wgCommandLineMode ) {
899 # Do not import if the importing wiki user cannot edit this page
900 $this->notice( 'import-error-edit', $title->getPrefixedText() );
901 return false;
902 } elseif ( !$title->exists() && !$title->userCan( 'create' ) && !$wgCommandLineMode ) {
903 # Do not import if the importing wiki user cannot create this page
904 $this->notice( 'import-error-create', $title->getPrefixedText() );
905 return false;
908 return array( $title, $origTitle );
912 /** This is a horrible hack used to keep source compatibility */
913 class UploadSourceAdapter {
914 /** @var array */
915 private static $sourceRegistrations = array();
917 /** @var string */
918 private $mSource;
920 /** @var string */
921 private $mBuffer;
923 /** @var int */
924 private $mPosition;
927 * @param string $source
928 * @return string
930 static function registerSource( $source ) {
931 $id = wfRandomString();
933 self::$sourceRegistrations[$id] = $source;
935 return $id;
939 * @param string $path
940 * @param string $mode
941 * @param array $options
942 * @param string $opened_path
943 * @return bool
945 function stream_open( $path, $mode, $options, &$opened_path ) {
946 $url = parse_url( $path );
947 $id = $url['host'];
949 if ( !isset( self::$sourceRegistrations[$id] ) ) {
950 return false;
953 $this->mSource = self::$sourceRegistrations[$id];
955 return true;
959 * @param int $count
960 * @return string
962 function stream_read( $count ) {
963 $return = '';
964 $leave = false;
966 while ( !$leave && !$this->mSource->atEnd() &&
967 strlen( $this->mBuffer ) < $count ) {
968 $read = $this->mSource->readChunk();
970 if ( !strlen( $read ) ) {
971 $leave = true;
974 $this->mBuffer .= $read;
977 if ( strlen( $this->mBuffer ) ) {
978 $return = substr( $this->mBuffer, 0, $count );
979 $this->mBuffer = substr( $this->mBuffer, $count );
982 $this->mPosition += strlen( $return );
984 return $return;
988 * @param string $data
989 * @return bool
991 function stream_write( $data ) {
992 return false;
996 * @return mixed
998 function stream_tell() {
999 return $this->mPosition;
1003 * @return bool
1005 function stream_eof() {
1006 return $this->mSource->atEnd();
1010 * @return array
1012 function url_stat() {
1013 $result = array();
1015 $result['dev'] = $result[0] = 0;
1016 $result['ino'] = $result[1] = 0;
1017 $result['mode'] = $result[2] = 0;
1018 $result['nlink'] = $result[3] = 0;
1019 $result['uid'] = $result[4] = 0;
1020 $result['gid'] = $result[5] = 0;
1021 $result['rdev'] = $result[6] = 0;
1022 $result['size'] = $result[7] = 0;
1023 $result['atime'] = $result[8] = 0;
1024 $result['mtime'] = $result[9] = 0;
1025 $result['ctime'] = $result[10] = 0;
1026 $result['blksize'] = $result[11] = 0;
1027 $result['blocks'] = $result[12] = 0;
1029 return $result;
1033 class XMLReader2 extends XMLReader {
1036 * @return bool|string
1038 function nodeContents() {
1039 if ( $this->isEmptyElement ) {
1040 return "";
1042 $buffer = "";
1043 while ( $this->read() ) {
1044 switch ( $this->nodeType ) {
1045 case XmlReader::TEXT:
1046 case XmlReader::SIGNIFICANT_WHITESPACE:
1047 $buffer .= $this->value;
1048 break;
1049 case XmlReader::END_ELEMENT:
1050 return $buffer;
1053 return $this->close();
1058 * @todo document (e.g. one-sentence class description).
1059 * @ingroup SpecialPage
1061 class WikiRevision {
1062 /** @todo Unused? */
1063 private $importer = null;
1065 /** @var Title */
1066 public $title = null;
1068 /** @var int */
1069 private $id = 0;
1071 /** @var string */
1072 public $timestamp = "20010115000000";
1075 * @var int
1076 * @todo Can't find any uses. Public, because that's suspicious. Get clarity. */
1077 public $user = 0;
1079 /** @var string */
1080 public $user_text = "";
1082 /** @var string */
1083 protected $model = null;
1085 /** @var string */
1086 protected $format = null;
1088 /** @var string */
1089 public $text = "";
1091 /** @var int */
1092 protected $size;
1094 /** @var Content */
1095 protected $content = null;
1097 /** @var ContentHandler */
1098 protected $contentHandler = null;
1100 /** @var string */
1101 public $comment = "";
1103 /** @var bool */
1104 protected $minor = false;
1106 /** @var string */
1107 protected $type = "";
1109 /** @var string */
1110 protected $action = "";
1112 /** @var string */
1113 protected $params = "";
1115 /** @var string */
1116 protected $fileSrc = '';
1118 /** @var bool|string */
1119 protected $sha1base36 = false;
1122 * @var bool
1123 * @todo Unused?
1125 private $isTemp = false;
1127 /** @var string */
1128 protected $archiveName = '';
1130 protected $filename;
1132 /** @var mixed */
1133 protected $src;
1135 /** @todo Unused? */
1136 private $fileIsTemp;
1138 /** @var bool */
1139 private $mNoUpdates = false;
1142 * @param Title $title
1143 * @throws MWException
1145 function setTitle( $title ) {
1146 if ( is_object( $title ) ) {
1147 $this->title = $title;
1148 } elseif ( is_null( $title ) ) {
1149 throw new MWException( "WikiRevision given a null title in import. "
1150 . "You may need to adjust \$wgLegalTitleChars." );
1151 } else {
1152 throw new MWException( "WikiRevision given non-object title in import." );
1157 * @param int $id
1159 function setID( $id ) {
1160 $this->id = $id;
1164 * @param string $ts
1166 function setTimestamp( $ts ) {
1167 # 2003-08-05T18:30:02Z
1168 $this->timestamp = wfTimestamp( TS_MW, $ts );
1172 * @param string $user
1174 function setUsername( $user ) {
1175 $this->user_text = $user;
1179 * @param string $ip
1181 function setUserIP( $ip ) {
1182 $this->user_text = $ip;
1186 * @param string $model
1188 function setModel( $model ) {
1189 $this->model = $model;
1193 * @param string $format
1195 function setFormat( $format ) {
1196 $this->format = $format;
1200 * @param string $text
1202 function setText( $text ) {
1203 $this->text = $text;
1207 * @param string $text
1209 function setComment( $text ) {
1210 $this->comment = $text;
1214 * @param bool $minor
1216 function setMinor( $minor ) {
1217 $this->minor = (bool)$minor;
1221 * @param mixed $src
1223 function setSrc( $src ) {
1224 $this->src = $src;
1228 * @param string $src
1229 * @param bool $isTemp
1231 function setFileSrc( $src, $isTemp ) {
1232 $this->fileSrc = $src;
1233 $this->fileIsTemp = $isTemp;
1237 * @param string $sha1base36
1239 function setSha1Base36( $sha1base36 ) {
1240 $this->sha1base36 = $sha1base36;
1244 * @param string $filename
1246 function setFilename( $filename ) {
1247 $this->filename = $filename;
1251 * @param string $archiveName
1253 function setArchiveName( $archiveName ) {
1254 $this->archiveName = $archiveName;
1258 * @param int $size
1260 function setSize( $size ) {
1261 $this->size = intval( $size );
1265 * @param string $type
1267 function setType( $type ) {
1268 $this->type = $type;
1272 * @param string $action
1274 function setAction( $action ) {
1275 $this->action = $action;
1279 * @param array $params
1281 function setParams( $params ) {
1282 $this->params = $params;
1286 * @param bool $noupdates
1288 public function setNoUpdates( $noupdates ) {
1289 $this->mNoUpdates = $noupdates;
1293 * @return Title
1295 function getTitle() {
1296 return $this->title;
1300 * @return int
1302 function getID() {
1303 return $this->id;
1307 * @return string
1309 function getTimestamp() {
1310 return $this->timestamp;
1314 * @return string
1316 function getUser() {
1317 return $this->user_text;
1321 * @return string
1323 * @deprecated Since 1.21, use getContent() instead.
1325 function getText() {
1326 ContentHandler::deprecated( __METHOD__, '1.21' );
1328 return $this->text;
1332 * @return ContentHandler
1334 function getContentHandler() {
1335 if ( is_null( $this->contentHandler ) ) {
1336 $this->contentHandler = ContentHandler::getForModelID( $this->getModel() );
1339 return $this->contentHandler;
1343 * @return Content
1345 function getContent() {
1346 if ( is_null( $this->content ) ) {
1347 $handler = $this->getContentHandler();
1348 $this->content = $handler->unserializeContent( $this->text, $this->getFormat() );
1351 return $this->content;
1355 * @return string
1357 function getModel() {
1358 if ( is_null( $this->model ) ) {
1359 $this->model = $this->getTitle()->getContentModel();
1362 return $this->model;
1366 * @return string
1368 function getFormat() {
1369 if ( is_null( $this->format ) ) {
1370 $this->format = $this->getContentHandler()->getDefaultFormat();
1373 return $this->format;
1377 * @return string
1379 function getComment() {
1380 return $this->comment;
1384 * @return bool
1386 function getMinor() {
1387 return $this->minor;
1391 * @return mixed
1393 function getSrc() {
1394 return $this->src;
1398 * @return bool|string
1400 function getSha1() {
1401 if ( $this->sha1base36 ) {
1402 return wfBaseConvert( $this->sha1base36, 36, 16 );
1404 return false;
1408 * @return string
1410 function getFileSrc() {
1411 return $this->fileSrc;
1415 * @return bool
1417 function isTempSrc() {
1418 return $this->isTemp;
1422 * @return mixed
1424 function getFilename() {
1425 return $this->filename;
1429 * @return string
1431 function getArchiveName() {
1432 return $this->archiveName;
1436 * @return mixed
1438 function getSize() {
1439 return $this->size;
1443 * @return string
1445 function getType() {
1446 return $this->type;
1450 * @return string
1452 function getAction() {
1453 return $this->action;
1457 * @return string
1459 function getParams() {
1460 return $this->params;
1464 * @return bool
1466 function importOldRevision() {
1467 $dbw = wfGetDB( DB_MASTER );
1469 # Sneak a single revision into place
1470 $user = User::newFromName( $this->getUser() );
1471 if ( $user ) {
1472 $userId = intval( $user->getId() );
1473 $userText = $user->getName();
1474 $userObj = $user;
1475 } else {
1476 $userId = 0;
1477 $userText = $this->getUser();
1478 $userObj = new User;
1481 // avoid memory leak...?
1482 $linkCache = LinkCache::singleton();
1483 $linkCache->clear();
1485 $page = WikiPage::factory( $this->title );
1486 if ( !$page->exists() ) {
1487 # must create the page...
1488 $pageId = $page->insertOn( $dbw );
1489 $created = true;
1490 $oldcountable = null;
1491 } else {
1492 $pageId = $page->getId();
1493 $created = false;
1495 $prior = $dbw->selectField( 'revision', '1',
1496 array( 'rev_page' => $pageId,
1497 'rev_timestamp' => $dbw->timestamp( $this->timestamp ),
1498 'rev_user_text' => $userText,
1499 'rev_comment' => $this->getComment() ),
1500 __METHOD__
1502 if ( $prior ) {
1503 // @todo FIXME: This could fail slightly for multiple matches :P
1504 wfDebug( __METHOD__ . ": skipping existing revision for [[" .
1505 $this->title->getPrefixedText() . "]], timestamp " . $this->timestamp . "\n" );
1506 return false;
1508 $oldcountable = $page->isCountable();
1511 # @todo FIXME: Use original rev_id optionally (better for backups)
1512 # Insert the row
1513 $revision = new Revision( array(
1514 'title' => $this->title,
1515 'page' => $pageId,
1516 'content_model' => $this->getModel(),
1517 'content_format' => $this->getFormat(),
1518 //XXX: just set 'content' => $this->getContent()?
1519 'text' => $this->getContent()->serialize( $this->getFormat() ),
1520 'comment' => $this->getComment(),
1521 'user' => $userId,
1522 'user_text' => $userText,
1523 'timestamp' => $this->timestamp,
1524 'minor_edit' => $this->minor,
1525 ) );
1526 $revision->insertOn( $dbw );
1527 $changed = $page->updateIfNewerOn( $dbw, $revision );
1529 if ( $changed !== false && !$this->mNoUpdates ) {
1530 wfDebug( __METHOD__ . ": running updates\n" );
1531 $page->doEditUpdates(
1532 $revision,
1533 $userObj,
1534 array( 'created' => $created, 'oldcountable' => $oldcountable )
1538 return true;
1542 * @return mixed
1544 function importLogItem() {
1545 $dbw = wfGetDB( DB_MASTER );
1546 # @todo FIXME: This will not record autoblocks
1547 if ( !$this->getTitle() ) {
1548 wfDebug( __METHOD__ . ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1549 $this->timestamp . "\n" );
1550 return;
1552 # Check if it exists already
1553 // @todo FIXME: Use original log ID (better for backups)
1554 $prior = $dbw->selectField( 'logging', '1',
1555 array( 'log_type' => $this->getType(),
1556 'log_action' => $this->getAction(),
1557 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
1558 'log_namespace' => $this->getTitle()->getNamespace(),
1559 'log_title' => $this->getTitle()->getDBkey(),
1560 'log_comment' => $this->getComment(),
1561 #'log_user_text' => $this->user_text,
1562 'log_params' => $this->params ),
1563 __METHOD__
1565 // @todo FIXME: This could fail slightly for multiple matches :P
1566 if ( $prior ) {
1567 wfDebug( __METHOD__
1568 . ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp "
1569 . $this->timestamp . "\n" );
1570 return;
1572 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1573 $data = array(
1574 'log_id' => $log_id,
1575 'log_type' => $this->type,
1576 'log_action' => $this->action,
1577 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
1578 'log_user' => User::idFromName( $this->user_text ),
1579 #'log_user_text' => $this->user_text,
1580 'log_namespace' => $this->getTitle()->getNamespace(),
1581 'log_title' => $this->getTitle()->getDBkey(),
1582 'log_comment' => $this->getComment(),
1583 'log_params' => $this->params
1585 $dbw->insert( 'logging', $data, __METHOD__ );
1589 * @return bool
1591 function importUpload() {
1592 # Construct a file
1593 $archiveName = $this->getArchiveName();
1594 if ( $archiveName ) {
1595 wfDebug( __METHOD__ . "Importing archived file as $archiveName\n" );
1596 $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
1597 RepoGroup::singleton()->getLocalRepo(), $archiveName );
1598 } else {
1599 $file = wfLocalFile( $this->getTitle() );
1600 wfDebug( __METHOD__ . 'Importing new file as ' . $file->getName() . "\n" );
1601 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1602 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1603 $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
1604 RepoGroup::singleton()->getLocalRepo(), $archiveName );
1605 wfDebug( __METHOD__ . "File already exists; importing as $archiveName\n" );
1608 if ( !$file ) {
1609 wfDebug( __METHOD__ . ': Bad file for ' . $this->getTitle() . "\n" );
1610 return false;
1613 # Get the file source or download if necessary
1614 $source = $this->getFileSrc();
1615 $flags = $this->isTempSrc() ? File::DELETE_SOURCE : 0;
1616 if ( !$source ) {
1617 $source = $this->downloadSource();
1618 $flags |= File::DELETE_SOURCE;
1620 if ( !$source ) {
1621 wfDebug( __METHOD__ . ": Could not fetch remote file.\n" );
1622 return false;
1624 $sha1 = $this->getSha1();
1625 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1626 if ( $flags & File::DELETE_SOURCE ) {
1627 # Broken file; delete it if it is a temporary file
1628 unlink( $source );
1630 wfDebug( __METHOD__ . ": Corrupt file $source.\n" );
1631 return false;
1634 $user = User::newFromName( $this->user_text );
1636 # Do the actual upload
1637 if ( $archiveName ) {
1638 $status = $file->uploadOld( $source, $archiveName,
1639 $this->getTimestamp(), $this->getComment(), $user, $flags );
1640 } else {
1641 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1642 $flags, false, $this->getTimestamp(), $user );
1645 if ( $status->isGood() ) {
1646 wfDebug( __METHOD__ . ": Successful\n" );
1647 return true;
1648 } else {
1649 wfDebug( __METHOD__ . ': failed: ' . $status->getXml() . "\n" );
1650 return false;
1655 * @return bool|string
1657 function downloadSource() {
1658 global $wgEnableUploads;
1659 if ( !$wgEnableUploads ) {
1660 return false;
1663 $tempo = tempnam( wfTempDir(), 'download' );
1664 $f = fopen( $tempo, 'wb' );
1665 if ( !$f ) {
1666 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1667 return false;
1670 // @todo FIXME!
1671 $src = $this->getSrc();
1672 $data = Http::get( $src );
1673 if ( !$data ) {
1674 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1675 fclose( $f );
1676 unlink( $tempo );
1677 return false;
1680 fwrite( $f, $data );
1681 fclose( $f );
1683 return $tempo;
1689 * @todo document (e.g. one-sentence class description).
1690 * @ingroup SpecialPage
1692 class ImportStringSource {
1693 function __construct( $string ) {
1694 $this->mString = $string;
1695 $this->mRead = false;
1699 * @return bool
1701 function atEnd() {
1702 return $this->mRead;
1706 * @return bool|string
1708 function readChunk() {
1709 if ( $this->atEnd() ) {
1710 return false;
1712 $this->mRead = true;
1713 return $this->mString;
1718 * @todo document (e.g. one-sentence class description).
1719 * @ingroup SpecialPage
1721 class ImportStreamSource {
1722 function __construct( $handle ) {
1723 $this->mHandle = $handle;
1727 * @return bool
1729 function atEnd() {
1730 return feof( $this->mHandle );
1734 * @return string
1736 function readChunk() {
1737 return fread( $this->mHandle, 32768 );
1741 * @param string $filename
1742 * @return Status
1744 static function newFromFile( $filename ) {
1745 wfSuppressWarnings();
1746 $file = fopen( $filename, 'rt' );
1747 wfRestoreWarnings();
1748 if ( !$file ) {
1749 return Status::newFatal( "importcantopen" );
1751 return Status::newGood( new ImportStreamSource( $file ) );
1755 * @param string $fieldname
1756 * @return Status
1758 static function newFromUpload( $fieldname = "xmlimport" ) {
1759 $upload =& $_FILES[$fieldname];
1761 if ( $upload === null || !$upload['name'] ) {
1762 return Status::newFatal( 'importnofile' );
1764 if ( !empty( $upload['error'] ) ) {
1765 switch ( $upload['error'] ) {
1766 case 1:
1767 # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1768 return Status::newFatal( 'importuploaderrorsize' );
1769 case 2:
1770 # The uploaded file exceeds the MAX_FILE_SIZE directive that
1771 # was specified in the HTML form.
1772 return Status::newFatal( 'importuploaderrorsize' );
1773 case 3:
1774 # The uploaded file was only partially uploaded
1775 return Status::newFatal( 'importuploaderrorpartial' );
1776 case 6:
1777 # Missing a temporary folder.
1778 return Status::newFatal( 'importuploaderrortemp' );
1779 # case else: # Currently impossible
1783 $fname = $upload['tmp_name'];
1784 if ( is_uploaded_file( $fname ) ) {
1785 return ImportStreamSource::newFromFile( $fname );
1786 } else {
1787 return Status::newFatal( 'importnofile' );
1792 * @param string $url
1793 * @param string $method
1794 * @return Status
1796 static function newFromURL( $url, $method = 'GET' ) {
1797 wfDebug( __METHOD__ . ": opening $url\n" );
1798 # Use the standard HTTP fetch function; it times out
1799 # quicker and sorts out user-agent problems which might
1800 # otherwise prevent importing from large sites, such
1801 # as the Wikimedia cluster, etc.
1802 $data = Http::request( $method, $url, array( 'followRedirects' => true ) );
1803 if ( $data !== false ) {
1804 $file = tmpfile();
1805 fwrite( $file, $data );
1806 fflush( $file );
1807 fseek( $file, 0 );
1808 return Status::newGood( new ImportStreamSource( $file ) );
1809 } else {
1810 return Status::newFatal( 'importcantopen' );
1815 * @param string $interwiki
1816 * @param string $page
1817 * @param bool $history
1818 * @param bool $templates
1819 * @param int $pageLinkDepth
1820 * @return Status
1822 public static function newFromInterwiki( $interwiki, $page, $history = false,
1823 $templates = false, $pageLinkDepth = 0
1825 if ( $page == '' ) {
1826 return Status::newFatal( 'import-noarticle' );
1828 $link = Title::newFromText( "$interwiki:Special:Export/$page" );
1829 if ( is_null( $link ) || !$link->isExternal() ) {
1830 return Status::newFatal( 'importbadinterwiki' );
1831 } else {
1832 $params = array();
1833 if ( $history ) {
1834 $params['history'] = 1;
1836 if ( $templates ) {
1837 $params['templates'] = 1;
1839 if ( $pageLinkDepth ) {
1840 $params['pagelink-depth'] = $pageLinkDepth;
1842 $url = $link->getFullURL( $params );
1843 # For interwikis, use POST to avoid redirects.
1844 return ImportStreamSource::newFromURL( $url, "POST" );