MediaWiki  master
RenderedRevision.php
Go to the documentation of this file.
1 <?php
23 namespace MediaWiki\Revision;
24 
32 use Title;
33 use User;
34 use Content;
36 
45 
49  private $title;
50 
52  private $revision;
53 
57  private $options;
58 
63 
67  private $forUser = null;
68 
73  private $revisionOutput = null;
74 
79  private $slotsOutput = [];
80 
85  private $combineOutput;
86 
91 
108  public function __construct(
109  Title $title,
112  callable $combineOutput,
114  User $forUser = null
115  ) {
116  $this->title = $title;
117  $this->options = $options;
118 
119  $this->setRevisionInternal( $revision );
120 
121  $this->combineOutput = $combineOutput;
122  $this->saveParseLogger = new NullLogger();
123 
125  throw new InvalidArgumentException(
126  'User must be specified when setting audience to FOR_THIS_USER'
127  );
128  }
129 
130  $this->audience = $audience;
131  $this->forUser = $forUser;
132  }
133 
137  public function setSaveParseLogger( LoggerInterface $saveParseLogger ) {
138  $this->saveParseLogger = $saveParseLogger;
139  }
140 
144  public function isContentDeleted() {
145  return $this->revision->isDeleted( RevisionRecord::DELETED_TEXT );
146  }
147 
151  public function getRevision() {
152  return $this->revision;
153  }
154 
158  public function getOptions() {
159  return $this->options;
160  }
161 
173  $this->revisionOutput = $output;
174 
175  // If there is only one slot, we assume that the combined output is identical
176  // with the main slot's output. This is intended to prevent a redundant re-parse of
177  // the content in case getSlotParserOutput( SlotRecord::MAIN ) is called, for instance
178  // from ContentHandler::getSecondaryDataUpdates.
179  if ( $this->revision->getSlotRoles() === [ SlotRecord::MAIN ] ) {
180  $this->slotsOutput[ SlotRecord::MAIN ] = $output;
181  }
182  }
183 
191  public function getRevisionParserOutput( array $hints = [] ) {
192  $withHtml = $hints['generate-html'] ?? true;
193 
194  if ( !$this->revisionOutput
195  || ( $withHtml && !$this->revisionOutput->hasText() )
196  ) {
197  $output = call_user_func( $this->combineOutput, $this, $hints );
198 
199  Assert::postcondition(
200  $output instanceof ParserOutput,
201  'Callback did not return a ParserOutput object!'
202  );
203 
204  $this->revisionOutput = $output;
205  }
206 
207  return $this->revisionOutput;
208  }
209 
220  public function getSlotParserOutput( $role, array $hints = [] ) {
221  $withHtml = $hints['generate-html'] ?? true;
222 
223  if ( !isset( $this->slotsOutput[ $role ] )
224  || ( $withHtml && !$this->slotsOutput[ $role ]->hasText() )
225  ) {
226  $content = $this->revision->getContent( $role, $this->audience, $this->forUser );
227 
228  if ( !$content ) {
229  throw new SuppressedDataException(
230  'Access to the content has been suppressed for this audience'
231  );
232  } else {
233  // XXX: allow SlotRoleHandler to control the ParserOutput?
234  $output = $this->getSlotParserOutputUncached( $content, $withHtml );
235 
236  if ( $withHtml && !$output->hasText() ) {
237  throw new LogicException(
238  'HTML generation was requested, but '
239  . get_class( $content )
240  . '::getParserOutput() returns a ParserOutput with no text set.'
241  );
242  }
243 
244  // Detach watcher, to ensure option use is not recorded in the wrong ParserOutput.
245  $this->options->registerWatcher( null );
246  }
247 
248  $this->slotsOutput[ $role ] = $output;
249  }
250 
251  return $this->slotsOutput[$role];
252  }
253 
260  private function getSlotParserOutputUncached( Content $content, $withHtml ) {
261  return $content->getParserOutput(
262  $this->title,
263  $this->revision->getId(),
265  $withHtml
266  );
267  }
268 
278  public function updateRevision( RevisionRecord $rev ) {
279  if ( $rev->getId() === $this->revision->getId() ) {
280  return;
281  }
282 
283  if ( $this->revision->getId() ) {
284  throw new LogicException( 'RenderedRevision already has a revision with ID '
285  . $this->revision->getId(), ', can\'t update to revision with ID ' . $rev->getId() );
286  }
287 
288  if ( !$this->revision->getSlots()->hasSameContent( $rev->getSlots() ) ) {
289  throw new LogicException( 'Cannot update to a revision with different content!' );
290  }
291 
292  $this->setRevisionInternal( $rev );
293 
295  $this->revision->getId(),
296  $this->revision->getTimestamp()
297  );
298  }
299 
309  private function pruneRevisionSensitiveOutput( $actualRevId, $actualRevTimestamp ) {
310  if ( $this->revisionOutput ) {
311  if ( $this->outputVariesOnRevisionMetaData(
312  $this->revisionOutput,
313  $actualRevId,
314  $actualRevTimestamp
315  ) ) {
316  $this->revisionOutput = null;
317  }
318  } else {
319  $this->saveParseLogger->debug( __METHOD__ . ": no prepared revision output...\n" );
320  }
321 
322  foreach ( $this->slotsOutput as $role => $output ) {
323  if ( $this->outputVariesOnRevisionMetaData(
324  $output,
325  $actualRevId,
326  $actualRevTimestamp
327  ) ) {
328  unset( $this->slotsOutput[$role] );
329  }
330  }
331  }
332 
337  $this->revision = $revision;
338 
339  // Force the parser to use $this->revision to resolve magic words like {{REVISIONUSER}}
340  // if the revision is either known to be complete, or it doesn't have a revision ID set.
341  // If it's incomplete and we have a revision ID, the parser can do better by loading
342  // the revision from the database if needed to handle a magic word.
343  //
344  // The following considerations inform the logic described above:
345  //
346  // 1) If we have a saved revision already loaded, we want the parser to use it, instead of
347  // loading it again.
348  //
349  // 2) If the revision is a fake that wraps some kind of synthetic content, such as an
350  // error message from Article, it should be used directly and things like {{REVISIONUSER}}
351  // should not expected to work, since there may not even be an actual revision to
352  // refer to.
353  //
354  // 3) If the revision is a fake constructed around a Title, a Content object, and
355  // a revision ID, to provide backwards compatibility to code that has access to those
356  // but not to a complete RevisionRecord for rendering, then we want the Parser to
357  // load the actual revision from the database when it encounters a magic word like
358  // {{REVISIONUSER}}, but we don't want to load that revision ahead of time just in case.
359  //
360  // 4) Previewing an edit to a template should use the submitted unsaved
361  // MutableRevisionRecord for self-transclusions in the template's documentation (see T7278).
362  // That revision would be complete except for the ID field.
363  //
364  // 5) Pre-save transform would provide a RevisionRecord that has all meta-data but is
365  // incomplete due to not yet having content set. However, since it doesn't have a revision
366  // ID either, the below code would still force it to be used, allowing
367  // {{subst::REVISIONUSER}} to function as expected.
368 
369  if ( $this->revision->isReadyForInsertion() || !$this->revision->getId() ) {
371  $oldCallback = $this->options->getCurrentRevisionCallback();
372  $this->options->setCurrentRevisionCallback(
373  function ( Title $parserTitle, $parser = false ) use ( $title, $oldCallback ) {
374  if ( $title->equals( $parserTitle ) ) {
375  $legacyRevision = new Revision( $this->revision );
376  return $legacyRevision;
377  } else {
378  return call_user_func( $oldCallback, $parserTitle, $parser );
379  }
380  }
381  );
382  }
383  }
384 
397  $actualRevId,
398  $actualRevTimestamp
399  ) {
400  $method = __METHOD__;
401 
402  if ( $out->getFlag( 'vary-revision' ) ) {
403  // If {{PAGEID}} resolved to 0, then that word need to resolve to the actual page ID
404  $this->saveParseLogger->info(
405  "$method: Prepared output has vary-revision..."
406  );
407  return true;
408  } elseif ( $out->getFlag( 'vary-revision-id' )
409  && $actualRevId !== false
410  && ( $actualRevId === true || $out->getSpeculativeRevIdUsed() !== $actualRevId )
411  ) {
412  $this->saveParseLogger->info(
413  "$method: Prepared output has vary-revision-id with wrong ID..."
414  );
415  return true;
416  } elseif ( $out->getFlag( 'vary-revision-timestamp' )
417  && $actualRevTimestamp !== false
418  && ( $actualRevTimestamp === true ||
419  $out->getRevisionTimestampUsed() !== $actualRevTimestamp )
420  ) {
421  $this->saveParseLogger->info(
422  "$method: Prepared output has vary-revision-timestamp with wrong timestamp..."
423  );
424  return true;
425  } elseif ( $out->getFlag( 'vary-revision-exists' ) ) {
426  // If {{REVISIONID}} resolved to '', it now needs to resolve to '-'.
427  // Note that edit stashing always uses '-', which can be used for both
428  // edit filter checks and canonical parser cache.
429  $this->saveParseLogger->info(
430  "$method: Prepared output has vary-revision-exists..."
431  );
432  return true;
433  } else {
434  // NOTE: In the original fix for T135261, the output was discarded if 'vary-user' was
435  // set for a null-edit. The reason was that the original rendering in that case was
436  // targeting the user making the null-edit, not the user who made the original edit,
437  // causing {{REVISIONUSER}} to return the wrong name.
438  // This case is now expected to be handled by the code in RevisionRenderer that
439  // constructs the ParserOptions: For a null-edit, setCurrentRevisionCallback is called
440  // with the old, existing revision.
441 
442  $this->saveParseLogger->debug( "$method: Keeping prepared output..." );
443  return false;
444  }
445  }
446 
447 }
setRevisionInternal(RevisionRecord $revision)
A lazy provider of ParserOutput objects for a revision&#39;s individual slots.
RenderedRevision represents the rendered representation of a revision.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
equals(LinkTarget $title)
Compare with another title.
Definition: Title.php:3985
getSlots()
Returns the slots defined for this revision.
LoggerInterface $saveParseLogger
For profiling ParserOutput re-use.
getSlotParserOutput( $role, array $hints=[])
setRevisionParserOutput(ParserOutput $output)
Sets a ParserOutput to be returned by getRevisionParserOutput().
outputVariesOnRevisionMetaData(ParserOutput $out, $actualRevId, $actualRevTimestamp)
ParserOutput null $revisionOutput
The combined ParserOutput for the revision, initialized lazily by getRevisionParserOutput().
title
see documentation in includes Linker php for Linker::makeImageLink or false for current used if you return false $parser
Definition: hooks.txt:1799
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title e g db for database replication lag or jobqueue for job queue size converted to pseudo seconds It is possible to add more fields and they will be returned to the user in the API response after the basic globals have been set but before ordinary actions take place $output
Definition: hooks.txt:2217
setSaveParseLogger(LoggerInterface $saveParseLogger)
The User object encapsulates all of the user-specific settings (user_id, name, rights, email address, options, last login time).
Definition: User.php:51
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password 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 $out
Definition: hooks.txt:780
Created by PhpStorm.
int $audience
Audience to check when accessing content.
getSlotParserOutputUncached(Content $content, $withHtml)
callable $combineOutput
Callback for combining slot output into revision output.
__construct(Title $title, RevisionRecord $revision, ParserOptions $options, callable $combineOutput, $audience=RevisionRecord::FOR_PUBLIC, User $forUser=null)
Exception raised in response to an audience check when attempting to access suppressed information wi...
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:780
pruneRevisionSensitiveOutput( $actualRevId, $actualRevTimestamp)
Prune any output that depends on the revision ID.
presenting them properly to the user as errors is done by the caller return true use this to change the list i e etc $rev
Definition: hooks.txt:1766
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
getId()
Get revision ID.
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
Using a hook running we can avoid having all this option specific stuff in our mainline code Using the function We ve cleaned up the code here by removing clumps of infrequently used code and moving them off somewhere else It s much easier for someone working with this code to see what s _really_ going and make changes or fix bugs In we can take all the code that deals with the little used title reversing options(say) and put it in one place. Instead of having little title-reversing if-blocks spread all over the codebase in showAnArticle
updateRevision(RevisionRecord $rev)
Updates the RevisionRecord after the revision has been saved.
In both all secondary updates will be triggered handle like object that caches derived data representing a revision
Definition: pageupdater.txt:78
getRevisionParserOutput(array $hints=[])
Page revision base class.
getParserOutput(Title $title, $revId=null, ParserOptions $options=null, $generateHtml=true)
Parse the Content object and generate a ParserOutput from the result.
getFlag( $flag)
User null $forUser
The user to use for audience checks during content access.
getRevisionTimestampUsed()
$content
Definition: pageupdater.txt:72
ParserOutput [] $slotsOutput
The ParserOutput for each slot, initialized lazily by getSlotParserOutput().