MediaWiki  master
RenderedRevision.php
Go to the documentation of this file.
1 <?php
23 namespace MediaWiki\Revision;
24 
25 use Content;
26 use InvalidArgumentException;
27 use LogicException;
32 use ParserOptions;
33 use ParserOutput;
34 use Psr\Log\LoggerInterface;
35 use Psr\Log\NullLogger;
36 use Wikimedia\Assert\Assert;
37 
46 
48  private $revision;
49 
53  private $options;
54 
58  private $audience = RevisionRecord::FOR_PUBLIC;
59 
63  private $performer = null;
64 
69  private $revisionOutput = null;
70 
75  private $slotsOutput = [];
76 
81  private $combineOutput;
82 
86  private $saveParseLogger;
87 
91  private $contentRenderer;
92 
109  public function __construct(
110  RevisionRecord $revision,
111  ParserOptions $options,
112  ContentRenderer $contentRenderer,
113  callable $combineOutput,
114  $audience = RevisionRecord::FOR_PUBLIC,
115  Authority $performer = null
116  ) {
117  $this->options = $options;
118 
119  $this->setRevisionInternal( $revision );
120 
121  $this->contentRenderer = $contentRenderer;
122  $this->combineOutput = $combineOutput;
123  $this->saveParseLogger = new NullLogger();
124 
125  if ( $audience === RevisionRecord::FOR_THIS_USER && !$performer ) {
126  throw new InvalidArgumentException(
127  'User must be specified when setting audience to FOR_THIS_USER'
128  );
129  }
130 
131  $this->audience = $audience;
132  $this->performer = $performer;
133  }
134 
138  public function setSaveParseLogger( LoggerInterface $saveParseLogger ) {
139  $this->saveParseLogger = $saveParseLogger;
140  }
141 
145  public function isContentDeleted() {
146  return $this->revision->isDeleted( RevisionRecord::DELETED_TEXT );
147  }
148 
152  public function getRevision() {
153  return $this->revision;
154  }
155 
159  public function getOptions() {
160  return $this->options;
161  }
162 
173  public function setRevisionParserOutput( ParserOutput $output ) {
174  $this->revisionOutput = $output;
175 
176  // If there is only one slot, we assume that the combined output is identical
177  // with the main slot's output. This is intended to prevent a redundant re-parse of
178  // the content in case getSlotParserOutput( SlotRecord::MAIN ) is called, for instance
179  // from ContentHandler::getSecondaryDataUpdates.
180  if ( $this->revision->getSlotRoles() === [ SlotRecord::MAIN ] ) {
181  $this->slotsOutput[ SlotRecord::MAIN ] = $output;
182  }
183  }
184 
193  public function getRevisionParserOutput( array $hints = [] ) {
194  $withHtml = $hints['generate-html'] ?? true;
195 
196  if ( !$this->revisionOutput
197  || ( $withHtml && !$this->revisionOutput->hasText() )
198  ) {
199  $output = call_user_func( $this->combineOutput, $this, $hints );
200 
201  Assert::postcondition(
202  $output instanceof ParserOutput,
203  'Callback did not return a ParserOutput object!'
204  );
205 
206  $this->revisionOutput = $output;
207  }
208 
209  return $this->revisionOutput;
210  }
211 
223  public function getSlotParserOutput( $role, array $hints = [] ) {
224  $withHtml = $hints['generate-html'] ?? true;
225 
226  if ( !isset( $this->slotsOutput[ $role ] )
227  || ( $withHtml && !$this->slotsOutput[ $role ]->hasText() )
228  ) {
229  $content = $this->revision->getContentOrThrow( $role, $this->audience, $this->performer );
230 
231  // XXX: allow SlotRoleHandler to control the ParserOutput?
232  $output = $this->getSlotParserOutputUncached( $content, $withHtml );
233 
234  if ( $withHtml && !$output->hasText() ) {
235  throw new LogicException(
236  'HTML generation was requested, but '
237  . get_class( $content )
238  . ' that passed to '
239  . 'ContentRenderer::getParserOutput() returns a ParserOutput with no text set.'
240  );
241  }
242 
243  // Detach watcher, to ensure option use is not recorded in the wrong ParserOutput.
244  $this->options->registerWatcher( null );
245 
246  $this->slotsOutput[ $role ] = $output;
247  }
248 
249  return $this->slotsOutput[$role];
250  }
251 
258  private function getSlotParserOutputUncached( Content $content, $withHtml ) {
259  $parserOutput = $this->contentRenderer->getParserOutput(
260  $content,
261  $this->revision->getPage(),
262  $this->revision->getId(),
263  $this->options,
264  $withHtml
265  );
266  // Save the rev_id and timestamp so that we don't have to load the revision row on view
267  $parserOutput->setCacheRevisionId( $this->revision->getId() );
268  $parserOutput->setTimestamp( $this->revision->getTimestamp() );
269  return $parserOutput;
270  }
271 
281  public function updateRevision( RevisionRecord $rev ) {
282  if ( $rev->getId() === $this->revision->getId() ) {
283  return;
284  }
285 
286  if ( $this->revision->getId() ) {
287  throw new LogicException( 'RenderedRevision already has a revision with ID '
288  . $this->revision->getId() . ', can\'t update to revision with ID ' . $rev->getId() );
289  }
290 
291  if ( !$this->revision->getSlots()->hasSameContent( $rev->getSlots() ) ) {
292  throw new LogicException( 'Cannot update to a revision with different content!' );
293  }
294 
295  $this->setRevisionInternal( $rev );
296 
297  $this->pruneRevisionSensitiveOutput(
298  $this->revision->getPageId(),
299  $this->revision->getId(),
300  $this->revision->getTimestamp()
301  );
302  }
303 
317  private function pruneRevisionSensitiveOutput(
318  $actualPageId,
319  $actualRevId,
320  $actualRevTimestamp
321  ) {
322  if ( $this->revisionOutput ) {
323  if ( $this->outputVariesOnRevisionMetaData(
324  $this->revisionOutput,
325  $actualPageId,
326  $actualRevId,
327  $actualRevTimestamp
328  ) ) {
329  $this->revisionOutput = null;
330  }
331  } else {
332  $this->saveParseLogger->debug( __METHOD__ . ": no prepared revision output" );
333  }
334 
335  foreach ( $this->slotsOutput as $role => $output ) {
336  if ( $this->outputVariesOnRevisionMetaData(
337  $output,
338  $actualPageId,
339  $actualRevId,
340  $actualRevTimestamp
341  ) ) {
342  unset( $this->slotsOutput[$role] );
343  }
344  }
345  }
346 
350  private function setRevisionInternal( RevisionRecord $revision ) {
351  $this->revision = $revision;
352 
353  // Force the parser to use $this->revision to resolve magic words like {{REVISIONUSER}}
354  // if the revision is either known to be complete, or it doesn't have a revision ID set.
355  // If it's incomplete and we have a revision ID, the parser can do better by loading
356  // the revision from the database if needed to handle a magic word.
357  //
358  // The following considerations inform the logic described above:
359  //
360  // 1) If we have a saved revision already loaded, we want the parser to use it, instead of
361  // loading it again.
362  //
363  // 2) If the revision is a fake that wraps some kind of synthetic content, such as an
364  // error message from Article, it should be used directly and things like {{REVISIONUSER}}
365  // should not expected to work, since there may not even be an actual revision to
366  // refer to.
367  //
368  // 3) If the revision is a fake constructed around a page, a Content object, and
369  // a revision ID, to provide backwards compatibility to code that has access to those
370  // but not to a complete RevisionRecord for rendering, then we want the Parser to
371  // load the actual revision from the database when it encounters a magic word like
372  // {{REVISIONUSER}}, but we don't want to load that revision ahead of time just in case.
373  //
374  // 4) Previewing an edit to a template should use the submitted unsaved
375  // MutableRevisionRecord for self-transclusions in the template's documentation (see T7278).
376  // That revision would be complete except for the ID field.
377  //
378  // 5) Pre-save transform would provide a RevisionRecord that has all meta-data but is
379  // incomplete due to not yet having content set. However, since it doesn't have a revision
380  // ID either, the below code would still force it to be used, allowing
381  // {{subst::REVISIONUSER}} to function as expected.
382 
383  if ( $this->revision->isReadyForInsertion() || !$this->revision->getId() ) {
384  $oldCallback = $this->options->getCurrentRevisionRecordCallback();
385  $this->options->setCurrentRevisionRecordCallback(
386  function ( PageReference $parserPage, $parser = null ) use ( $oldCallback ) {
387  if ( $this->revision->getPage()->isSamePageAs( $parserPage ) ) {
388  return $this->revision;
389  } else {
390  return call_user_func( $oldCallback, $parserPage, $parser );
391  }
392  }
393  );
394  }
395  }
396 
410  private function outputVariesOnRevisionMetaData(
411  ParserOutput $parserOutput,
412  $actualPageId,
413  $actualRevId,
414  $actualRevTimestamp
415  ) {
416  $logger = $this->saveParseLogger;
417  $varyMsg = __METHOD__ . ": cannot use prepared output for '{title}'";
418  $context = [ 'title' => (string)$this->revision->getPage() ];
419 
420  if ( $parserOutput->getOutputFlag( ParserOutputFlags::VARY_REVISION ) ) {
421  // If {{PAGEID}} resolved to 0, then that word need to resolve to the actual page ID
422  $logger->info( "$varyMsg (vary-revision)", $context );
423  return true;
424  } elseif (
425  $parserOutput->getOutputFlag( ParserOutputFlags::VARY_REVISION_ID )
426  && $actualRevId !== false
427  && ( $actualRevId === true || $parserOutput->getSpeculativeRevIdUsed() !== $actualRevId )
428  ) {
429  $logger->info( "$varyMsg (vary-revision-id and wrong ID)", $context );
430  return true;
431  } elseif (
432  $parserOutput->getOutputFlag( ParserOutputFlags::VARY_REVISION_TIMESTAMP )
433  && $actualRevTimestamp !== false
434  && ( $actualRevTimestamp === true ||
435  $parserOutput->getRevisionTimestampUsed() !== $actualRevTimestamp )
436  ) {
437  $logger->info( "$varyMsg (vary-revision-timestamp and wrong timestamp)", $context );
438  return true;
439  } elseif (
440  $parserOutput->getOutputFlag( ParserOutputFlags::VARY_PAGE_ID )
441  && $actualPageId !== false
442  && ( $actualPageId === true || $parserOutput->getSpeculativePageIdUsed() !== $actualPageId )
443  ) {
444  $logger->info( "$varyMsg (vary-page-id and wrong ID)", $context );
445  return true;
446  } elseif ( $parserOutput->getOutputFlag( ParserOutputFlags::VARY_REVISION_EXISTS ) ) {
447  // If {{REVISIONID}} resolved to '', it now needs to resolve to '-'.
448  // Note that edit stashing always uses '-', which can be used for both
449  // edit filter checks and canonical parser cache.
450  $logger->info( "$varyMsg (vary-revision-exists)", $context );
451  return true;
452  } elseif (
453  $parserOutput->getOutputFlag( ParserOutputFlags::VARY_REVISION_SHA1 ) &&
454  $parserOutput->getRevisionUsedSha1Base36() !== $this->revision->getSha1()
455  ) {
456  // If a self-transclusion used the proposed page text, it must match the final
457  // page content after PST transformations and automatically merged edit conflicts
458  $logger->info( "$varyMsg (vary-revision-sha1 with wrong SHA-1)", $context );
459  return true;
460  }
461 
462  // NOTE: In the original fix for T135261, the output was discarded if ParserOutputFlags::VARY_USER was
463  // set for a null-edit. The reason was that the original rendering in that case was
464  // targeting the user making the null-edit, not the user who made the original edit,
465  // causing {{REVISIONUSER}} to return the wrong name.
466  // This case is now expected to be handled by the code in RevisionRenderer that
467  // constructs the ParserOptions: For a null-edit, setCurrentRevisionRecordCallback is
468  // called with the old, existing revision.
469  $logger->debug( __METHOD__ . ": reusing prepared output for '{title}'", $context );
470  return false;
471  }
472 }
setCacheRevisionId( $id)
Definition: CacheTime.php:106
RenderedRevision represents the rendered representation of a revision.
__construct(RevisionRecord $revision, ParserOptions $options, ContentRenderer $contentRenderer, callable $combineOutput, $audience=RevisionRecord::FOR_PUBLIC, Authority $performer=null)
setRevisionParserOutput(ParserOutput $output)
Sets a ParserOutput to be returned by getRevisionParserOutput().
updateRevision(RevisionRecord $rev)
Updates the RevisionRecord after the revision has been saved.
setSaveParseLogger(LoggerInterface $saveParseLogger)
getSlotParserOutput( $role, array $hints=[])
Page revision base class.
getSlots()
Returns the slots defined for this revision.
getId( $wikiId=self::LOCAL)
Get revision ID.
Set options of the Parser.
getRevisionTimestampUsed()
getRevisionUsedSha1Base36()
getSpeculativePageIdUsed()
getOutputFlag(string $name)
Provides a uniform interface to various boolean flags stored in the ParserOutput.
setTimestamp( $timestamp)
Base interface for representing page content.
Definition: Content.php:37
Interface for objects (potentially) representing a page that can be viewable and linked to on a wiki.
This interface represents the authority associated the current execution context, such as a web reque...
Definition: Authority.php:37
A lazy provider of ParserOutput objects for a revision's individual slots.
$content
Definition: router.php:76