MediaWiki  1.28.1
WikiRevision.php
Go to the documentation of this file.
1 <?php
33 class WikiRevision {
35  public $importer = null;
36 
38  public $title = null;
39 
41  public $id = 0;
42 
44  public $timestamp = "20010115000000";
45 
49  public $user = 0;
50 
52  public $user_text = "";
53 
55  public $userObj = null;
56 
58  public $model = null;
59 
61  public $format = null;
62 
64  public $text = "";
65 
67  protected $size;
68 
70  public $content = null;
71 
73  protected $contentHandler = null;
74 
76  public $comment = "";
77 
79  public $minor = false;
80 
82  public $type = "";
83 
85  public $action = "";
86 
88  public $params = "";
89 
91  public $fileSrc = '';
92 
94  public $sha1base36 = false;
95 
100  public $isTemp = false;
101 
103  public $archiveName = '';
104 
105  protected $filename;
106 
108  protected $src;
109 
111  public $fileIsTemp;
112 
114  private $mNoUpdates = false;
115 
117  private $config;
118 
119  public function __construct( Config $config ) {
120  $this->config = $config;
121  }
122 
127  function setTitle( $title ) {
128  if ( is_object( $title ) ) {
129  $this->title = $title;
130  } elseif ( is_null( $title ) ) {
131  throw new MWException( "WikiRevision given a null title in import. "
132  . "You may need to adjust \$wgLegalTitleChars." );
133  } else {
134  throw new MWException( "WikiRevision given non-object title in import." );
135  }
136  }
137 
141  function setID( $id ) {
142  $this->id = $id;
143  }
144 
148  function setTimestamp( $ts ) {
149  # 2003-08-05T18:30:02Z
150  $this->timestamp = wfTimestamp( TS_MW, $ts );
151  }
152 
156  function setUsername( $user ) {
157  $this->user_text = $user;
158  }
159 
163  function setUserObj( $user ) {
164  $this->userObj = $user;
165  }
166 
170  function setUserIP( $ip ) {
171  $this->user_text = $ip;
172  }
173 
177  function setModel( $model ) {
178  $this->model = $model;
179  }
180 
184  function setFormat( $format ) {
185  $this->format = $format;
186  }
187 
191  function setText( $text ) {
192  $this->text = $text;
193  }
194 
198  function setComment( $text ) {
199  $this->comment = $text;
200  }
201 
205  function setMinor( $minor ) {
206  $this->minor = (bool)$minor;
207  }
208 
212  function setSrc( $src ) {
213  $this->src = $src;
214  }
215 
220  function setFileSrc( $src, $isTemp ) {
221  $this->fileSrc = $src;
222  $this->fileIsTemp = $isTemp;
223  }
224 
229  $this->sha1base36 = $sha1base36;
230  }
231 
235  function setFilename( $filename ) {
236  $this->filename = $filename;
237  }
238 
243  $this->archiveName = $archiveName;
244  }
245 
249  function setSize( $size ) {
250  $this->size = intval( $size );
251  }
252 
256  function setType( $type ) {
257  $this->type = $type;
258  }
259 
263  function setAction( $action ) {
264  $this->action = $action;
265  }
266 
270  function setParams( $params ) {
271  $this->params = $params;
272  }
273 
277  public function setNoUpdates( $noupdates ) {
278  $this->mNoUpdates = $noupdates;
279  }
280 
284  function getTitle() {
285  return $this->title;
286  }
287 
291  function getID() {
292  return $this->id;
293  }
294 
298  function getTimestamp() {
299  return $this->timestamp;
300  }
301 
305  function getUser() {
306  return $this->user_text;
307  }
308 
312  function getUserObj() {
313  return $this->userObj;
314  }
315 
321  function getText() {
322  wfDeprecated( __METHOD__, '1.21' );
323 
324  return $this->text;
325  }
326 
330  function getContentHandler() {
331  if ( is_null( $this->contentHandler ) ) {
332  $this->contentHandler = ContentHandler::getForModelID( $this->getModel() );
333  }
334 
335  return $this->contentHandler;
336  }
337 
341  function getContent() {
342  if ( is_null( $this->content ) ) {
343  $handler = $this->getContentHandler();
344  $this->content = $handler->unserializeContent( $this->text, $this->getFormat() );
345  }
346 
347  return $this->content;
348  }
349 
353  function getModel() {
354  if ( is_null( $this->model ) ) {
355  $this->model = $this->getTitle()->getContentModel();
356  }
357 
358  return $this->model;
359  }
360 
364  function getFormat() {
365  if ( is_null( $this->format ) ) {
366  $this->format = $this->getContentHandler()->getDefaultFormat();
367  }
368 
369  return $this->format;
370  }
371 
375  function getComment() {
376  return $this->comment;
377  }
378 
382  function getMinor() {
383  return $this->minor;
384  }
385 
389  function getSrc() {
390  return $this->src;
391  }
392 
396  function getSha1() {
397  if ( $this->sha1base36 ) {
398  return Wikimedia\base_convert( $this->sha1base36, 36, 16 );
399  }
400  return false;
401  }
402 
406  function getFileSrc() {
407  return $this->fileSrc;
408  }
409 
413  function isTempSrc() {
414  return $this->isTemp;
415  }
416 
420  function getFilename() {
421  return $this->filename;
422  }
423 
427  function getArchiveName() {
428  return $this->archiveName;
429  }
430 
434  function getSize() {
435  return $this->size;
436  }
437 
441  function getType() {
442  return $this->type;
443  }
444 
448  function getAction() {
449  return $this->action;
450  }
451 
455  function getParams() {
456  return $this->params;
457  }
458 
462  function importOldRevision() {
463  $dbw = wfGetDB( DB_MASTER );
464 
465  # Sneak a single revision into place
466  $user = $this->getUserObj() ?: User::newFromName( $this->getUser() );
467  if ( $user ) {
468  $userId = intval( $user->getId() );
469  $userText = $user->getName();
470  } else {
471  $userId = 0;
472  $userText = $this->getUser();
473  $user = new User;
474  }
475 
476  // avoid memory leak...?
478 
479  $page = WikiPage::factory( $this->title );
480  $page->loadPageData( 'fromdbmaster' );
481  if ( !$page->exists() ) {
482  // must create the page...
483  $pageId = $page->insertOn( $dbw );
484  $created = true;
485  $oldcountable = null;
486  } else {
487  $pageId = $page->getId();
488  $created = false;
489 
490  $prior = $dbw->selectField( 'revision', '1',
491  [ 'rev_page' => $pageId,
492  'rev_timestamp' => $dbw->timestamp( $this->timestamp ),
493  'rev_user_text' => $userText,
494  'rev_comment' => $this->getComment() ],
495  __METHOD__
496  );
497  if ( $prior ) {
498  // @todo FIXME: This could fail slightly for multiple matches :P
499  wfDebug( __METHOD__ . ": skipping existing revision for [[" .
500  $this->title->getPrefixedText() . "]], timestamp " . $this->timestamp . "\n" );
501  return false;
502  }
503  }
504 
505  if ( !$pageId ) {
506  // This seems to happen if two clients simultaneously try to import the
507  // same page
508  wfDebug( __METHOD__ . ': got invalid $pageId when importing revision of [[' .
509  $this->title->getPrefixedText() . ']], timestamp ' . $this->timestamp . "\n" );
510  return false;
511  }
512 
513  // Select previous version to make size diffs correct
514  // @todo This assumes that multiple revisions of the same page are imported
515  // in order from oldest to newest.
516  $prevId = $dbw->selectField( 'revision', 'rev_id',
517  [
518  'rev_page' => $pageId,
519  'rev_timestamp <= ' . $dbw->addQuotes( $dbw->timestamp( $this->timestamp ) ),
520  ],
521  __METHOD__,
522  [ 'ORDER BY' => [
523  'rev_timestamp DESC',
524  'rev_id DESC', // timestamp is not unique per page
525  ]
526  ]
527  );
528 
529  # @todo FIXME: Use original rev_id optionally (better for backups)
530  # Insert the row
531  $revision = new Revision( [
532  'title' => $this->title,
533  'page' => $pageId,
534  'content_model' => $this->getModel(),
535  'content_format' => $this->getFormat(),
536  // XXX: just set 'content' => $this->getContent()?
537  'text' => $this->getContent()->serialize( $this->getFormat() ),
538  'comment' => $this->getComment(),
539  'user' => $userId,
540  'user_text' => $userText,
541  'timestamp' => $this->timestamp,
542  'minor_edit' => $this->minor,
543  'parent_id' => $prevId,
544  ] );
545  $revision->insertOn( $dbw );
546  $changed = $page->updateIfNewerOn( $dbw, $revision );
547 
548  if ( $changed !== false && !$this->mNoUpdates ) {
549  wfDebug( __METHOD__ . ": running updates\n" );
550  // countable/oldcountable stuff is handled in WikiImporter::finishImportPage
551  $page->doEditUpdates(
552  $revision,
553  $user,
554  [ 'created' => $created, 'oldcountable' => 'no-change' ]
555  );
556  }
557 
558  return true;
559  }
560 
561  function importLogItem() {
562  $dbw = wfGetDB( DB_MASTER );
563 
564  $user = $this->getUserObj() ?: User::newFromName( $this->getUser() );
565  if ( $user ) {
566  $userId = intval( $user->getId() );
567  $userText = $user->getName();
568  } else {
569  $userId = 0;
570  $userText = $this->getUser();
571  }
572 
573  # @todo FIXME: This will not record autoblocks
574  if ( !$this->getTitle() ) {
575  wfDebug( __METHOD__ . ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
576  $this->timestamp . "\n" );
577  return false;
578  }
579  # Check if it exists already
580  // @todo FIXME: Use original log ID (better for backups)
581  $prior = $dbw->selectField( 'logging', '1',
582  [ 'log_type' => $this->getType(),
583  'log_action' => $this->getAction(),
584  'log_timestamp' => $dbw->timestamp( $this->timestamp ),
585  'log_namespace' => $this->getTitle()->getNamespace(),
586  'log_title' => $this->getTitle()->getDBkey(),
587  'log_comment' => $this->getComment(),
588  # 'log_user_text' => $this->user_text,
589  'log_params' => $this->params ],
590  __METHOD__
591  );
592  // @todo FIXME: This could fail slightly for multiple matches :P
593  if ( $prior ) {
594  wfDebug( __METHOD__
595  . ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp "
596  . $this->timestamp . "\n" );
597  return false;
598  }
599  $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
600  $data = [
601  'log_id' => $log_id,
602  'log_type' => $this->type,
603  'log_action' => $this->action,
604  'log_timestamp' => $dbw->timestamp( $this->timestamp ),
605  'log_user' => $userId,
606  'log_user_text' => $userText,
607  'log_namespace' => $this->getTitle()->getNamespace(),
608  'log_title' => $this->getTitle()->getDBkey(),
609  'log_comment' => $this->getComment(),
610  'log_params' => $this->params
611  ];
612  $dbw->insert( 'logging', $data, __METHOD__ );
613 
614  return true;
615  }
616 
620  function importUpload() {
621  # Construct a file
622  $archiveName = $this->getArchiveName();
623  if ( $archiveName ) {
624  wfDebug( __METHOD__ . "Importing archived file as $archiveName\n" );
625  $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
626  RepoGroup::singleton()->getLocalRepo(), $archiveName );
627  } else {
628  $file = wfLocalFile( $this->getTitle() );
629  $file->load( File::READ_LATEST );
630  wfDebug( __METHOD__ . 'Importing new file as ' . $file->getName() . "\n" );
631  if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
632  $archiveName = $file->getTimestamp() . '!' . $file->getName();
633  $file = OldLocalFile::newFromArchiveName( $this->getTitle(),
634  RepoGroup::singleton()->getLocalRepo(), $archiveName );
635  wfDebug( __METHOD__ . "File already exists; importing as $archiveName\n" );
636  }
637  }
638  if ( !$file ) {
639  wfDebug( __METHOD__ . ': Bad file for ' . $this->getTitle() . "\n" );
640  return false;
641  }
642 
643  # Get the file source or download if necessary
644  $source = $this->getFileSrc();
645  $autoDeleteSource = $this->isTempSrc();
646  if ( !strlen( $source ) ) {
647  $source = $this->downloadSource();
648  $autoDeleteSource = true;
649  }
650  if ( !strlen( $source ) ) {
651  wfDebug( __METHOD__ . ": Could not fetch remote file.\n" );
652  return false;
653  }
654 
655  $tmpFile = new TempFSFile( $source );
656  if ( $autoDeleteSource ) {
657  $tmpFile->autocollect();
658  }
659 
660  $sha1File = ltrim( sha1_file( $source ), '0' );
661  $sha1 = $this->getSha1();
662  if ( $sha1 && ( $sha1 !== $sha1File ) ) {
663  wfDebug( __METHOD__ . ": Corrupt file $source.\n" );
664  return false;
665  }
666 
667  $user = $this->getUserObj() ?: User::newFromName( $this->getUser() );
668 
669  # Do the actual upload
670  if ( $archiveName ) {
671  $status = $file->uploadOld( $source, $archiveName,
672  $this->getTimestamp(), $this->getComment(), $user );
673  } else {
674  $flags = 0;
675  $status = $file->upload( $source, $this->getComment(), $this->getComment(),
676  $flags, false, $this->getTimestamp(), $user );
677  }
678 
679  if ( $status->isGood() ) {
680  wfDebug( __METHOD__ . ": Successful\n" );
681  return true;
682  } else {
683  wfDebug( __METHOD__ . ': failed: ' . $status->getHTML() . "\n" );
684  return false;
685  }
686  }
687 
691  function downloadSource() {
692  if ( !$this->config->get( 'EnableUploads' ) ) {
693  return false;
694  }
695 
696  $tempo = tempnam( wfTempDir(), 'download' );
697  $f = fopen( $tempo, 'wb' );
698  if ( !$f ) {
699  wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
700  return false;
701  }
702 
703  // @todo FIXME!
704  $src = $this->getSrc();
705  $data = Http::get( $src, [], __METHOD__ );
706  if ( !$data ) {
707  wfDebug( "IMPORT: couldn't fetch source $src\n" );
708  fclose( $f );
709  unlink( $tempo );
710  return false;
711  }
712 
713  fwrite( $f, $data );
714  fclose( $f );
715 
716  return $tempo;
717  }
718 
719 }
static newFromName($name, $validate= 'valid')
Static factory method for creation from username.
Definition: User.php:525
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:115
wfGetDB($db, $groups=[], $wiki=false)
Get a Database object.
bool string $sha1base36
static clearCaches()
Definition: Title.php:3352
setFileSrc($src, $isTemp)
per default it will return the text for text based content
static getForModelID($modelId)
Returns the ContentHandler singleton for the given model ID.
static newFromArchiveName($title, $repo, $archiveName)
string $format
This class is used to hold the location and do limited manipulation of files stored temporarily (this...
Definition: TempFSFile.php:30
$source
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition: hooks.txt:2703
Content $content
title
wfLocalFile($title)
Get an object referring to a locally registered file.
const DB_MASTER
Definition: defines.php:23
setSha1Base36($sha1base36)
setFilename($filename)
string $action
wfDebug($text, $dest= 'all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
setNoUpdates($noupdates)
setModel($model)
wfTimestamp($outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
setAction($action)
string $comment
wfTempDir()
Tries to get the system directory for temporary files.
setUserObj($user)
static singleton()
Get a RepoGroup instance.
Definition: RepoGroup.php:59
setParams($params)
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object to manipulate or replace but no entry for that model exists in $wgContentHandlers if desired whether it is OK to use $contentModel on $title Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok inclusive false for true for descending in case the handler function wants to provide a converted Content object Note that $result getContentModel() must return $toModel. 'CustomEditor'$rcid is used in generating this variable which contains information about the new such as the revision s whether the revision was marked as a minor edit or etc which include things like revision author revision comment
Definition: hooks.txt:1156
setFormat($format)
Represents a revision, log entry or upload during the import process.
wfDeprecated($function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
string $archiveName
const TS_MW
MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
Definition: defines.php:11
setArchiveName($archiveName)
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add text
Definition: design.txt:12
string $timestamp
setMinor($minor)
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
ContentHandler $contentHandler
This document describes the state of Postgres support in and is fairly well maintained The main code is very well while extensions are very hit and miss it is probably the most supported database after MySQL Much of the work in making MediaWiki database agnostic came about through the work of creating Postgres as and are nearing end of but without copying over all the usage comments General notes on the but these can almost always be programmed around *Although Postgres has a true BOOLEAN type
Definition: postgres.txt:22
__construct(Config $config)
setUsername($user)
string $fileSrc
string $user_text
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
Definition: hooks.txt:1046
serialize()
Definition: ApiMessage.php:94
static get($url, $options=[], $caller=__METHOD__)
Simple wrapper for Http::request( 'GET' )
Definition: Http.php:94
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check set to true or false to override the $wgMaxImageArea check result gives extension the possibility to transform it themselves $handler
Definition: hooks.txt:802
string $params
setTitle($title)
setComment($text)
if the prop value should be in the metadata multi language array format
Definition: hooks.txt:1610
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached $page
Definition: hooks.txt:2491