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 $dbDomain;
58 
64  public function __construct(
65  ILoadBalancer $loadBalancer,
66  SlotRoleRegistry $roleRegistry,
67  $dbDomain = false
68  ) {
69  $this->loadBalancer = $loadBalancer;
70  $this->roleRegistery = $roleRegistry;
71  $this->dbDomain = $dbDomain;
72  $this->saveParseLogger = new NullLogger();
73  }
74 
78  public function setLogger( LoggerInterface $saveParseLogger ) {
79  $this->saveParseLogger = $saveParseLogger;
80  }
81 
101  public function getRenderedRevision(
104  User $forUser = null,
105  array $hints = []
106  ) {
107  if ( $rev->getWikiId() !== $this->dbDomain ) {
108  throw new InvalidArgumentException( 'Mismatching wiki ID ' . $rev->getWikiId() );
109  }
110 
111  $audience = $hints['audience']
113 
114  if ( !$rev->audienceCan( RevisionRecord::DELETED_TEXT, $audience, $forUser ) ) {
115  // Returning null here is awkward, but consist with the signature of
116  // Revision::getContent() and RevisionRecord::getContent().
117  return null;
118  }
119 
120  if ( !$options ) {
121  $options = ParserOptions::newCanonical( $forUser ?: 'canonical' );
122  }
123 
124  $useMaster = $hints['use-master'] ?? false;
125 
126  $dbIndex = $useMaster
127  ? DB_MASTER // use latest values
128  : DB_REPLICA; // T154554
129 
130  $options->setSpeculativeRevIdCallback( function () use ( $dbIndex ) {
131  return $this->getSpeculativeRevId( $dbIndex );
132  } );
133  $options->setSpeculativePageIdCallback( function () use ( $dbIndex ) {
134  return $this->getSpeculativePageId( $dbIndex );
135  } );
136 
137  if ( !$rev->getId() && $rev->getTimestamp() ) {
138  // This is an unsaved revision with an already determined timestamp.
139  // Make the "current" time used during parsing match that of the revision.
140  // Any REVISION* parser variables will match up if the revision is saved.
141  $options->setTimestamp( $rev->getTimestamp() );
142  }
143 
145 
146  $renderedRevision = new RenderedRevision(
147  $title,
148  $rev,
149  $options,
150  function ( RenderedRevision $rrev, array $hints ) {
151  return $this->combineSlotOutput( $rrev, $hints );
152  },
153  $audience,
154  $forUser
155  );
156 
157  $renderedRevision->setSaveParseLogger( $this->saveParseLogger );
158 
159  if ( isset( $hints['known-revision-output'] ) ) {
160  $renderedRevision->setRevisionParserOutput( $hints['known-revision-output'] );
161  }
162 
163  return $renderedRevision;
164  }
165 
166  private function getSpeculativeRevId( $dbIndex ) {
167  // Use a separate master connection in order to see the latest data, by avoiding
168  // stale data from REPEATABLE-READ snapshots.
169  $flags = ILoadBalancer::CONN_TRX_AUTOCOMMIT;
170 
171  $db = $this->loadBalancer->getConnectionRef( $dbIndex, [], $this->dbDomain, $flags );
172 
173  return 1 + (int)$db->selectField(
174  'revision',
175  'MAX(rev_id)',
176  [],
177  __METHOD__
178  );
179  }
180 
181  private function getSpeculativePageId( $dbIndex ) {
182  // Use a separate master connection in order to see the latest data, by avoiding
183  // stale data from REPEATABLE-READ snapshots.
184  $flags = ILoadBalancer::CONN_TRX_AUTOCOMMIT;
185 
186  $db = $this->loadBalancer->getConnectionRef( $dbIndex, [], $this->dbDomain, $flags );
187 
188  return 1 + (int)$db->selectField(
189  'page',
190  'MAX(page_id)',
191  [],
192  __METHOD__
193  );
194  }
195 
206  private function combineSlotOutput( RenderedRevision $rrev, array $hints = [] ) {
207  $revision = $rrev->getRevision();
208  $slots = $revision->getSlots()->getSlots();
209 
210  $withHtml = $hints['generate-html'] ?? true;
211 
212  // short circuit if there is only the main slot
213  if ( array_keys( $slots ) === [ SlotRecord::MAIN ] ) {
214  return $rrev->getSlotParserOutput( SlotRecord::MAIN );
215  }
216 
217  // move main slot to front
218  if ( isset( $slots[SlotRecord::MAIN] ) ) {
219  $slots = [ SlotRecord::MAIN => $slots[SlotRecord::MAIN] ] + $slots;
220  }
221 
222  $combinedOutput = new ParserOutput( null );
223  $slotOutput = [];
224 
225  $options = $rrev->getOptions();
226  $options->registerWatcher( [ $combinedOutput, 'recordOption' ] );
227 
228  foreach ( $slots as $role => $slot ) {
229  $out = $rrev->getSlotParserOutput( $role, $hints );
230  $slotOutput[$role] = $out;
231 
232  // XXX: should the SlotRoleHandler be able to intervene here?
233  $combinedOutput->mergeInternalMetaDataFrom( $out );
234  $combinedOutput->mergeTrackingMetaDataFrom( $out );
235  }
236 
237  if ( $withHtml ) {
238  $html = '';
239  $first = true;
241  foreach ( $slotOutput as $role => $out ) {
242  $roleHandler = $this->roleRegistery->getRoleHandler( $role );
243 
244  // TODO: put more fancy layout logic here, see T200915.
245  $layout = $roleHandler->getOutputLayoutHints();
246  $display = $layout['display'] ?? 'section';
247 
248  if ( $display === 'none' ) {
249  continue;
250  }
251 
252  if ( $first ) {
253  // skip header for the first slot
254  $first = false;
255  } else {
256  // NOTE: this placeholder is hydrated by ParserOutput::getText().
257  $headText = Html::element( 'mw:slotheader', [], $role );
258  $html .= Html::rawElement( 'h1', [ 'class' => 'mw-slot-header' ], $headText );
259  }
260 
261  // XXX: do we want to put a wrapper div around the output?
262  // Do we want to let $roleHandler do that?
263  $html .= $out->getRawText();
264  $combinedOutput->mergeHtmlMetaDataFrom( $out );
265  }
266 
267  $combinedOutput->setText( $html );
268  }
269 
270  $options->registerWatcher( null );
271  return $combinedOutput;
272  }
273 
274 }
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:1983
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:231
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:209
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:773
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:1983
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:773
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:918
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:1759
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:274
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
__construct(ILoadBalancer $loadBalancer, SlotRoleRegistry $roleRegistry, $dbDomain=false)