MediaWiki  master
RevisionRenderer.php
Go to the documentation of this file.
1 <?php
23 namespace MediaWiki\Revision;
24 
25 use Html;
31 use Title;
32 use User;
34 
46 
49 
51  private $loadBalancer;
52 
54  private $roleRegistery;
55 
57  private $wikiId;
58 
64  public function __construct(
65  ILoadBalancer $loadBalancer,
66  SlotRoleRegistry $roleRegistry,
67  $wikiId = false
68  ) {
69  $this->loadBalancer = $loadBalancer;
70  $this->roleRegistery = $roleRegistry;
71  $this->wikiId = $wikiId;
72 
73  $this->saveParseLogger = new NullLogger();
74  }
75 
79  public function setLogger( LoggerInterface $saveParseLogger ) {
80  $this->saveParseLogger = $saveParseLogger;
81  }
82 
102  public function getRenderedRevision(
105  User $forUser = null,
106  array $hints = []
107  ) {
108  if ( $rev->getWikiId() !== $this->wikiId ) {
109  throw new InvalidArgumentException( 'Mismatching wiki ID ' . $rev->getWikiId() );
110  }
111 
112  $audience = $hints['audience']
114 
115  if ( !$rev->audienceCan( RevisionRecord::DELETED_TEXT, $audience, $forUser ) ) {
116  // Returning null here is awkward, but consist with the signature of
117  // Revision::getContent() and RevisionRecord::getContent().
118  return null;
119  }
120 
121  if ( !$options ) {
122  $options = ParserOptions::newCanonical( $forUser ?: 'canonical' );
123  }
124 
125  $useMaster = $hints['use-master'] ?? false;
126 
127  $dbIndex = $useMaster
128  ? DB_MASTER // use latest values
129  : DB_REPLICA; // T154554
130 
131  $options->setSpeculativeRevIdCallback( function () use ( $dbIndex ) {
132  return $this->getSpeculativeRevId( $dbIndex );
133  } );
134 
135  if ( !$rev->getId() && $rev->getTimestamp() ) {
136  // This is an unsaved revision with an already determined timestamp.
137  // Make the "current" time used during parsing match that of the revision.
138  // Any REVISION* parser variables will match up if the revision is saved.
139  $options->setTimestamp( $rev->getTimestamp() );
140  }
141 
143 
144  $renderedRevision = new RenderedRevision(
145  $title,
146  $rev,
147  $options,
148  function ( RenderedRevision $rrev, array $hints ) {
149  return $this->combineSlotOutput( $rrev, $hints );
150  },
151  $audience,
152  $forUser
153  );
154 
155  $renderedRevision->setSaveParseLogger( $this->saveParseLogger );
156 
157  if ( isset( $hints['known-revision-output'] ) ) {
158  $renderedRevision->setRevisionParserOutput( $hints['known-revision-output'] );
159  }
160 
161  return $renderedRevision;
162  }
163 
164  private function getSpeculativeRevId( $dbIndex ) {
165  // Use a fresh master connection in order to see the latest data, by avoiding
166  // stale data from REPEATABLE-READ snapshots.
167  // HACK: But don't use a fresh connection in unit tests, since it would not have
168  // the fake tables. This should be handled by the LoadBalancer!
169  $flags = defined( 'MW_PHPUNIT_TEST' ) || $dbIndex === DB_REPLICA
170  ? 0 : ILoadBalancer::CONN_TRX_AUTOCOMMIT;
171 
172  $db = $this->loadBalancer->getConnectionRef( $dbIndex, [], $this->wikiId, $flags );
173 
174  return 1 + (int)$db->selectField(
175  'revision',
176  'MAX(rev_id)',
177  [],
178  __METHOD__
179  );
180  }
181 
192  private function combineSlotOutput( RenderedRevision $rrev, array $hints = [] ) {
193  $revision = $rrev->getRevision();
194  $slots = $revision->getSlots()->getSlots();
195 
196  $withHtml = $hints['generate-html'] ?? true;
197 
198  // short circuit if there is only the main slot
199  if ( array_keys( $slots ) === [ SlotRecord::MAIN ] ) {
200  return $rrev->getSlotParserOutput( SlotRecord::MAIN );
201  }
202 
203  // move main slot to front
204  if ( isset( $slots[SlotRecord::MAIN] ) ) {
205  $slots = [ SlotRecord::MAIN => $slots[SlotRecord::MAIN] ] + $slots;
206  }
207 
208  $combinedOutput = new ParserOutput( null );
209  $slotOutput = [];
210 
211  $options = $rrev->getOptions();
212  $options->registerWatcher( [ $combinedOutput, 'recordOption' ] );
213 
214  foreach ( $slots as $role => $slot ) {
215  $out = $rrev->getSlotParserOutput( $role, $hints );
216  $slotOutput[$role] = $out;
217 
218  // XXX: should the SlotRoleHandler be able to intervene here?
219  $combinedOutput->mergeInternalMetaDataFrom( $out, $role );
220  $combinedOutput->mergeTrackingMetaDataFrom( $out );
221  }
222 
223  if ( $withHtml ) {
224  $html = '';
225  $first = true;
227  foreach ( $slotOutput as $role => $out ) {
228  $roleHandler = $this->roleRegistery->getRoleHandler( $role );
229 
230  // TODO: put more fancy layout logic here, see T200915.
231  $layout = $roleHandler->getOutputLayoutHints();
232  $display = $layout['display'] ?? 'section';
233 
234  if ( $display === 'none' ) {
235  continue;
236  }
237 
238  if ( $first ) {
239  // skip header for the first slot
240  $first = false;
241  } else {
242  // NOTE: this placeholder is hydrated by ParserOutput::getText().
243  $headText = Html::element( 'mw:slotheader', [], $role );
244  $html .= Html::rawElement( 'h1', [ 'class' => 'mw-slot-header' ], $headText );
245  }
246 
247  // XXX: do we want to put a wrapper div around the output?
248  // Do we want to let $roleHandler do that?
249  $html .= $out->getRawText();
250  $combinedOutput->mergeHtmlMetaDataFrom( $out );
251  }
252 
253  $combinedOutput->setText( $html );
254  }
255 
256  $options->registerWatcher( null );
257  return $combinedOutput;
258  }
259 
260 }
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses & $html
Definition: hooks.txt:1982
combineSlotOutput(RenderedRevision $rrev, array $hints=[])
This implements the layout for combining the output of multiple slots.
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:232
RenderedRevision represents the rendered representation of a revision.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
The RevisionRenderer service provides access to rendered output for revisions.
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:210
A registry service for SlotRoleHandlers, used to define which slot roles are available on which page...
getSlotParserOutput( $role, array $hints=[])
setLogger(LoggerInterface $saveParseLogger)
const DB_MASTER
Definition: defines.php:26
setSaveParseLogger(LoggerInterface $saveParseLogger)
static newCanonical( $context=null, $userLang=null)
Creates a "canonical" ParserOptions object.
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
__construct(ILoadBalancer $loadBalancer, SlotRoleRegistry $roleRegistry, $wikiId=false)
Created by PhpStorm.
LoggerInterface $saveParseLogger
SlotRoleRegistry $roleRegistery
getPageAsLinkTarget()
Returns the title of the page this revision is associated with as a LinkTarget object.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition: hooks.txt:1982
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
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:925
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
static newFromLinkTarget(LinkTarget $linkTarget, $forceClone='')
Returns a Title given a LinkTarget.
Definition: Title.php:271
audienceCan( $field, $audience, User $user=null)
Check that the given audience has access to the given field.
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
getRenderedRevision(RevisionRecord $rev, ParserOptions $options=null, User $forUser=null, array $hints=[])
getTimestamp()
MCR migration note: this replaces Revision::getTimestamp.
getWikiId()
Get the ID of the wiki this revision belongs to.
Page revision base class.
const DB_REPLICA
Definition: defines.php:25