summaryrefslogtreecommitdiff
path: root/www/wiki/includes/import
diff options
context:
space:
mode:
authorYaco <franco@reevo.org>2020-06-04 11:01:00 -0300
committerYaco <franco@reevo.org>2020-06-04 11:01:00 -0300
commitfc7369835258467bf97eb64f184b93691f9a9fd5 (patch)
treedaabd60089d2dd76d9f5fb416b005fbe159c799d /www/wiki/includes/import
first commit
Diffstat (limited to 'www/wiki/includes/import')
-rw-r--r--www/wiki/includes/import/ImportSource.php51
-rw-r--r--www/wiki/includes/import/ImportStreamSource.php183
-rw-r--r--www/wiki/includes/import/ImportStringSource.php57
-rw-r--r--www/wiki/includes/import/ImportableOldRevision.php68
-rw-r--r--www/wiki/includes/import/ImportableOldRevisionImporter.php145
-rw-r--r--www/wiki/includes/import/ImportableUploadRevision.php68
-rw-r--r--www/wiki/includes/import/ImportableUploadRevisionImporter.php155
-rw-r--r--www/wiki/includes/import/OldRevisionImporter.php17
-rw-r--r--www/wiki/includes/import/UploadRevisionImporter.php18
-rw-r--r--www/wiki/includes/import/UploadSourceAdapter.php149
-rw-r--r--www/wiki/includes/import/WikiImporter.php1120
-rw-r--r--www/wiki/includes/import/WikiRevision.php676
12 files changed, 2707 insertions, 0 deletions
diff --git a/www/wiki/includes/import/ImportSource.php b/www/wiki/includes/import/ImportSource.php
new file mode 100644
index 00000000..75d20b4e
--- /dev/null
+++ b/www/wiki/includes/import/ImportSource.php
@@ -0,0 +1,51 @@
+<?php
+/**
+ * Source interface for XML import.
+ *
+ * Copyright © 2003,2005 Brion Vibber <brion@pobox.com>
+ * https://www.mediawiki.org/
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
+ *
+ * @file
+ * @ingroup SpecialPage
+ */
+
+/**
+ * Source interface for XML import.
+ *
+ * @ingroup SpecialPage
+ */
+interface ImportSource {
+
+ /**
+ * Indicates whether the end of the input has been reached.
+ * Will return true after a finite number of calls to readChunk.
+ *
+ * @return bool true if there is no more input, false otherwise.
+ */
+ function atEnd();
+
+ /**
+ * Return a chunk of the input, as a (possibly empty) string.
+ * When the end of input is reached, readChunk() returns false.
+ * If atEnd() returns false, readChunk() will return a string.
+ * If atEnd() returns true, readChunk() will return false.
+ *
+ * @return bool|string
+ */
+ function readChunk();
+}
diff --git a/www/wiki/includes/import/ImportStreamSource.php b/www/wiki/includes/import/ImportStreamSource.php
new file mode 100644
index 00000000..cf382e48
--- /dev/null
+++ b/www/wiki/includes/import/ImportStreamSource.php
@@ -0,0 +1,183 @@
+<?php
+/**
+ * MediaWiki page data importer.
+ *
+ * Copyright © 2003,2005 Brion Vibber <brion@pobox.com>
+ * https://www.mediawiki.org/
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
+ *
+ * @file
+ * @ingroup SpecialPage
+ */
+use MediaWiki\MediaWikiServices;
+
+/**
+ * Imports a XML dump from a file (either from file upload, files on disk, or HTTP)
+ * @ingroup SpecialPage
+ */
+class ImportStreamSource implements ImportSource {
+ function __construct( $handle ) {
+ $this->mHandle = $handle;
+ }
+
+ /**
+ * @return bool
+ */
+ function atEnd() {
+ return feof( $this->mHandle );
+ }
+
+ /**
+ * @return string
+ */
+ function readChunk() {
+ return fread( $this->mHandle, 32768 );
+ }
+
+ /**
+ * @param string $filename
+ * @return Status
+ */
+ static function newFromFile( $filename ) {
+ Wikimedia\suppressWarnings();
+ $file = fopen( $filename, 'rt' );
+ Wikimedia\restoreWarnings();
+ if ( !$file ) {
+ return Status::newFatal( "importcantopen" );
+ }
+ return Status::newGood( new ImportStreamSource( $file ) );
+ }
+
+ /**
+ * @param string $fieldname
+ * @return Status
+ */
+ static function newFromUpload( $fieldname = "xmlimport" ) {
+ $upload =& $_FILES[$fieldname];
+
+ if ( $upload === null || !$upload['name'] ) {
+ return Status::newFatal( 'importnofile' );
+ }
+ if ( !empty( $upload['error'] ) ) {
+ switch ( $upload['error'] ) {
+ case 1:
+ # The uploaded file exceeds the upload_max_filesize directive in php.ini.
+ return Status::newFatal( 'importuploaderrorsize' );
+ case 2:
+ # The uploaded file exceeds the MAX_FILE_SIZE directive that
+ # was specified in the HTML form.
+ return Status::newFatal( 'importuploaderrorsize' );
+ case 3:
+ # The uploaded file was only partially uploaded
+ return Status::newFatal( 'importuploaderrorpartial' );
+ case 6:
+ # Missing a temporary folder.
+ return Status::newFatal( 'importuploaderrortemp' );
+ # case else: # Currently impossible
+ }
+
+ }
+ $fname = $upload['tmp_name'];
+ if ( is_uploaded_file( $fname ) ) {
+ return self::newFromFile( $fname );
+ } else {
+ return Status::newFatal( 'importnofile' );
+ }
+ }
+
+ /**
+ * @param string $url
+ * @param string $method
+ * @return Status
+ */
+ static function newFromURL( $url, $method = 'GET' ) {
+ global $wgHTTPImportTimeout;
+ wfDebug( __METHOD__ . ": opening $url\n" );
+ # Use the standard HTTP fetch function; it times out
+ # quicker and sorts out user-agent problems which might
+ # otherwise prevent importing from large sites, such
+ # as the Wikimedia cluster, etc.
+ $data = Http::request(
+ $method,
+ $url,
+ [
+ 'followRedirects' => true,
+ 'timeout' => $wgHTTPImportTimeout
+ ],
+ __METHOD__
+ );
+ if ( $data !== false ) {
+ $file = tmpfile();
+ fwrite( $file, $data );
+ fflush( $file );
+ fseek( $file, 0 );
+ return Status::newGood( new ImportStreamSource( $file ) );
+ } else {
+ return Status::newFatal( 'importcantopen' );
+ }
+ }
+
+ /**
+ * @param string $interwiki
+ * @param string $page
+ * @param bool $history
+ * @param bool $templates
+ * @param int $pageLinkDepth
+ * @return Status
+ */
+ public static function newFromInterwiki( $interwiki, $page, $history = false,
+ $templates = false, $pageLinkDepth = 0
+ ) {
+ if ( $page == '' ) {
+ return Status::newFatal( 'import-noarticle' );
+ }
+
+ # Look up the first interwiki prefix, and let the foreign site handle
+ # subsequent interwiki prefixes
+ $firstIwPrefix = strtok( $interwiki, ':' );
+ $interwikiLookup = MediaWikiServices::getInstance()->getInterwikiLookup();
+ $firstIw = $interwikiLookup->fetch( $firstIwPrefix );
+ if ( !$firstIw ) {
+ return Status::newFatal( 'importbadinterwiki' );
+ }
+
+ $additionalIwPrefixes = strtok( '' );
+ if ( $additionalIwPrefixes ) {
+ $additionalIwPrefixes .= ':';
+ }
+ # Have to do a DB-key replacement ourselves; otherwise spaces get
+ # URL-encoded to +, which is wrong in this case. Similar to logic in
+ # Title::getLocalURL
+ $link = $firstIw->getURL( strtr( "${additionalIwPrefixes}Special:Export/$page",
+ ' ', '_' ) );
+
+ $params = [];
+ if ( $history ) {
+ $params['history'] = 1;
+ }
+ if ( $templates ) {
+ $params['templates'] = 1;
+ }
+ if ( $pageLinkDepth ) {
+ $params['pagelink-depth'] = $pageLinkDepth;
+ }
+
+ $url = wfAppendQuery( $link, $params );
+ # For interwikis, use POST to avoid redirects.
+ return self::newFromURL( $url, "POST" );
+ }
+}
diff --git a/www/wiki/includes/import/ImportStringSource.php b/www/wiki/includes/import/ImportStringSource.php
new file mode 100644
index 00000000..85983b1a
--- /dev/null
+++ b/www/wiki/includes/import/ImportStringSource.php
@@ -0,0 +1,57 @@
+<?php
+/**
+ * MediaWiki page data importer.
+ *
+ * Copyright © 2003,2005 Brion Vibber <brion@pobox.com>
+ * https://www.mediawiki.org/
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
+ *
+ * @file
+ * @ingroup SpecialPage
+ */
+
+/**
+ * Used for importing XML dumps where the content of the dump is in a string.
+ * This class is ineffecient, and should only be used for small dumps.
+ * For larger dumps, ImportStreamSource should be used instead.
+ *
+ * @ingroup SpecialPage
+ */
+class ImportStringSource implements ImportSource {
+ function __construct( $string ) {
+ $this->mString = $string;
+ $this->mRead = false;
+ }
+
+ /**
+ * @return bool
+ */
+ function atEnd() {
+ return $this->mRead;
+ }
+
+ /**
+ * @return bool|string
+ */
+ function readChunk() {
+ if ( $this->atEnd() ) {
+ return false;
+ }
+ $this->mRead = true;
+ return $this->mString;
+ }
+}
diff --git a/www/wiki/includes/import/ImportableOldRevision.php b/www/wiki/includes/import/ImportableOldRevision.php
new file mode 100644
index 00000000..6d1e2426
--- /dev/null
+++ b/www/wiki/includes/import/ImportableOldRevision.php
@@ -0,0 +1,68 @@
+<?php
+
+/**
+ * @since 1.31
+ */
+interface ImportableOldRevision {
+
+ /**
+ * @since 1.31
+ * @return User
+ */
+ public function getUserObj();
+
+ /**
+ * @since 1.31
+ * @return string
+ */
+ public function getUser();
+
+ /**
+ * @since 1.31
+ * @return Title
+ */
+ public function getTitle();
+
+ /**
+ * @since 1.31
+ * @return string
+ */
+ public function getTimestamp();
+
+ /**
+ * @since 1.31
+ * @return string
+ */
+ public function getComment();
+
+ /**
+ * @since 1.31
+ * @return string
+ */
+ public function getModel();
+
+ /**
+ * @since 1.31
+ * @return string
+ */
+ public function getFormat();
+
+ /**
+ * @since 1.31
+ * @return Content
+ */
+ public function getContent();
+
+ /**
+ * @since 1.31
+ * @return bool
+ */
+ public function getMinor();
+
+ /**
+ * @since 1.31
+ * @return bool|string
+ */
+ public function getSha1Base36();
+
+}
diff --git a/www/wiki/includes/import/ImportableOldRevisionImporter.php b/www/wiki/includes/import/ImportableOldRevisionImporter.php
new file mode 100644
index 00000000..066a3eac
--- /dev/null
+++ b/www/wiki/includes/import/ImportableOldRevisionImporter.php
@@ -0,0 +1,145 @@
+<?php
+
+use Psr\Log\LoggerInterface;
+use Wikimedia\Rdbms\LoadBalancer;
+
+/**
+ * @since 1.31
+ */
+class ImportableOldRevisionImporter implements OldRevisionImporter {
+
+ /**
+ * @var LoggerInterface
+ */
+ private $logger;
+
+ /**
+ * @var bool
+ */
+ private $doUpdates;
+
+ /**
+ * @var LoadBalancer
+ */
+ private $loadBalancer;
+
+ /**
+ * @param bool $doUpdates
+ * @param LoggerInterface $logger
+ * @param LoadBalancer $loadBalancer
+ */
+ public function __construct(
+ $doUpdates,
+ LoggerInterface $logger,
+ LoadBalancer $loadBalancer
+ ) {
+ $this->doUpdates = $doUpdates;
+ $this->logger = $logger;
+ $this->loadBalancer = $loadBalancer;
+ }
+
+ public function import( ImportableOldRevision $importableRevision, $doUpdates = true ) {
+ $dbw = $this->loadBalancer->getConnectionRef( DB_MASTER );
+
+ # Sneak a single revision into place
+ $user = $importableRevision->getUserObj() ?: User::newFromName( $importableRevision->getUser() );
+ if ( $user ) {
+ $userId = intval( $user->getId() );
+ $userText = $user->getName();
+ } else {
+ $userId = 0;
+ $userText = $importableRevision->getUser();
+ $user = new User;
+ }
+
+ // avoid memory leak...?
+ Title::clearCaches();
+
+ $page = WikiPage::factory( $importableRevision->getTitle() );
+ $page->loadPageData( 'fromdbmaster' );
+ if ( !$page->exists() ) {
+ // must create the page...
+ $pageId = $page->insertOn( $dbw );
+ $created = true;
+ $oldcountable = null;
+ } else {
+ $pageId = $page->getId();
+ $created = false;
+
+ // Note: sha1 has been in XML dumps since 2012. If you have an
+ // older dump, the duplicate detection here won't work.
+ if ( $importableRevision->getSha1Base36() !== false ) {
+ $prior = $dbw->selectField( 'revision', '1',
+ [ 'rev_page' => $pageId,
+ 'rev_timestamp' => $dbw->timestamp( $importableRevision->getTimestamp() ),
+ 'rev_sha1' => $importableRevision->getSha1Base36() ],
+ __METHOD__
+ );
+ if ( $prior ) {
+ // @todo FIXME: This could fail slightly for multiple matches :P
+ $this->logger->debug( __METHOD__ . ": skipping existing revision for [[" .
+ $importableRevision->getTitle()->getPrefixedText() . "]], timestamp " .
+ $importableRevision->getTimestamp() . "\n" );
+ return false;
+ }
+ }
+ }
+
+ if ( !$pageId ) {
+ // This seems to happen if two clients simultaneously try to import the
+ // same page
+ $this->logger->debug( __METHOD__ . ': got invalid $pageId when importing revision of [[' .
+ $importableRevision->getTitle()->getPrefixedText() . ']], timestamp ' .
+ $importableRevision->getTimestamp() . "\n" );
+ return false;
+ }
+
+ // Select previous version to make size diffs correct
+ // @todo This assumes that multiple revisions of the same page are imported
+ // in order from oldest to newest.
+ $prevId = $dbw->selectField( 'revision', 'rev_id',
+ [
+ 'rev_page' => $pageId,
+ 'rev_timestamp <= ' . $dbw->addQuotes( $dbw->timestamp( $importableRevision->getTimestamp() ) ),
+ ],
+ __METHOD__,
+ [ 'ORDER BY' => [
+ 'rev_timestamp DESC',
+ 'rev_id DESC', // timestamp is not unique per page
+ ]
+ ]
+ );
+
+ # @todo FIXME: Use original rev_id optionally (better for backups)
+ # Insert the row
+ $revision = new Revision( [
+ 'title' => $importableRevision->getTitle(),
+ 'page' => $pageId,
+ 'content_model' => $importableRevision->getModel(),
+ 'content_format' => $importableRevision->getFormat(),
+ // XXX: just set 'content' => $wikiRevision->getContent()?
+ 'text' => $importableRevision->getContent()->serialize( $importableRevision->getFormat() ),
+ 'comment' => $importableRevision->getComment(),
+ 'user' => $userId,
+ 'user_text' => $userText,
+ 'timestamp' => $importableRevision->getTimestamp(),
+ 'minor_edit' => $importableRevision->getMinor(),
+ 'parent_id' => $prevId,
+ ] );
+ $revision->insertOn( $dbw );
+ $changed = $page->updateIfNewerOn( $dbw, $revision );
+
+ if ( $changed !== false && $this->doUpdates ) {
+ $this->logger->debug( __METHOD__ . ": running updates\n" );
+ // countable/oldcountable stuff is handled in WikiImporter::finishImportPage
+ $page->doEditUpdates(
+ $revision,
+ $user,
+ [ 'created' => $created, 'oldcountable' => 'no-change' ]
+ );
+ }
+
+ return true;
+ }
+
+}
diff --git a/www/wiki/includes/import/ImportableUploadRevision.php b/www/wiki/includes/import/ImportableUploadRevision.php
new file mode 100644
index 00000000..3f60112a
--- /dev/null
+++ b/www/wiki/includes/import/ImportableUploadRevision.php
@@ -0,0 +1,68 @@
+<?php
+
+/**
+ * @since 1.31
+ */
+interface ImportableUploadRevision {
+
+ /**
+ * @since 1.31
+ * @return string Archive name of a revision if archived.
+ */
+ public function getArchiveName();
+
+ /**
+ * @since 1.31
+ * @return Title
+ */
+ public function getTitle();
+
+ /**
+ * @since 1.31
+ * @return string
+ */
+ public function getTimestamp();
+
+ /**
+ * @since 1.31
+ * @return string|null HTTP source of revision to be used for downloading.
+ */
+ public function getSrc();
+
+ /**
+ * @since 1.31
+ * @return string Local file source of the revision.
+ */
+ public function getFileSrc();
+
+ /**
+ * @since 1.31
+ * @return bool Is the return of getFileSrc only temporary?
+ */
+ public function isTempSrc();
+
+ /**
+ * @since 1.31
+ * @return string|bool sha1 of the revision, false if not set or errors occour.
+ */
+ public function getSha1();
+
+ /**
+ * @since 1.31
+ * @return User
+ */
+ public function getUserObj();
+
+ /**
+ * @since 1.31
+ * @return string The username of the user that created this revision
+ */
+ public function getUser();
+
+ /**
+ * @since 1.31
+ * @return string
+ */
+ public function getComment();
+
+}
diff --git a/www/wiki/includes/import/ImportableUploadRevisionImporter.php b/www/wiki/includes/import/ImportableUploadRevisionImporter.php
new file mode 100644
index 00000000..515cdd5e
--- /dev/null
+++ b/www/wiki/includes/import/ImportableUploadRevisionImporter.php
@@ -0,0 +1,155 @@
+<?php
+
+use Psr\Log\LoggerInterface;
+
+/**
+ * @since 1.31
+ */
+class ImportableUploadRevisionImporter implements UploadRevisionImporter {
+
+ /**
+ * @var LoggerInterface
+ */
+ private $logger;
+
+ /**
+ * @var bool
+ */
+ private $enableUploads;
+
+ /**
+ * @param bool $enableUploads
+ * @param LoggerInterface $logger
+ */
+ public function __construct(
+ $enableUploads,
+ LoggerInterface $logger
+ ) {
+ $this->enableUploads = $enableUploads;
+ $this->logger = $logger;
+ }
+
+ /**
+ * @return StatusValue
+ */
+ private function newNotOkStatus() {
+ $statusValue = new StatusValue();
+ $statusValue->setOK( false );
+ return $statusValue;
+ }
+
+ public function import( ImportableUploadRevision $importableRevision ) {
+ # Construct a file
+ $archiveName = $importableRevision->getArchiveName();
+ if ( $archiveName ) {
+ $this->logger->debug( __METHOD__ . "Importing archived file as $archiveName\n" );
+ $file = OldLocalFile::newFromArchiveName( $importableRevision->getTitle(),
+ RepoGroup::singleton()->getLocalRepo(), $archiveName );
+ } else {
+ $file = wfLocalFile( $importableRevision->getTitle() );
+ $file->load( File::READ_LATEST );
+ $this->logger->debug( __METHOD__ . 'Importing new file as ' . $file->getName() . "\n" );
+ if ( $file->exists() && $file->getTimestamp() > $importableRevision->getTimestamp() ) {
+ $archiveName = $importableRevision->getTimestamp() . '!' . $file->getName();
+ $file = OldLocalFile::newFromArchiveName( $importableRevision->getTitle(),
+ RepoGroup::singleton()->getLocalRepo(), $archiveName );
+ $this->logger->debug( __METHOD__ . "File already exists; importing as $archiveName\n" );
+ }
+ }
+ if ( !$file ) {
+ $this->logger->debug( __METHOD__ . ': Bad file for ' . $importableRevision->getTitle() . "\n" );
+ return $this->newNotOkStatus();
+ }
+
+ # Get the file source or download if necessary
+ $source = $importableRevision->getFileSrc();
+ $autoDeleteSource = $importableRevision->isTempSrc();
+ if ( !strlen( $source ) ) {
+ $source = $this->downloadSource( $importableRevision );
+ $autoDeleteSource = true;
+ }
+ if ( !strlen( $source ) ) {
+ $this->logger->debug( __METHOD__ . ": Could not fetch remote file.\n" );
+ return $this->newNotOkStatus();
+ }
+
+ $tmpFile = new TempFSFile( $source );
+ if ( $autoDeleteSource ) {
+ $tmpFile->autocollect();
+ }
+
+ $sha1File = ltrim( sha1_file( $source ), '0' );
+ $sha1 = $importableRevision->getSha1();
+ if ( $sha1 && ( $sha1 !== $sha1File ) ) {
+ $this->logger->debug( __METHOD__ . ": Corrupt file $source.\n" );
+ return $this->newNotOkStatus();
+ }
+
+ $user = $importableRevision->getUserObj()
+ ?: User::newFromName( $importableRevision->getUser(), false );
+
+ # Do the actual upload
+ if ( $archiveName ) {
+ $status = $file->uploadOld( $source, $archiveName,
+ $importableRevision->getTimestamp(), $importableRevision->getComment(), $user );
+ } else {
+ $flags = 0;
+ $status = $file->upload(
+ $source,
+ $importableRevision->getComment(),
+ $importableRevision->getComment(),
+ $flags,
+ false,
+ $importableRevision->getTimestamp(),
+ $user
+ );
+ }
+
+ if ( $status->isGood() ) {
+ $this->logger->debug( __METHOD__ . ": Successful\n" );
+ } else {
+ $this->logger->debug( __METHOD__ . ': failed: ' . $status->getHTML() . "\n" );
+ }
+
+ return $status;
+ }
+
+ /**
+ * @deprecated DO NOT CALL ME.
+ * This method was introduced when factoring UploadImporter out of WikiRevision.
+ * It only has 1 use by the deprecated downloadSource method in WikiRevision.
+ * Do not use this in new code.
+ *
+ * @param ImportableUploadRevision $wikiRevision
+ *
+ * @return bool|string
+ */
+ public function downloadSource( ImportableUploadRevision $wikiRevision ) {
+ if ( !$this->enableUploads ) {
+ return false;
+ }
+
+ $tempo = tempnam( wfTempDir(), 'download' );
+ $f = fopen( $tempo, 'wb' );
+ if ( !$f ) {
+ $this->logger->debug( "IMPORT: couldn't write to temp file $tempo\n" );
+ return false;
+ }
+
+ // @todo FIXME!
+ $src = $wikiRevision->getSrc();
+ $data = Http::get( $src, [], __METHOD__ );
+ if ( !$data ) {
+ $this->logger->debug( "IMPORT: couldn't fetch source $src\n" );
+ fclose( $f );
+ unlink( $tempo );
+ return false;
+ }
+
+ fwrite( $f, $data );
+ fclose( $f );
+
+ return $tempo;
+ }
+
+}
diff --git a/www/wiki/includes/import/OldRevisionImporter.php b/www/wiki/includes/import/OldRevisionImporter.php
new file mode 100644
index 00000000..72af43b9
--- /dev/null
+++ b/www/wiki/includes/import/OldRevisionImporter.php
@@ -0,0 +1,17 @@
+<?php
+
+/**
+ * @since 1.31
+ */
+interface OldRevisionImporter {
+
+ /**
+ * @since 1.31
+ *
+ * @param ImportableOldRevision $importableRevision
+ *
+ * @return bool Success
+ */
+ public function import( ImportableOldRevision $importableRevision );
+
+}
diff --git a/www/wiki/includes/import/UploadRevisionImporter.php b/www/wiki/includes/import/UploadRevisionImporter.php
new file mode 100644
index 00000000..966fc11a
--- /dev/null
+++ b/www/wiki/includes/import/UploadRevisionImporter.php
@@ -0,0 +1,18 @@
+<?php
+
+/**
+ * @since 1.31
+ */
+interface UploadRevisionImporter {
+
+ /**
+ * @since 1.31
+ *
+ * @param ImportableUploadRevision $importableUploadRevision
+ *
+ * @return StatusValue On success, the value member contains the
+ * archive name, or an empty string if it was a new file.
+ */
+ public function import( ImportableUploadRevision $importableUploadRevision );
+
+}
diff --git a/www/wiki/includes/import/UploadSourceAdapter.php b/www/wiki/includes/import/UploadSourceAdapter.php
new file mode 100644
index 00000000..ccacbe4a
--- /dev/null
+++ b/www/wiki/includes/import/UploadSourceAdapter.php
@@ -0,0 +1,149 @@
+<?php
+/**
+ * MediaWiki page data importer.
+ *
+ * Copyright © 2003,2005 Brion Vibber <brion@pobox.com>
+ * https://www.mediawiki.org/
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
+ *
+ * @file
+ * @ingroup SpecialPage
+ */
+
+/**
+ * This is a horrible hack used to keep source compatibility.
+ * @ingroup SpecialPage
+ */
+class UploadSourceAdapter {
+ /** @var array */
+ public static $sourceRegistrations = [];
+
+ /** @var string */
+ private $mSource;
+
+ /** @var string */
+ private $mBuffer;
+
+ /** @var int */
+ private $mPosition;
+
+ /**
+ * @param ImportSource $source
+ * @return string
+ */
+ static function registerSource( ImportSource $source ) {
+ $id = wfRandomString();
+
+ self::$sourceRegistrations[$id] = $source;
+
+ return $id;
+ }
+
+ /**
+ * @param string $path
+ * @param string $mode
+ * @param array $options
+ * @param string &$opened_path
+ * @return bool
+ */
+ function stream_open( $path, $mode, $options, &$opened_path ) {
+ $url = parse_url( $path );
+ $id = $url['host'];
+
+ if ( !isset( self::$sourceRegistrations[$id] ) ) {
+ return false;
+ }
+
+ $this->mSource = self::$sourceRegistrations[$id];
+
+ return true;
+ }
+
+ /**
+ * @param int $count
+ * @return string
+ */
+ function stream_read( $count ) {
+ $return = '';
+ $leave = false;
+
+ while ( !$leave && !$this->mSource->atEnd() &&
+ strlen( $this->mBuffer ) < $count ) {
+ $read = $this->mSource->readChunk();
+
+ if ( !strlen( $read ) ) {
+ $leave = true;
+ }
+
+ $this->mBuffer .= $read;
+ }
+
+ if ( strlen( $this->mBuffer ) ) {
+ $return = substr( $this->mBuffer, 0, $count );
+ $this->mBuffer = substr( $this->mBuffer, $count );
+ }
+
+ $this->mPosition += strlen( $return );
+
+ return $return;
+ }
+
+ /**
+ * @param string $data
+ * @return bool
+ */
+ function stream_write( $data ) {
+ return false;
+ }
+
+ /**
+ * @return mixed
+ */
+ function stream_tell() {
+ return $this->mPosition;
+ }
+
+ /**
+ * @return bool
+ */
+ function stream_eof() {
+ return $this->mSource->atEnd();
+ }
+
+ /**
+ * @return array
+ */
+ function url_stat() {
+ $result = [];
+
+ $result['dev'] = $result[0] = 0;
+ $result['ino'] = $result[1] = 0;
+ $result['mode'] = $result[2] = 0;
+ $result['nlink'] = $result[3] = 0;
+ $result['uid'] = $result[4] = 0;
+ $result['gid'] = $result[5] = 0;
+ $result['rdev'] = $result[6] = 0;
+ $result['size'] = $result[7] = 0;
+ $result['atime'] = $result[8] = 0;
+ $result['mtime'] = $result[9] = 0;
+ $result['ctime'] = $result[10] = 0;
+ $result['blksize'] = $result[11] = 0;
+ $result['blocks'] = $result[12] = 0;
+
+ return $result;
+ }
+}
diff --git a/www/wiki/includes/import/WikiImporter.php b/www/wiki/includes/import/WikiImporter.php
new file mode 100644
index 00000000..8991f5ef
--- /dev/null
+++ b/www/wiki/includes/import/WikiImporter.php
@@ -0,0 +1,1120 @@
+<?php
+/**
+ * MediaWiki page data importer.
+ *
+ * Copyright © 2003,2005 Brion Vibber <brion@pobox.com>
+ * https://www.mediawiki.org/
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
+ *
+ * @file
+ * @ingroup SpecialPage
+ */
+
+/**
+ * XML file reader for the page data importer.
+ *
+ * implements Special:Import
+ * @ingroup SpecialPage
+ */
+class WikiImporter {
+ private $reader = null;
+ private $foreignNamespaces = null;
+ private $mLogItemCallback, $mUploadCallback, $mRevisionCallback, $mPageCallback;
+ private $mSiteInfoCallback, $mPageOutCallback;
+ private $mNoticeCallback, $mDebug;
+ private $mImportUploads, $mImageBasePath;
+ private $mNoUpdates = false;
+ private $pageOffset = 0;
+ /** @var Config */
+ private $config;
+ /** @var ImportTitleFactory */
+ private $importTitleFactory;
+ /** @var array */
+ private $countableCache = [];
+ /** @var bool */
+ private $disableStatisticsUpdate = false;
+ /** @var ExternalUserNames */
+ private $externalUserNames;
+
+ /**
+ * Creates an ImportXMLReader drawing from the source provided
+ * @param ImportSource $source
+ * @param Config $config
+ * @throws Exception
+ */
+ function __construct( ImportSource $source, Config $config ) {
+ if ( !class_exists( 'XMLReader' ) ) {
+ throw new Exception( 'Import requires PHP to have been compiled with libxml support' );
+ }
+
+ $this->reader = new XMLReader();
+ $this->config = $config;
+
+ if ( !in_array( 'uploadsource', stream_get_wrappers() ) ) {
+ stream_wrapper_register( 'uploadsource', UploadSourceAdapter::class );
+ }
+ $id = UploadSourceAdapter::registerSource( $source );
+
+ // Enable the entity loader, as it is needed for loading external URLs via
+ // XMLReader::open (T86036)
+ $oldDisable = libxml_disable_entity_loader( false );
+ if ( defined( 'LIBXML_PARSEHUGE' ) ) {
+ $status = $this->reader->open( "uploadsource://$id", null, LIBXML_PARSEHUGE );
+ } else {
+ $status = $this->reader->open( "uploadsource://$id" );
+ }
+ if ( !$status ) {
+ $error = libxml_get_last_error();
+ libxml_disable_entity_loader( $oldDisable );
+ throw new MWException( 'Encountered an internal error while initializing WikiImporter object: ' .
+ $error->message );
+ }
+ libxml_disable_entity_loader( $oldDisable );
+
+ // Default callbacks
+ $this->setPageCallback( [ $this, 'beforeImportPage' ] );
+ $this->setRevisionCallback( [ $this, "importRevision" ] );
+ $this->setUploadCallback( [ $this, 'importUpload' ] );
+ $this->setLogItemCallback( [ $this, 'importLogItem' ] );
+ $this->setPageOutCallback( [ $this, 'finishImportPage' ] );
+
+ $this->importTitleFactory = new NaiveImportTitleFactory();
+ $this->externalUserNames = new ExternalUserNames( 'imported', false );
+ }
+
+ /**
+ * @return null|XMLReader
+ */
+ public function getReader() {
+ return $this->reader;
+ }
+
+ public function throwXmlError( $err ) {
+ $this->debug( "FAILURE: $err" );
+ wfDebug( "WikiImporter XML error: $err\n" );
+ }
+
+ public function debug( $data ) {
+ if ( $this->mDebug ) {
+ wfDebug( "IMPORT: $data\n" );
+ }
+ }
+
+ public function warn( $data ) {
+ wfDebug( "IMPORT: $data\n" );
+ }
+
+ public function notice( $msg /*, $param, ...*/ ) {
+ $params = func_get_args();
+ array_shift( $params );
+
+ if ( is_callable( $this->mNoticeCallback ) ) {
+ call_user_func( $this->mNoticeCallback, $msg, $params );
+ } else { # No ImportReporter -> CLI
+ // T177997: the command line importers should call setNoticeCallback()
+ // for their own custom callback to echo the notice
+ wfDebug( wfMessage( $msg, $params )->text() . "\n" );
+ }
+ }
+
+ /**
+ * Set debug mode...
+ * @param bool $debug
+ */
+ function setDebug( $debug ) {
+ $this->mDebug = $debug;
+ }
+
+ /**
+ * Set 'no updates' mode. In this mode, the link tables will not be updated by the importer
+ * @param bool $noupdates
+ */
+ function setNoUpdates( $noupdates ) {
+ $this->mNoUpdates = $noupdates;
+ }
+
+ /**
+ * Sets 'pageOffset' value. So it will skip the first n-1 pages
+ * and start from the nth page. It's 1-based indexing.
+ * @param int $nthPage
+ * @since 1.29
+ */
+ function setPageOffset( $nthPage ) {
+ $this->pageOffset = $nthPage;
+ }
+
+ /**
+ * Set a callback that displays notice messages
+ *
+ * @param callable $callback
+ * @return callable
+ */
+ public function setNoticeCallback( $callback ) {
+ return wfSetVar( $this->mNoticeCallback, $callback );
+ }
+
+ /**
+ * Sets the action to perform as each new page in the stream is reached.
+ * @param callable $callback
+ * @return callable
+ */
+ public function setPageCallback( $callback ) {
+ $previous = $this->mPageCallback;
+ $this->mPageCallback = $callback;
+ return $previous;
+ }
+
+ /**
+ * Sets the action to perform as each page in the stream is completed.
+ * Callback accepts the page title (as a Title object), a second object
+ * with the original title form (in case it's been overridden into a
+ * local namespace), and a count of revisions.
+ *
+ * @param callable $callback
+ * @return callable
+ */
+ public function setPageOutCallback( $callback ) {
+ $previous = $this->mPageOutCallback;
+ $this->mPageOutCallback = $callback;
+ return $previous;
+ }
+
+ /**
+ * Sets the action to perform as each page revision is reached.
+ * @param callable $callback
+ * @return callable
+ */
+ public function setRevisionCallback( $callback ) {
+ $previous = $this->mRevisionCallback;
+ $this->mRevisionCallback = $callback;
+ return $previous;
+ }
+
+ /**
+ * Sets the action to perform as each file upload version is reached.
+ * @param callable $callback
+ * @return callable
+ */
+ public function setUploadCallback( $callback ) {
+ $previous = $this->mUploadCallback;
+ $this->mUploadCallback = $callback;
+ return $previous;
+ }
+
+ /**
+ * Sets the action to perform as each log item reached.
+ * @param callable $callback
+ * @return callable
+ */
+ public function setLogItemCallback( $callback ) {
+ $previous = $this->mLogItemCallback;
+ $this->mLogItemCallback = $callback;
+ return $previous;
+ }
+
+ /**
+ * Sets the action to perform when site info is encountered
+ * @param callable $callback
+ * @return callable
+ */
+ public function setSiteInfoCallback( $callback ) {
+ $previous = $this->mSiteInfoCallback;
+ $this->mSiteInfoCallback = $callback;
+ return $previous;
+ }
+
+ /**
+ * Sets the factory object to use to convert ForeignTitle objects into local
+ * Title objects
+ * @param ImportTitleFactory $factory
+ */
+ public function setImportTitleFactory( $factory ) {
+ $this->importTitleFactory = $factory;
+ }
+
+ /**
+ * Set a target namespace to override the defaults
+ * @param null|int $namespace
+ * @return bool
+ */
+ public function setTargetNamespace( $namespace ) {
+ if ( is_null( $namespace ) ) {
+ // Don't override namespaces
+ $this->setImportTitleFactory( new NaiveImportTitleFactory() );
+ return true;
+ } elseif (
+ $namespace >= 0 &&
+ MWNamespace::exists( intval( $namespace ) )
+ ) {
+ $namespace = intval( $namespace );
+ $this->setImportTitleFactory( new NamespaceImportTitleFactory( $namespace ) );
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ /**
+ * Set a target root page under which all pages are imported
+ * @param null|string $rootpage
+ * @return Status
+ */
+ public function setTargetRootPage( $rootpage ) {
+ $status = Status::newGood();
+ if ( is_null( $rootpage ) ) {
+ // No rootpage
+ $this->setImportTitleFactory( new NaiveImportTitleFactory() );
+ } elseif ( $rootpage !== '' ) {
+ $rootpage = rtrim( $rootpage, '/' ); // avoid double slashes
+ $title = Title::newFromText( $rootpage );
+
+ if ( !$title || $title->isExternal() ) {
+ $status->fatal( 'import-rootpage-invalid' );
+ } else {
+ if ( !MWNamespace::hasSubpages( $title->getNamespace() ) ) {
+ global $wgContLang;
+
+ $displayNSText = $title->getNamespace() == NS_MAIN
+ ? wfMessage( 'blanknamespace' )->text()
+ : $wgContLang->getNsText( $title->getNamespace() );
+ $status->fatal( 'import-rootpage-nosubpage', $displayNSText );
+ } else {
+ // set namespace to 'all', so the namespace check in processTitle() can pass
+ $this->setTargetNamespace( null );
+ $this->setImportTitleFactory( new SubpageImportTitleFactory( $title ) );
+ }
+ }
+ }
+ return $status;
+ }
+
+ /**
+ * @param string $dir
+ */
+ public function setImageBasePath( $dir ) {
+ $this->mImageBasePath = $dir;
+ }
+
+ /**
+ * @param bool $import
+ */
+ public function setImportUploads( $import ) {
+ $this->mImportUploads = $import;
+ }
+
+ /**
+ * @since 1.31
+ * @param string $usernamePrefix Prefix to apply to unknown (and possibly also known) usernames
+ * @param bool $assignKnownUsers Whether to apply the prefix to usernames that exist locally
+ */
+ public function setUsernamePrefix( $usernamePrefix, $assignKnownUsers ) {
+ $this->externalUserNames = new ExternalUserNames( $usernamePrefix, $assignKnownUsers );
+ }
+
+ /**
+ * Statistics update can cause a lot of time
+ * @since 1.29
+ */
+ public function disableStatisticsUpdate() {
+ $this->disableStatisticsUpdate = true;
+ }
+
+ /**
+ * Default per-page callback. Sets up some things related to site statistics
+ * @param array $titleAndForeignTitle Two-element array, with Title object at
+ * index 0 and ForeignTitle object at index 1
+ * @return bool
+ */
+ public function beforeImportPage( $titleAndForeignTitle ) {
+ $title = $titleAndForeignTitle[0];
+ $page = WikiPage::factory( $title );
+ $this->countableCache['title_' . $title->getPrefixedText()] = $page->isCountable();
+ return true;
+ }
+
+ /**
+ * Default per-revision callback, performs the import.
+ * @param WikiRevision $revision
+ * @return bool
+ */
+ public function importRevision( $revision ) {
+ if ( !$revision->getContentHandler()->canBeUsedOn( $revision->getTitle() ) ) {
+ $this->notice( 'import-error-bad-location',
+ $revision->getTitle()->getPrefixedText(),
+ $revision->getID(),
+ $revision->getModel(),
+ $revision->getFormat() );
+
+ return false;
+ }
+
+ try {
+ return $revision->importOldRevision();
+ } catch ( MWContentSerializationException $ex ) {
+ $this->notice( 'import-error-unserialize',
+ $revision->getTitle()->getPrefixedText(),
+ $revision->getID(),
+ $revision->getModel(),
+ $revision->getFormat() );
+ }
+
+ return false;
+ }
+
+ /**
+ * Default per-revision callback, performs the import.
+ * @param WikiRevision $revision
+ * @return bool
+ */
+ public function importLogItem( $revision ) {
+ return $revision->importLogItem();
+ }
+
+ /**
+ * Dummy for now...
+ * @param WikiRevision $revision
+ * @return bool
+ */
+ public function importUpload( $revision ) {
+ return $revision->importUpload();
+ }
+
+ /**
+ * Mostly for hook use
+ * @param Title $title
+ * @param ForeignTitle $foreignTitle
+ * @param int $revCount
+ * @param int $sRevCount
+ * @param array $pageInfo
+ * @return bool
+ */
+ public function finishImportPage( $title, $foreignTitle, $revCount,
+ $sRevCount, $pageInfo
+ ) {
+ // Update article count statistics (T42009)
+ // The normal counting logic in WikiPage->doEditUpdates() is designed for
+ // one-revision-at-a-time editing, not bulk imports. In this situation it
+ // suffers from issues of replica DB lag. We let WikiPage handle the total page
+ // and revision count, and we implement our own custom logic for the
+ // article (content page) count.
+ if ( !$this->disableStatisticsUpdate ) {
+ $page = WikiPage::factory( $title );
+ $page->loadPageData( 'fromdbmaster' );
+ $content = $page->getContent();
+ if ( $content === null ) {
+ wfDebug( __METHOD__ . ': Skipping article count adjustment for ' . $title .
+ ' because WikiPage::getContent() returned null' );
+ } else {
+ $editInfo = $page->prepareContentForEdit( $content );
+ $countKey = 'title_' . $title->getPrefixedText();
+ $countable = $page->isCountable( $editInfo );
+ if ( array_key_exists( $countKey, $this->countableCache ) &&
+ $countable != $this->countableCache[$countKey] ) {
+ DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [
+ 'articles' => ( (int)$countable - (int)$this->countableCache[$countKey] )
+ ] ) );
+ }
+ }
+ }
+
+ $args = func_get_args();
+ return Hooks::run( 'AfterImportPage', $args );
+ }
+
+ /**
+ * Alternate per-revision callback, for debugging.
+ * @param WikiRevision &$revision
+ */
+ public function debugRevisionHandler( &$revision ) {
+ $this->debug( "Got revision:" );
+ if ( is_object( $revision->title ) ) {
+ $this->debug( "-- Title: " . $revision->title->getPrefixedText() );
+ } else {
+ $this->debug( "-- Title: <invalid>" );
+ }
+ $this->debug( "-- User: " . $revision->user_text );
+ $this->debug( "-- Timestamp: " . $revision->timestamp );
+ $this->debug( "-- Comment: " . $revision->comment );
+ $this->debug( "-- Text: " . $revision->text );
+ }
+
+ /**
+ * Notify the callback function of site info
+ * @param array $siteInfo
+ * @return bool|mixed
+ */
+ private function siteInfoCallback( $siteInfo ) {
+ if ( isset( $this->mSiteInfoCallback ) ) {
+ return call_user_func_array( $this->mSiteInfoCallback,
+ [ $siteInfo, $this ] );
+ } else {
+ return false;
+ }
+ }
+
+ /**
+ * Notify the callback function when a new "<page>" is reached.
+ * @param Title $title
+ */
+ function pageCallback( $title ) {
+ if ( isset( $this->mPageCallback ) ) {
+ call_user_func( $this->mPageCallback, $title );
+ }
+ }
+
+ /**
+ * Notify the callback function when a "</page>" is closed.
+ * @param Title $title
+ * @param ForeignTitle $foreignTitle
+ * @param int $revCount
+ * @param int $sucCount Number of revisions for which callback returned true
+ * @param array $pageInfo Associative array of page information
+ */
+ private function pageOutCallback( $title, $foreignTitle, $revCount,
+ $sucCount, $pageInfo ) {
+ if ( isset( $this->mPageOutCallback ) ) {
+ $args = func_get_args();
+ call_user_func_array( $this->mPageOutCallback, $args );
+ }
+ }
+
+ /**
+ * Notify the callback function of a revision
+ * @param WikiRevision $revision
+ * @return bool|mixed
+ */
+ private function revisionCallback( $revision ) {
+ if ( isset( $this->mRevisionCallback ) ) {
+ return call_user_func_array( $this->mRevisionCallback,
+ [ $revision, $this ] );
+ } else {
+ return false;
+ }
+ }
+
+ /**
+ * Notify the callback function of a new log item
+ * @param WikiRevision $revision
+ * @return bool|mixed
+ */
+ private function logItemCallback( $revision ) {
+ if ( isset( $this->mLogItemCallback ) ) {
+ return call_user_func_array( $this->mLogItemCallback,
+ [ $revision, $this ] );
+ } else {
+ return false;
+ }
+ }
+
+ /**
+ * Retrieves the contents of the named attribute of the current element.
+ * @param string $attr The name of the attribute
+ * @return string The value of the attribute or an empty string if it is not set in the current
+ * element.
+ */
+ public function nodeAttribute( $attr ) {
+ return $this->reader->getAttribute( $attr );
+ }
+
+ /**
+ * Shouldn't something like this be built-in to XMLReader?
+ * Fetches text contents of the current element, assuming
+ * no sub-elements or such scary things.
+ * @return string
+ * @access private
+ */
+ public function nodeContents() {
+ if ( $this->reader->isEmptyElement ) {
+ return "";
+ }
+ $buffer = "";
+ while ( $this->reader->read() ) {
+ switch ( $this->reader->nodeType ) {
+ case XMLReader::TEXT:
+ case XMLReader::CDATA:
+ case XMLReader::SIGNIFICANT_WHITESPACE:
+ $buffer .= $this->reader->value;
+ break;
+ case XMLReader::END_ELEMENT:
+ return $buffer;
+ }
+ }
+
+ $this->reader->close();
+ return '';
+ }
+
+ /**
+ * Primary entry point
+ * @throws Exception
+ * @throws MWException
+ * @return bool
+ */
+ public function doImport() {
+ // Calls to reader->read need to be wrapped in calls to
+ // libxml_disable_entity_loader() to avoid local file
+ // inclusion attacks (T48932).
+ $oldDisable = libxml_disable_entity_loader( true );
+ $this->reader->read();
+
+ if ( $this->reader->localName != 'mediawiki' ) {
+ libxml_disable_entity_loader( $oldDisable );
+ throw new MWException( "Expected <mediawiki> tag, got " .
+ $this->reader->localName );
+ }
+ $this->debug( "<mediawiki> tag is correct." );
+
+ $this->debug( "Starting primary dump processing loop." );
+
+ $keepReading = $this->reader->read();
+ $skip = false;
+ $rethrow = null;
+ $pageCount = 0;
+ try {
+ while ( $keepReading ) {
+ $tag = $this->reader->localName;
+ if ( $this->pageOffset ) {
+ if ( $tag === 'page' ) {
+ $pageCount++;
+ }
+ if ( $pageCount < $this->pageOffset ) {
+ $keepReading = $this->reader->next();
+ continue;
+ }
+ }
+ $type = $this->reader->nodeType;
+
+ if ( !Hooks::run( 'ImportHandleToplevelXMLTag', [ $this ] ) ) {
+ // Do nothing
+ } elseif ( $tag == 'mediawiki' && $type == XMLReader::END_ELEMENT ) {
+ break;
+ } elseif ( $tag == 'siteinfo' ) {
+ $this->handleSiteInfo();
+ } elseif ( $tag == 'page' ) {
+ $this->handlePage();
+ } elseif ( $tag == 'logitem' ) {
+ $this->handleLogItem();
+ } elseif ( $tag != '#text' ) {
+ $this->warn( "Unhandled top-level XML tag $tag" );
+
+ $skip = true;
+ }
+
+ if ( $skip ) {
+ $keepReading = $this->reader->next();
+ $skip = false;
+ $this->debug( "Skip" );
+ } else {
+ $keepReading = $this->reader->read();
+ }
+ }
+ } catch ( Exception $ex ) {
+ $rethrow = $ex;
+ }
+
+ // finally
+ libxml_disable_entity_loader( $oldDisable );
+ $this->reader->close();
+
+ if ( $rethrow ) {
+ throw $rethrow;
+ }
+
+ return true;
+ }
+
+ private function handleSiteInfo() {
+ $this->debug( "Enter site info handler." );
+ $siteInfo = [];
+
+ // Fields that can just be stuffed in the siteInfo object
+ $normalFields = [ 'sitename', 'base', 'generator', 'case' ];
+
+ while ( $this->reader->read() ) {
+ if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
+ $this->reader->localName == 'siteinfo' ) {
+ break;
+ }
+
+ $tag = $this->reader->localName;
+
+ if ( $tag == 'namespace' ) {
+ $this->foreignNamespaces[$this->nodeAttribute( 'key' )] =
+ $this->nodeContents();
+ } elseif ( in_array( $tag, $normalFields ) ) {
+ $siteInfo[$tag] = $this->nodeContents();
+ }
+ }
+
+ $siteInfo['_namespaces'] = $this->foreignNamespaces;
+ $this->siteInfoCallback( $siteInfo );
+ }
+
+ private function handleLogItem() {
+ $this->debug( "Enter log item handler." );
+ $logInfo = [];
+
+ // Fields that can just be stuffed in the pageInfo object
+ $normalFields = [ 'id', 'comment', 'type', 'action', 'timestamp',
+ 'logtitle', 'params' ];
+
+ while ( $this->reader->read() ) {
+ if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
+ $this->reader->localName == 'logitem' ) {
+ break;
+ }
+
+ $tag = $this->reader->localName;
+
+ if ( !Hooks::run( 'ImportHandleLogItemXMLTag', [
+ $this, $logInfo
+ ] ) ) {
+ // Do nothing
+ } elseif ( in_array( $tag, $normalFields ) ) {
+ $logInfo[$tag] = $this->nodeContents();
+ } elseif ( $tag == 'contributor' ) {
+ $logInfo['contributor'] = $this->handleContributor();
+ } elseif ( $tag != '#text' ) {
+ $this->warn( "Unhandled log-item XML tag $tag" );
+ }
+ }
+
+ $this->processLogItem( $logInfo );
+ }
+
+ /**
+ * @param array $logInfo
+ * @return bool|mixed
+ */
+ private function processLogItem( $logInfo ) {
+ $revision = new WikiRevision( $this->config );
+
+ if ( isset( $logInfo['id'] ) ) {
+ $revision->setID( $logInfo['id'] );
+ }
+ $revision->setType( $logInfo['type'] );
+ $revision->setAction( $logInfo['action'] );
+ if ( isset( $logInfo['timestamp'] ) ) {
+ $revision->setTimestamp( $logInfo['timestamp'] );
+ }
+ if ( isset( $logInfo['params'] ) ) {
+ $revision->setParams( $logInfo['params'] );
+ }
+ if ( isset( $logInfo['logtitle'] ) ) {
+ // @todo Using Title for non-local titles is a recipe for disaster.
+ // We should use ForeignTitle here instead.
+ $revision->setTitle( Title::newFromText( $logInfo['logtitle'] ) );
+ }
+
+ $revision->setNoUpdates( $this->mNoUpdates );
+
+ if ( isset( $logInfo['comment'] ) ) {
+ $revision->setComment( $logInfo['comment'] );
+ }
+
+ if ( isset( $logInfo['contributor']['ip'] ) ) {
+ $revision->setUserIP( $logInfo['contributor']['ip'] );
+ }
+
+ if ( !isset( $logInfo['contributor']['username'] ) ) {
+ $revision->setUsername( $this->externalUserNames->addPrefix( 'Unknown user' ) );
+ } else {
+ $revision->setUsername(
+ $this->externalUserNames->applyPrefix( $logInfo['contributor']['username'] )
+ );
+ }
+
+ return $this->logItemCallback( $revision );
+ }
+
+ private function handlePage() {
+ // Handle page data.
+ $this->debug( "Enter page handler." );
+ $pageInfo = [ 'revisionCount' => 0, 'successfulRevisionCount' => 0 ];
+
+ // Fields that can just be stuffed in the pageInfo object
+ $normalFields = [ 'title', 'ns', 'id', 'redirect', 'restrictions' ];
+
+ $skip = false;
+ $badTitle = false;
+
+ while ( $skip ? $this->reader->next() : $this->reader->read() ) {
+ if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
+ $this->reader->localName == 'page' ) {
+ break;
+ }
+
+ $skip = false;
+
+ $tag = $this->reader->localName;
+
+ if ( $badTitle ) {
+ // The title is invalid, bail out of this page
+ $skip = true;
+ } elseif ( !Hooks::run( 'ImportHandlePageXMLTag', [ $this,
+ &$pageInfo ] ) ) {
+ // Do nothing
+ } elseif ( in_array( $tag, $normalFields ) ) {
+ // An XML snippet:
+ // <page>
+ // <id>123</id>
+ // <title>Page</title>
+ // <redirect title="NewTitle"/>
+ // ...
+ // Because the redirect tag is built differently, we need special handling for that case.
+ if ( $tag == 'redirect' ) {
+ $pageInfo[$tag] = $this->nodeAttribute( 'title' );
+ } else {
+ $pageInfo[$tag] = $this->nodeContents();
+ }
+ } elseif ( $tag == 'revision' || $tag == 'upload' ) {
+ if ( !isset( $title ) ) {
+ $title = $this->processTitle( $pageInfo['title'],
+ isset( $pageInfo['ns'] ) ? $pageInfo['ns'] : null );
+
+ // $title is either an array of two titles or false.
+ if ( is_array( $title ) ) {
+ $this->pageCallback( $title );
+ list( $pageInfo['_title'], $foreignTitle ) = $title;
+ } else {
+ $badTitle = true;
+ $skip = true;
+ }
+ }
+
+ if ( $title ) {
+ if ( $tag == 'revision' ) {
+ $this->handleRevision( $pageInfo );
+ } else {
+ $this->handleUpload( $pageInfo );
+ }
+ }
+ } elseif ( $tag != '#text' ) {
+ $this->warn( "Unhandled page XML tag $tag" );
+ $skip = true;
+ }
+ }
+
+ // @note $pageInfo is only set if a valid $title is processed above with
+ // no error. If we have a valid $title, then pageCallback is called
+ // above, $pageInfo['title'] is set and we do pageOutCallback here.
+ // If $pageInfo['_title'] is not set, then $foreignTitle is also not
+ // set since they both come from $title above.
+ if ( array_key_exists( '_title', $pageInfo ) ) {
+ $this->pageOutCallback( $pageInfo['_title'], $foreignTitle,
+ $pageInfo['revisionCount'],
+ $pageInfo['successfulRevisionCount'],
+ $pageInfo );
+ }
+ }
+
+ /**
+ * @param array $pageInfo
+ */
+ private function handleRevision( &$pageInfo ) {
+ $this->debug( "Enter revision handler" );
+ $revisionInfo = [];
+
+ $normalFields = [ 'id', 'timestamp', 'comment', 'minor', 'model', 'format', 'text', 'sha1' ];
+
+ $skip = false;
+
+ while ( $skip ? $this->reader->next() : $this->reader->read() ) {
+ if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
+ $this->reader->localName == 'revision' ) {
+ break;
+ }
+
+ $tag = $this->reader->localName;
+
+ if ( !Hooks::run( 'ImportHandleRevisionXMLTag', [
+ $this, $pageInfo, $revisionInfo
+ ] ) ) {
+ // Do nothing
+ } elseif ( in_array( $tag, $normalFields ) ) {
+ $revisionInfo[$tag] = $this->nodeContents();
+ } elseif ( $tag == 'contributor' ) {
+ $revisionInfo['contributor'] = $this->handleContributor();
+ } elseif ( $tag != '#text' ) {
+ $this->warn( "Unhandled revision XML tag $tag" );
+ $skip = true;
+ }
+ }
+
+ $pageInfo['revisionCount']++;
+ if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
+ $pageInfo['successfulRevisionCount']++;
+ }
+ }
+
+ /**
+ * @param array $pageInfo
+ * @param array $revisionInfo
+ * @throws MWException
+ * @return bool|mixed
+ */
+ private function processRevision( $pageInfo, $revisionInfo ) {
+ global $wgMaxArticleSize;
+
+ // Make sure revisions won't violate $wgMaxArticleSize, which could lead to
+ // database errors and instability. Testing for revisions with only listed
+ // content models, as other content models might use serialization formats
+ // which aren't checked against $wgMaxArticleSize.
+ if ( ( !isset( $revisionInfo['model'] ) ||
+ in_array( $revisionInfo['model'], [
+ 'wikitext',
+ 'css',
+ 'json',
+ 'javascript',
+ 'text',
+ ''
+ ] ) ) &&
+ strlen( $revisionInfo['text'] ) > $wgMaxArticleSize * 1024
+ ) {
+ throw new MWException( 'The text of ' .
+ ( isset( $revisionInfo['id'] ) ?
+ "the revision with ID $revisionInfo[id]" :
+ 'a revision'
+ ) . " exceeds the maximum allowable size ($wgMaxArticleSize KB)" );
+ }
+
+ $revision = new WikiRevision( $this->config );
+
+ if ( isset( $revisionInfo['id'] ) ) {
+ $revision->setID( $revisionInfo['id'] );
+ }
+ if ( isset( $revisionInfo['model'] ) ) {
+ $revision->setModel( $revisionInfo['model'] );
+ }
+ if ( isset( $revisionInfo['format'] ) ) {
+ $revision->setFormat( $revisionInfo['format'] );
+ }
+ $revision->setTitle( $pageInfo['_title'] );
+
+ if ( isset( $revisionInfo['text'] ) ) {
+ $handler = $revision->getContentHandler();
+ $text = $handler->importTransform(
+ $revisionInfo['text'],
+ $revision->getFormat() );
+
+ $revision->setText( $text );
+ }
+ if ( isset( $revisionInfo['timestamp'] ) ) {
+ $revision->setTimestamp( $revisionInfo['timestamp'] );
+ } else {
+ $revision->setTimestamp( wfTimestampNow() );
+ }
+
+ if ( isset( $revisionInfo['comment'] ) ) {
+ $revision->setComment( $revisionInfo['comment'] );
+ }
+
+ if ( isset( $revisionInfo['minor'] ) ) {
+ $revision->setMinor( true );
+ }
+ if ( isset( $revisionInfo['contributor']['ip'] ) ) {
+ $revision->setUserIP( $revisionInfo['contributor']['ip'] );
+ } elseif ( isset( $revisionInfo['contributor']['username'] ) ) {
+ $revision->setUsername(
+ $this->externalUserNames->applyPrefix( $revisionInfo['contributor']['username'] )
+ );
+ } else {
+ $revision->setUsername( $this->externalUserNames->addPrefix( 'Unknown user' ) );
+ }
+ if ( isset( $revisionInfo['sha1'] ) ) {
+ $revision->setSha1Base36( $revisionInfo['sha1'] );
+ }
+ $revision->setNoUpdates( $this->mNoUpdates );
+
+ return $this->revisionCallback( $revision );
+ }
+
+ /**
+ * @param array $pageInfo
+ * @return mixed
+ */
+ private function handleUpload( &$pageInfo ) {
+ $this->debug( "Enter upload handler" );
+ $uploadInfo = [];
+
+ $normalFields = [ 'timestamp', 'comment', 'filename', 'text',
+ 'src', 'size', 'sha1base36', 'archivename', 'rel' ];
+
+ $skip = false;
+
+ while ( $skip ? $this->reader->next() : $this->reader->read() ) {
+ if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
+ $this->reader->localName == 'upload' ) {
+ break;
+ }
+
+ $tag = $this->reader->localName;
+
+ if ( !Hooks::run( 'ImportHandleUploadXMLTag', [
+ $this, $pageInfo
+ ] ) ) {
+ // Do nothing
+ } elseif ( in_array( $tag, $normalFields ) ) {
+ $uploadInfo[$tag] = $this->nodeContents();
+ } elseif ( $tag == 'contributor' ) {
+ $uploadInfo['contributor'] = $this->handleContributor();
+ } elseif ( $tag == 'contents' ) {
+ $contents = $this->nodeContents();
+ $encoding = $this->reader->getAttribute( 'encoding' );
+ if ( $encoding === 'base64' ) {
+ $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
+ $uploadInfo['isTempSrc'] = true;
+ }
+ } elseif ( $tag != '#text' ) {
+ $this->warn( "Unhandled upload XML tag $tag" );
+ $skip = true;
+ }
+ }
+
+ if ( $this->mImageBasePath && isset( $uploadInfo['rel'] ) ) {
+ $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
+ if ( file_exists( $path ) ) {
+ $uploadInfo['fileSrc'] = $path;
+ $uploadInfo['isTempSrc'] = false;
+ }
+ }
+
+ if ( $this->mImportUploads ) {
+ return $this->processUpload( $pageInfo, $uploadInfo );
+ }
+ }
+
+ /**
+ * @param string $contents
+ * @return string
+ */
+ private function dumpTemp( $contents ) {
+ $filename = tempnam( wfTempDir(), 'importupload' );
+ file_put_contents( $filename, $contents );
+ return $filename;
+ }
+
+ /**
+ * @param array $pageInfo
+ * @param array $uploadInfo
+ * @return mixed
+ */
+ private function processUpload( $pageInfo, $uploadInfo ) {
+ $revision = new WikiRevision( $this->config );
+ $text = isset( $uploadInfo['text'] ) ? $uploadInfo['text'] : '';
+
+ $revision->setTitle( $pageInfo['_title'] );
+ $revision->setID( $pageInfo['id'] );
+ $revision->setTimestamp( $uploadInfo['timestamp'] );
+ $revision->setText( $text );
+ $revision->setFilename( $uploadInfo['filename'] );
+ if ( isset( $uploadInfo['archivename'] ) ) {
+ $revision->setArchiveName( $uploadInfo['archivename'] );
+ }
+ $revision->setSrc( $uploadInfo['src'] );
+ if ( isset( $uploadInfo['fileSrc'] ) ) {
+ $revision->setFileSrc( $uploadInfo['fileSrc'],
+ !empty( $uploadInfo['isTempSrc'] ) );
+ }
+ if ( isset( $uploadInfo['sha1base36'] ) ) {
+ $revision->setSha1Base36( $uploadInfo['sha1base36'] );
+ }
+ $revision->setSize( intval( $uploadInfo['size'] ) );
+ $revision->setComment( $uploadInfo['comment'] );
+
+ if ( isset( $uploadInfo['contributor']['ip'] ) ) {
+ $revision->setUserIP( $uploadInfo['contributor']['ip'] );
+ }
+ if ( isset( $uploadInfo['contributor']['username'] ) ) {
+ $revision->setUsername(
+ $this->externalUserNames->applyPrefix( $uploadInfo['contributor']['username'] )
+ );
+ }
+ $revision->setNoUpdates( $this->mNoUpdates );
+
+ return call_user_func( $this->mUploadCallback, $revision );
+ }
+
+ /**
+ * @return array
+ */
+ private function handleContributor() {
+ $fields = [ 'id', 'ip', 'username' ];
+ $info = [];
+
+ if ( $this->reader->isEmptyElement ) {
+ return $info;
+ }
+ while ( $this->reader->read() ) {
+ if ( $this->reader->nodeType == XMLReader::END_ELEMENT &&
+ $this->reader->localName == 'contributor' ) {
+ break;
+ }
+
+ $tag = $this->reader->localName;
+
+ if ( in_array( $tag, $fields ) ) {
+ $info[$tag] = $this->nodeContents();
+ }
+ }
+
+ return $info;
+ }
+
+ /**
+ * @param string $text
+ * @param string|null $ns
+ * @return array|bool
+ */
+ private function processTitle( $text, $ns = null ) {
+ if ( is_null( $this->foreignNamespaces ) ) {
+ $foreignTitleFactory = new NaiveForeignTitleFactory();
+ } else {
+ $foreignTitleFactory = new NamespaceAwareForeignTitleFactory(
+ $this->foreignNamespaces );
+ }
+
+ $foreignTitle = $foreignTitleFactory->createForeignTitle( $text,
+ intval( $ns ) );
+
+ $title = $this->importTitleFactory->createTitleFromForeignTitle(
+ $foreignTitle );
+
+ $commandLineMode = $this->config->get( 'CommandLineMode' );
+ if ( is_null( $title ) ) {
+ # Invalid page title? Ignore the page
+ $this->notice( 'import-error-invalid', $foreignTitle->getFullText() );
+ return false;
+ } elseif ( $title->isExternal() ) {
+ $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
+ return false;
+ } elseif ( !$title->canExist() ) {
+ $this->notice( 'import-error-special', $title->getPrefixedText() );
+ return false;
+ } elseif ( !$title->userCan( 'edit' ) && !$commandLineMode ) {
+ # Do not import if the importing wiki user cannot edit this page
+ $this->notice( 'import-error-edit', $title->getPrefixedText() );
+ return false;
+ } elseif ( !$title->exists() && !$title->userCan( 'create' ) && !$commandLineMode ) {
+ # Do not import if the importing wiki user cannot create this page
+ $this->notice( 'import-error-create', $title->getPrefixedText() );
+ return false;
+ }
+
+ return [ $title, $foreignTitle ];
+ }
+}
diff --git a/www/wiki/includes/import/WikiRevision.php b/www/wiki/includes/import/WikiRevision.php
new file mode 100644
index 00000000..55a7b2d3
--- /dev/null
+++ b/www/wiki/includes/import/WikiRevision.php
@@ -0,0 +1,676 @@
+<?php
+/**
+ * MediaWiki page data importer.
+ *
+ * Copyright © 2003,2005 Brion Vibber <brion@pobox.com>
+ * https://www.mediawiki.org/
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
+ *
+ * @file
+ * @ingroup SpecialPage
+ */
+use MediaWiki\Logger\LoggerFactory;
+use MediaWiki\MediaWikiServices;
+
+/**
+ * Represents a revision, log entry or upload during the import process.
+ * This class sticks closely to the structure of the XML dump.
+ *
+ * @since 1.2
+ *
+ * @ingroup SpecialPage
+ */
+class WikiRevision implements ImportableUploadRevision, ImportableOldRevision {
+
+ /**
+ * @since 1.17
+ * @deprecated in 1.29. Unused.
+ * @note Introduced in 9b3128eb2b654761f21fd4ca1d5a1a4b796dc912, unused there, unused now.
+ */
+ public $importer = null;
+
+ /**
+ * @since 1.2
+ * @var Title
+ */
+ public $title = null;
+
+ /**
+ * @since 1.6.4
+ * @var int
+ */
+ public $id = 0;
+
+ /**
+ * @since 1.2
+ * @var string
+ */
+ public $timestamp = "20010115000000";
+
+ /**
+ * @since 1.2
+ * @var int
+ * @deprecated in 1.29. Unused.
+ * @note Introduced in 436a028086fb3f01c4605c5ad2964d56f9306aca, unused there, unused now.
+ */
+ public $user = 0;
+
+ /**
+ * @since 1.2
+ * @var string
+ */
+ public $user_text = "";
+
+ /**
+ * @since 1.27
+ * @var User
+ */
+ public $userObj = null;
+
+ /**
+ * @since 1.21
+ * @var string
+ */
+ public $model = null;
+
+ /**
+ * @since 1.21
+ * @var string
+ */
+ public $format = null;
+
+ /**
+ * @since 1.2
+ * @var string
+ */
+ public $text = "";
+
+ /**
+ * @since 1.12.2
+ * @var int
+ */
+ protected $size;
+
+ /**
+ * @since 1.21
+ * @var Content
+ */
+ public $content = null;
+
+ /**
+ * @since 1.24
+ * @var ContentHandler
+ */
+ protected $contentHandler = null;
+
+ /**
+ * @since 1.2.6
+ * @var string
+ */
+ public $comment = "";
+
+ /**
+ * @since 1.5.7
+ * @var bool
+ */
+ public $minor = false;
+
+ /**
+ * @since 1.12.2
+ * @var string
+ */
+ public $type = "";
+
+ /**
+ * @since 1.12.2
+ * @var string
+ */
+ public $action = "";
+
+ /**
+ * @since 1.12.2
+ * @var string
+ */
+ public $params = "";
+
+ /**
+ * @since 1.17
+ * @var string
+ */
+ public $fileSrc = '';
+
+ /**
+ * @since 1.17
+ * @var bool|string
+ */
+ public $sha1base36 = false;
+
+ /**
+ * @since 1.17
+ * @var string
+ */
+ public $archiveName = '';
+
+ /**
+ * @since 1.12.2
+ */
+ protected $filename;
+
+ /**
+ * @since 1.12.2
+ * @var string|null
+ */
+ protected $src = null;
+
+ /**
+ * @since 1.18
+ * @var bool
+ * @todo Unused?
+ */
+ public $isTemp = false;
+
+ /**
+ * @since 1.18
+ * @deprecated 1.29 use Wikirevision::isTempSrc()
+ * First written to in 43d5d3b682cc1733ad01a837d11af4a402d57e6a
+ * Actually introduced in 52cd34acf590e5be946b7885ffdc13a157c1c6cf
+ */
+ public $fileIsTemp;
+
+ /** @var bool */
+ private $mNoUpdates = false;
+
+ /** @var Config $config */
+ private $config;
+
+ public function __construct( Config $config ) {
+ $this->config = $config;
+ }
+
+ /**
+ * @since 1.7 taking a Title object (string before)
+ * @param Title $title
+ * @throws MWException
+ */
+ public function setTitle( $title ) {
+ if ( is_object( $title ) ) {
+ $this->title = $title;
+ } elseif ( is_null( $title ) ) {
+ throw new MWException( "WikiRevision given a null title in import. "
+ . "You may need to adjust \$wgLegalTitleChars." );
+ } else {
+ throw new MWException( "WikiRevision given non-object title in import." );
+ }
+ }
+
+ /**
+ * @since 1.6.4
+ * @param int $id
+ */
+ public function setID( $id ) {
+ $this->id = $id;
+ }
+
+ /**
+ * @since 1.2
+ * @param string $ts
+ */
+ public function setTimestamp( $ts ) {
+ # 2003-08-05T18:30:02Z
+ $this->timestamp = wfTimestamp( TS_MW, $ts );
+ }
+
+ /**
+ * @since 1.2
+ * @param string $user
+ */
+ public function setUsername( $user ) {
+ $this->user_text = $user;
+ }
+
+ /**
+ * @since 1.27
+ * @param User $user
+ */
+ public function setUserObj( $user ) {
+ $this->userObj = $user;
+ }
+
+ /**
+ * @since 1.2
+ * @param string $ip
+ */
+ public function setUserIP( $ip ) {
+ $this->user_text = $ip;
+ }
+
+ /**
+ * @since 1.21
+ * @param string $model
+ */
+ public function setModel( $model ) {
+ $this->model = $model;
+ }
+
+ /**
+ * @since 1.21
+ * @param string $format
+ */
+ public function setFormat( $format ) {
+ $this->format = $format;
+ }
+
+ /**
+ * @since 1.2
+ * @param string $text
+ */
+ public function setText( $text ) {
+ $this->text = $text;
+ }
+
+ /**
+ * @since 1.2.6
+ * @param string $text
+ */
+ public function setComment( $text ) {
+ $this->comment = $text;
+ }
+
+ /**
+ * @since 1.5.7
+ * @param bool $minor
+ */
+ public function setMinor( $minor ) {
+ $this->minor = (bool)$minor;
+ }
+
+ /**
+ * @since 1.12.2
+ * @param string|null $src
+ */
+ public function setSrc( $src ) {
+ $this->src = $src;
+ }
+
+ /**
+ * @since 1.17
+ * @param string $src
+ * @param bool $isTemp
+ */
+ public function setFileSrc( $src, $isTemp ) {
+ $this->fileSrc = $src;
+ $this->fileIsTemp = $isTemp;
+ $this->isTemp = $isTemp;
+ }
+
+ /**
+ * @since 1.17
+ * @param string $sha1base36
+ */
+ public function setSha1Base36( $sha1base36 ) {
+ $this->sha1base36 = $sha1base36;
+ }
+
+ /**
+ * @since 1.12.2
+ * @param string $filename
+ */
+ public function setFilename( $filename ) {
+ $this->filename = $filename;
+ }
+
+ /**
+ * @since 1.17
+ * @param string $archiveName
+ */
+ public function setArchiveName( $archiveName ) {
+ $this->archiveName = $archiveName;
+ }
+
+ /**
+ * @since 1.12.2
+ * @param int $size
+ */
+ public function setSize( $size ) {
+ $this->size = intval( $size );
+ }
+
+ /**
+ * @since 1.12.2
+ * @param string $type
+ */
+ public function setType( $type ) {
+ $this->type = $type;
+ }
+
+ /**
+ * @since 1.12.2
+ * @param string $action
+ */
+ public function setAction( $action ) {
+ $this->action = $action;
+ }
+
+ /**
+ * @since 1.12.2
+ * @param array $params
+ */
+ public function setParams( $params ) {
+ $this->params = $params;
+ }
+
+ /**
+ * @since 1.18
+ * @param bool $noupdates
+ */
+ public function setNoUpdates( $noupdates ) {
+ $this->mNoUpdates = $noupdates;
+ }
+
+ /**
+ * @since 1.2
+ * @return Title
+ */
+ public function getTitle() {
+ return $this->title;
+ }
+
+ /**
+ * @since 1.6.4
+ * @return int
+ */
+ public function getID() {
+ return $this->id;
+ }
+
+ /**
+ * @since 1.2
+ * @return string
+ */
+ public function getTimestamp() {
+ return $this->timestamp;
+ }
+
+ /**
+ * @since 1.2
+ * @return string
+ */
+ public function getUser() {
+ return $this->user_text;
+ }
+
+ /**
+ * @since 1.27
+ * @return User
+ */
+ public function getUserObj() {
+ return $this->userObj;
+ }
+
+ /**
+ * @since 1.2
+ * @return string
+ */
+ public function getText() {
+ return $this->text;
+ }
+
+ /**
+ * @since 1.24
+ * @return ContentHandler
+ */
+ public function getContentHandler() {
+ if ( is_null( $this->contentHandler ) ) {
+ $this->contentHandler = ContentHandler::getForModelID( $this->getModel() );
+ }
+
+ return $this->contentHandler;
+ }
+
+ /**
+ * @since 1.21
+ * @return Content
+ */
+ public function getContent() {
+ if ( is_null( $this->content ) ) {
+ $handler = $this->getContentHandler();
+ $this->content = $handler->unserializeContent( $this->text, $this->getFormat() );
+ }
+
+ return $this->content;
+ }
+
+ /**
+ * @since 1.21
+ * @return string
+ */
+ public function getModel() {
+ if ( is_null( $this->model ) ) {
+ $this->model = $this->getTitle()->getContentModel();
+ }
+
+ return $this->model;
+ }
+
+ /**
+ * @since 1.21
+ * @return string
+ */
+ public function getFormat() {
+ if ( is_null( $this->format ) ) {
+ $this->format = $this->getContentHandler()->getDefaultFormat();
+ }
+
+ return $this->format;
+ }
+
+ /**
+ * @since 1.2.6
+ * @return string
+ */
+ public function getComment() {
+ return $this->comment;
+ }
+
+ /**
+ * @since 1.5.7
+ * @return bool
+ */
+ public function getMinor() {
+ return $this->minor;
+ }
+
+ /**
+ * @since 1.12.2
+ * @return string|null
+ */
+ public function getSrc() {
+ return $this->src;
+ }
+
+ /**
+ * @since 1.17
+ * @return bool|string
+ */
+ public function getSha1() {
+ if ( $this->sha1base36 ) {
+ return Wikimedia\base_convert( $this->sha1base36, 36, 16 );
+ }
+ return false;
+ }
+
+ /**
+ * @since 1.31
+ * @return bool|string
+ */
+ public function getSha1Base36() {
+ if ( $this->sha1base36 ) {
+ return $this->sha1base36;
+ }
+ return false;
+ }
+
+ /**
+ * @since 1.17
+ * @return string
+ */
+ public function getFileSrc() {
+ return $this->fileSrc;
+ }
+
+ /**
+ * @since 1.17
+ * @return bool
+ */
+ public function isTempSrc() {
+ return $this->isTemp;
+ }
+
+ /**
+ * @since 1.12.2
+ * @return mixed
+ */
+ public function getFilename() {
+ return $this->filename;
+ }
+
+ /**
+ * @since 1.17
+ * @return string
+ */
+ public function getArchiveName() {
+ return $this->archiveName;
+ }
+
+ /**
+ * @since 1.12.2
+ * @return mixed
+ */
+ public function getSize() {
+ return $this->size;
+ }
+
+ /**
+ * @since 1.12.2
+ * @return string
+ */
+ public function getType() {
+ return $this->type;
+ }
+
+ /**
+ * @since 1.12.2
+ * @return string
+ */
+ public function getAction() {
+ return $this->action;
+ }
+
+ /**
+ * @since 1.12.2
+ * @return string
+ */
+ public function getParams() {
+ return $this->params;
+ }
+
+ /**
+ * @since 1.4.1
+ * @deprecated in 1.31. Use OldRevisionImporter::import
+ * @return bool
+ */
+ public function importOldRevision() {
+ if ( $this->mNoUpdates ) {
+ $importer = MediaWikiServices::getInstance()->getWikiRevisionOldRevisionImporterNoUpdates();
+ } else {
+ $importer = MediaWikiServices::getInstance()->getWikiRevisionOldRevisionImporter();
+ }
+ return $importer->import( $this );
+ }
+
+ /**
+ * @since 1.12.2
+ * @return bool
+ */
+ public function importLogItem() {
+ $dbw = wfGetDB( DB_MASTER );
+
+ $user = $this->getUserObj() ?: User::newFromName( $this->getUser(), false );
+
+ # @todo FIXME: This will not record autoblocks
+ if ( !$this->getTitle() ) {
+ wfDebug( __METHOD__ . ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
+ $this->timestamp . "\n" );
+ return false;
+ }
+ # Check if it exists already
+ // @todo FIXME: Use original log ID (better for backups)
+ $prior = $dbw->selectField( 'logging', '1',
+ [ 'log_type' => $this->getType(),
+ 'log_action' => $this->getAction(),
+ 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
+ 'log_namespace' => $this->getTitle()->getNamespace(),
+ 'log_title' => $this->getTitle()->getDBkey(),
+ 'log_params' => $this->params ],
+ __METHOD__
+ );
+ // @todo FIXME: This could fail slightly for multiple matches :P
+ if ( $prior ) {
+ wfDebug( __METHOD__
+ . ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp "
+ . $this->timestamp . "\n" );
+ return false;
+ }
+ $data = [
+ 'log_type' => $this->type,
+ 'log_action' => $this->action,
+ 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
+ 'log_namespace' => $this->getTitle()->getNamespace(),
+ 'log_title' => $this->getTitle()->getDBkey(),
+ 'log_params' => $this->params
+ ] + CommentStore::getStore()->insert( $dbw, 'log_comment', $this->getComment() )
+ + ActorMigration::newMigration()->getInsertValues( $dbw, 'log_user', $user );
+ $dbw->insert( 'logging', $data, __METHOD__ );
+
+ return true;
+ }
+
+ /**
+ * @since 1.12.2
+ * @deprecated in 1.31. Use UploadImporter::import
+ * @return bool
+ */
+ public function importUpload() {
+ $importer = MediaWikiServices::getInstance()->getWikiRevisionUploadImporter();
+ $statusValue = $importer->import( $this );
+ return $statusValue->isGood();
+ }
+
+ /**
+ * @since 1.12.2
+ * @deprecated in 1.31. Use UploadImporter::downloadSource
+ * @return bool|string
+ */
+ public function downloadSource() {
+ $importer = new ImportableUploadRevisionImporter(
+ $this->config->get( 'EnableUploads' ),
+ LoggerFactory::getInstance( 'UploadRevisionImporter' )
+ );
+ return $importer->downloadSource( $this );
+ }
+
+}