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->getPageId(),
296  $this->revision->getId(),
297  $this->revision->getTimestamp()
298  );
299  }
300 
315  $actualPageId,
316  $actualRevId,
317  $actualRevTimestamp
318  ) {
319  if ( $this->revisionOutput ) {
320  if ( $this->outputVariesOnRevisionMetaData(
321  $this->revisionOutput,
322  $actualPageId,
323  $actualRevId,
324  $actualRevTimestamp
325  ) ) {
326  $this->revisionOutput = null;
327  }
328  } else {
329  $this->saveParseLogger->debug( __METHOD__ . ": no prepared revision output" );
330  }
331 
332  foreach ( $this->slotsOutput as $role => $output ) {
333  if ( $this->outputVariesOnRevisionMetaData(
334  $output,
335  $actualPageId,
336  $actualRevId,
337  $actualRevTimestamp
338  ) ) {
339  unset( $this->slotsOutput[$role] );
340  }
341  }
342  }
343 
348  $this->revision = $revision;
349 
350  // Force the parser to use $this->revision to resolve magic words like {{REVISIONUSER}}
351  // if the revision is either known to be complete, or it doesn't have a revision ID set.
352  // If it's incomplete and we have a revision ID, the parser can do better by loading
353  // the revision from the database if needed to handle a magic word.
354  //
355  // The following considerations inform the logic described above:
356  //
357  // 1) If we have a saved revision already loaded, we want the parser to use it, instead of
358  // loading it again.
359  //
360  // 2) If the revision is a fake that wraps some kind of synthetic content, such as an
361  // error message from Article, it should be used directly and things like {{REVISIONUSER}}
362  // should not expected to work, since there may not even be an actual revision to
363  // refer to.
364  //
365  // 3) If the revision is a fake constructed around a Title, a Content object, and
366  // a revision ID, to provide backwards compatibility to code that has access to those
367  // but not to a complete RevisionRecord for rendering, then we want the Parser to
368  // load the actual revision from the database when it encounters a magic word like
369  // {{REVISIONUSER}}, but we don't want to load that revision ahead of time just in case.
370  //
371  // 4) Previewing an edit to a template should use the submitted unsaved
372  // MutableRevisionRecord for self-transclusions in the template's documentation (see T7278).
373  // That revision would be complete except for the ID field.
374  //
375  // 5) Pre-save transform would provide a RevisionRecord that has all meta-data but is
376  // incomplete due to not yet having content set. However, since it doesn't have a revision
377  // ID either, the below code would still force it to be used, allowing
378  // {{subst::REVISIONUSER}} to function as expected.
379 
380  if ( $this->revision->isReadyForInsertion() || !$this->revision->getId() ) {
382  $oldCallback = $this->options->getCurrentRevisionCallback();
383  $this->options->setCurrentRevisionCallback(
384  function ( Title $parserTitle, $parser = false ) use ( $title, $oldCallback ) {
385  if ( $title->equals( $parserTitle ) ) {
386  $legacyRevision = new Revision( $this->revision );
387  return $legacyRevision;
388  } else {
389  return call_user_func( $oldCallback, $parserTitle, $parser );
390  }
391  }
392  );
393  }
394  }
395 
411  $actualPageId,
412  $actualRevId,
413  $actualRevTimestamp
414  ) {
415  $logger = $this->saveParseLogger;
416  $varyMsg = __METHOD__ . ": cannot use prepared output for '{title}'";
417  $context = [ 'title' => $this->title->getPrefixedText() ];
418 
419  if ( $out->getFlag( 'vary-revision' ) ) {
420  // If {{PAGEID}} resolved to 0, then that word need to resolve to the actual page ID
421  $logger->info( "$varyMsg (vary-revision)", $context );
422  return true;
423  } elseif (
424  $out->getFlag( 'vary-revision-id' )
425  && $actualRevId !== false
426  && ( $actualRevId === true || $out->getSpeculativeRevIdUsed() !== $actualRevId )
427  ) {
428  $logger->info( "$varyMsg (vary-revision-id and wrong ID)", $context );
429  return true;
430  } elseif (
431  $out->getFlag( 'vary-revision-timestamp' )
432  && $actualRevTimestamp !== false
433  && ( $actualRevTimestamp === true ||
434  $out->getRevisionTimestampUsed() !== $actualRevTimestamp )
435  ) {
436  $logger->info( "$varyMsg (vary-revision-timestamp and wrong timestamp)", $context );
437  return true;
438  } elseif (
439  $out->getFlag( 'vary-page-id' )
440  && $actualPageId !== false
441  && ( $actualPageId === true || $out->getSpeculativePageIdUsed() !== $actualPageId )
442  ) {
443  $logger->info( "$varyMsg (vary-page-id and wrong ID)", $context );
444  return true;
445  } elseif ( $out->getFlag( 'vary-revision-exists' ) ) {
446  // If {{REVISIONID}} resolved to '', it now needs to resolve to '-'.
447  // Note that edit stashing always uses '-', which can be used for both
448  // edit filter checks and canonical parser cache.
449  $logger->info( "$varyMsg (vary-revision-exists)", $context );
450  return true;
451  } elseif (
452  $out->getFlag( 'vary-revision-sha1' ) &&
453  $out->getRevisionUsedSha1Base36() !== $this->revision->getSha1()
454  ) {
455  // If a self-transclusion used the proposed page text, it must match the final
456  // page content after PST transformations and automatically merged edit conflicts
457  $logger->info( "$varyMsg (vary-revision-sha1 with wrong SHA-1)", $context );
458  return true;
459  }
460 
461  // NOTE: In the original fix for T135261, the output was discarded if 'vary-user' was
462  // set for a null-edit. The reason was that the original rendering in that case was
463  // targeting the user making the null-edit, not the user who made the original edit,
464  // causing {{REVISIONUSER}} to return the wrong name.
465  // This case is now expected to be handled by the code in RevisionRenderer that
466  // constructs the ParserOptions: For a null-edit, setCurrentRevisionCallback is called
467  // with the old, existing revision.
468  $logger->debug( __METHOD__ . ": reusing prepared output for '{title}'", $context );
469  return false;
470  }
471 }
pruneRevisionSensitiveOutput( $actualPageId, $actualRevId, $actualRevTimestamp)
Prune any output that depends on the revision ID.
setRevisionInternal(RevisionRecord $revision)
A lazy provider of ParserOutput objects for a revision&#39;s individual slots.
getRevisionUsedSha1Base36()
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:4008
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, $actualPageId, $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:1781
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:2205
getSpeculativePageIdUsed()
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:767
Created by PhpStorm.
int $audience
Audience to check when accessing content.
IContextSource $context
Definition: MediaWiki.php:38
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:767
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:1748
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().