Import: Handle uploads with sha1 starting with 0 properly
[mediawiki.git] / includes / import / WikiRevision.php
blob6c238cf9f2783c63bb210c89dfe9cf80d985f126
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 * Represents a revision, log entry or upload during the import process.
29 * This class sticks closely to the structure of the XML dump.
31 * @ingroup SpecialPage
33 class WikiRevision {
34 /** @todo Unused? */
35 public $importer = null;
37 /** @var Title */
38 public $title = null;
40 /** @var int */
41 public $id = 0;
43 /** @var string */
44 public $timestamp = "20010115000000";
46 /**
47 * @var int
48 * @todo Can't find any uses. Public, because that's suspicious. Get clarity. */
49 public $user = 0;
51 /** @var string */
52 public $user_text = "";
54 /** @var string */
55 public $model = null;
57 /** @var string */
58 public $format = null;
60 /** @var string */
61 public $text = "";
63 /** @var int */
64 protected $size;
66 /** @var Content */
67 public $content = null;
69 /** @var ContentHandler */
70 protected $contentHandler = null;
72 /** @var string */
73 public $comment = "";
75 /** @var bool */
76 public $minor = false;
78 /** @var string */
79 public $type = "";
81 /** @var string */
82 public $action = "";
84 /** @var string */
85 public $params = "";
87 /** @var string */
88 public $fileSrc = '';
90 /** @var bool|string */
91 public $sha1base36 = false;
93 /**
94 * @var bool
95 * @todo Unused?
97 public $isTemp = false;
99 /** @var string */
100 public $archiveName = '';
102 protected $filename;
104 /** @var mixed */
105 protected $src;
107 /** @todo Unused? */
108 public $fileIsTemp;
110 /** @var bool */
111 private $mNoUpdates = false;
113 /** @var Config $config */
114 private $config;
116 public function __construct( Config $config ) {
117 $this->config = $config;
121 * @param Title $title
122 * @throws MWException
124 function setTitle( $title ) {
125 if ( is_object( $title ) ) {
126 $this->title = $title;
127 } elseif ( is_null( $title ) ) {
128 throw new MWException( "WikiRevision given a null title in import. "
129 . "You may need to adjust \$wgLegalTitleChars." );
130 } else {
131 throw new MWException( "WikiRevision given non-object title in import." );
136 * @param int $id
138 function setID( $id ) {
139 $this->id = $id;
143 * @param string $ts
145 function setTimestamp( $ts ) {
146 # 2003-08-05T18:30:02Z
147 $this->timestamp = wfTimestamp( TS_MW, $ts );
151 * @param string $user
153 function setUsername( $user ) {
154 $this->user_text = $user;
158 * @param string $ip
160 function setUserIP( $ip ) {
161 $this->user_text = $ip;
165 * @param string $model
167 function setModel( $model ) {
168 $this->model = $model;
172 * @param string $format
174 function setFormat( $format ) {
175 $this->format = $format;
179 * @param string $text
181 function setText( $text ) {
182 $this->text = $text;
186 * @param string $text
188 function setComment( $text ) {
189 $this->comment = $text;
193 * @param bool $minor
195 function setMinor( $minor ) {
196 $this->minor = (bool)$minor;
200 * @param mixed $src
202 function setSrc( $src ) {
203 $this->src = $src;
207 * @param string $src
208 * @param bool $isTemp
210 function setFileSrc( $src, $isTemp ) {
211 $this->fileSrc = $src;
212 $this->fileIsTemp = $isTemp;
216 * @param string $sha1base36
218 function setSha1Base36( $sha1base36 ) {
219 $this->sha1base36 = $sha1base36;
223 * @param string $filename
225 function setFilename( $filename ) {
226 $this->filename = $filename;
230 * @param string $archiveName
232 function setArchiveName( $archiveName ) {
233 $this->archiveName = $archiveName;
237 * @param int $size
239 function setSize( $size ) {
240 $this->size = intval( $size );
244 * @param string $type
246 function setType( $type ) {
247 $this->type = $type;
251 * @param string $action
253 function setAction( $action ) {
254 $this->action = $action;
258 * @param array $params
260 function setParams( $params ) {
261 $this->params = $params;
265 * @param bool $noupdates
267 public function setNoUpdates( $noupdates ) {
268 $this->mNoUpdates = $noupdates;
272 * @return Title
274 function getTitle() {
275 return $this->title;
279 * @return int
281 function getID() {
282 return $this->id;
286 * @return string
288 function getTimestamp() {
289 return $this->timestamp;
293 * @return string
295 function getUser() {
296 return $this->user_text;
300 * @return string
302 * @deprecated Since 1.21, use getContent() instead.
304 function getText() {
305 ContentHandler::deprecated( __METHOD__, '1.21' );
307 return $this->text;
311 * @return ContentHandler
313 function getContentHandler() {
314 if ( is_null( $this->contentHandler ) ) {
315 $this->contentHandler = ContentHandler::getForModelID( $this->getModel() );
318 return $this->contentHandler;
322 * @return Content
324 function getContent() {
325 if ( is_null( $this->content ) ) {
326 $handler = $this->getContentHandler();
327 $this->content = $handler->unserializeContent( $this->text, $this->getFormat() );
330 return $this->content;
334 * @return string
336 function getModel() {
337 if ( is_null( $this->model ) ) {
338 $this->model = $this->getTitle()->getContentModel();
341 return $this->model;
345 * @return string
347 function getFormat() {
348 if ( is_null( $this->format ) ) {
349 $this->format = $this->getContentHandler()->getDefaultFormat();
352 return $this->format;
356 * @return string
358 function getComment() {
359 return $this->comment;
363 * @return bool
365 function getMinor() {
366 return $this->minor;
370 * @return mixed
372 function getSrc() {
373 return $this->src;
377 * @return bool|string
379 function getSha1() {
380 if ( $this->sha1base36 ) {
381 return Wikimedia\base_convert( $this->sha1base36, 36, 16 );
383 return false;
387 * @return string
389 function getFileSrc() {
390 return $this->fileSrc;
394 * @return bool
396 function isTempSrc() {
397 return $this->isTemp;
401 * @return mixed
403 function getFilename() {
404 return $this->filename;
408 * @return string
410 function getArchiveName() {
411 return $this->archiveName;
415 * @return mixed
417 function getSize() {
418 return $this->size;
422 * @return string
424 function getType() {
425 return $this->type;
429 * @return string
431 function getAction() {
432 return $this->action;
436 * @return string
438 function getParams() {
439 return $this->params;
443 * @return bool
445 function importOldRevision() {
446 $dbw = wfGetDB( DB_MASTER );
448 # Sneak a single revision into place
449 $user = User::newFromName( $this->getUser() );
450 if ( $user ) {
451 $userId = intval( $user->getId() );
452 $userText = $user->getName();
453 $userObj = $user;
454 } else {
455 $userId = 0;
456 $userText = $this->getUser();
457 $userObj = new User;
460 // avoid memory leak...?
461 Title::clearCaches();
463 $page = WikiPage::factory( $this->title );
464 $page->loadPageData( 'fromdbmaster' );
465 if ( !$page->exists() ) {
466 # must create the page...
467 $pageId = $page->insertOn( $dbw );
468 $created = true;
469 $oldcountable = null;
470 } else {
471 $pageId = $page->getId();
472 $created = false;
474 $prior = $dbw->selectField( 'revision', '1',
475 array( 'rev_page' => $pageId,
476 'rev_timestamp' => $dbw->timestamp( $this->timestamp ),
477 'rev_user_text' => $userText,
478 'rev_comment' => $this->getComment() ),
479 __METHOD__
481 if ( $prior ) {
482 // @todo FIXME: This could fail slightly for multiple matches :P
483 wfDebug( __METHOD__ . ": skipping existing revision for [[" .
484 $this->title->getPrefixedText() . "]], timestamp " . $this->timestamp . "\n" );
485 return false;
489 // Select previous version to make size diffs correct
490 $prevId = $dbw->selectField( 'revision', 'rev_id',
491 array(
492 'rev_page' => $pageId,
493 'rev_timestamp <= ' . $dbw->timestamp( $this->timestamp ),
495 __METHOD__,
496 array( 'ORDER BY' => array(
497 'rev_timestamp DESC',
498 'rev_id DESC', // timestamp is not unique per page
503 # @todo FIXME: Use original rev_id optionally (better for backups)
504 # Insert the row
505 $revision = new Revision( array(
506 'title' => $this->title,
507 'page' => $pageId,
508 'content_model' => $this->getModel(),
509 'content_format' => $this->getFormat(),
510 // XXX: just set 'content' => $this->getContent()?
511 'text' => $this->getContent()->serialize( $this->getFormat() ),
512 'comment' => $this->getComment(),
513 'user' => $userId,
514 'user_text' => $userText,
515 'timestamp' => $this->timestamp,
516 'minor_edit' => $this->minor,
517 'parent_id' => $prevId,
518 ) );
519 $revision->insertOn( $dbw );
520 $changed = $page->updateIfNewerOn( $dbw, $revision );
522 if ( $changed !== false && !$this->mNoUpdates ) {
523 wfDebug( __METHOD__ . ": running updates\n" );
524 // countable/oldcountable stuff is handled in WikiImporter::finishImportPage
525 $page->doEditUpdates(
526 $revision,
527 $userObj,
528 array( 'created' => $created, 'oldcountable' => 'no-change' )
532 return true;
535 function importLogItem() {
536 $dbw = wfGetDB( DB_MASTER );
537 # @todo FIXME: This will not record autoblocks
538 if ( !$this->getTitle() ) {
539 wfDebug( __METHOD__ . ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
540 $this->timestamp . "\n" );
541 return;
543 # Check if it exists already
544 // @todo FIXME: Use original log ID (better for backups)
545 $prior = $dbw->selectField( 'logging', '1',
546 array( 'log_type' => $this->getType(),
547 'log_action' => $this->getAction(),
548 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
549 'log_namespace' => $this->getTitle()->getNamespace(),
550 'log_title' => $this->getTitle()->getDBkey(),
551 'log_comment' => $this->getComment(),
552 # 'log_user_text' => $this->user_text,
553 'log_params' => $this->params ),
554 __METHOD__
556 // @todo FIXME: This could fail slightly for multiple matches :P
557 if ( $prior ) {
558 wfDebug( __METHOD__
559 . ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp "
560 . $this->timestamp . "\n" );
561 return;
563 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
564 $data = array(
565 'log_id' => $log_id,
566 'log_type' => $this->type,
567 'log_action' => $this->action,
568 'log_timestamp' => $dbw->timestamp( $this->timestamp ),
569 'log_user' => User::idFromName( $this->user_text ),
570 # 'log_user_text' => $this->user_text,
571 'log_namespace' => $this->getTitle()->getNamespace(),
572 'log_title' => $this->getTitle()->getDBkey(),
573 'log_comment' => $this->getComment(),
574 'log_params' => $this->params
576 $dbw->insert( 'logging', $data, __METHOD__ );
580 * @return bool
582 function importUpload() {
583 # Construct a file
584 $archiveName = $this->getArchiveName();
585 if ( $archiveName ) {
586 wfDebug( __METHOD__ . "Importing archived file as $archiveName\n" );
587 $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
588 RepoGroup::singleton()->getLocalRepo(), $archiveName );
589 } else {
590 $file = wfLocalFile( $this->getTitle() );
591 $file->load( File::READ_LATEST );
592 wfDebug( __METHOD__ . 'Importing new file as ' . $file->getName() . "\n" );
593 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
594 $archiveName = $file->getTimestamp() . '!' . $file->getName();
595 $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
596 RepoGroup::singleton()->getLocalRepo(), $archiveName );
597 wfDebug( __METHOD__ . "File already exists; importing as $archiveName\n" );
600 if ( !$file ) {
601 wfDebug( __METHOD__ . ': Bad file for ' . $this->getTitle() . "\n" );
602 return false;
605 # Get the file source or download if necessary
606 $source = $this->getFileSrc();
607 $flags = $this->isTempSrc() ? File::DELETE_SOURCE : 0;
608 if ( !$source ) {
609 $source = $this->downloadSource();
610 $flags |= File::DELETE_SOURCE;
612 if ( !$source ) {
613 wfDebug( __METHOD__ . ": Could not fetch remote file.\n" );
614 return false;
616 $sha1File = ltrim( sha1_file( $source ), '0' );
617 $sha1 = $this->getSha1();
618 if ( $sha1 && ( $sha1 !== $sha1File ) ) {
619 if ( $flags & File::DELETE_SOURCE ) {
620 # Broken file; delete it if it is a temporary file
621 unlink( $source );
623 wfDebug( __METHOD__ . ": Corrupt file $source.\n" );
624 return false;
627 $user = User::newFromName( $this->user_text );
629 # Do the actual upload
630 if ( $archiveName ) {
631 $status = $file->uploadOld( $source, $archiveName,
632 $this->getTimestamp(), $this->getComment(), $user, $flags );
633 } else {
634 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
635 $flags, false, $this->getTimestamp(), $user );
638 if ( $status->isGood() ) {
639 wfDebug( __METHOD__ . ": Successful\n" );
640 return true;
641 } else {
642 wfDebug( __METHOD__ . ': failed: ' . $status->getHTML() . "\n" );
643 return false;
648 * @return bool|string
650 function downloadSource() {
651 if ( !$this->config->get( 'EnableUploads' ) ) {
652 return false;
655 $tempo = tempnam( wfTempDir(), 'download' );
656 $f = fopen( $tempo, 'wb' );
657 if ( !$f ) {
658 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
659 return false;
662 // @todo FIXME!
663 $src = $this->getSrc();
664 $data = Http::get( $src, array(), __METHOD__ );
665 if ( !$data ) {
666 wfDebug( "IMPORT: couldn't fetch source $src\n" );
667 fclose( $f );
668 unlink( $tempo );
669 return false;
672 fwrite( $f, $data );
673 fclose( $f );
675 return $tempo;