Debian Codegraph @

includes/Revision/RevisionRenderer.php

raw symbols SCIP
1 <?php
2 /**
3 * This file is part of MediaWiki.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 namespace MediaWiki\Revision;
24
25 use InvalidArgumentException;
26 use MediaWiki\Content\Renderer\ContentRenderer;
27 use MediaWiki\Html\Html;
28 use MediaWiki\Parser\ParserOptions;
29 use MediaWiki\Parser\ParserOutput;
30 use MediaWiki\Parser\ParserOutputFlags;
31 use MediaWiki\Permissions\Authority;
32 use Psr\Log\LoggerInterface;
33 use Psr\Log\NullLogger;
34 use Wikimedia\Rdbms\ILoadBalancer;
35
36 /**
37 * The RevisionRenderer service provides access to rendered output for revisions.
38 * It does so by acting as a factory for RenderedRevision instances, which in turn
39 * provide lazy access to ParserOutput objects.
40 *
41 * One key responsibility of RevisionRenderer is implementing the layout used to combine
42 * the output of multiple slots.
43 *
44 * @since 1.32
45 */
46 class RevisionRenderer {
47
48 /** @var LoggerInterface */
49 private $saveParseLogger;
50
51 /** @var ILoadBalancer */
52 private $loadBalancer;
53
54 /** @var SlotRoleRegistry */
55 private $roleRegistry;
56
57 /** @var ContentRenderer */
58 private $contentRenderer;
59
60 /** @var string|false */
61 private $dbDomain;
62
63 /**
64 * @param ILoadBalancer $loadBalancer
65 * @param SlotRoleRegistry $roleRegistry
66 * @param ContentRenderer $contentRenderer
67 * @param string|false $dbDomain DB domain of the relevant wiki or false for the current one
68 */
69 public function __construct(
70 ILoadBalancer $loadBalancer,
71 SlotRoleRegistry $roleRegistry,
72 ContentRenderer $contentRenderer,
73 $dbDomain = false
74 ) {
75 $this->loadBalancer = $loadBalancer;
76 $this->roleRegistry = $roleRegistry;
77 $this->contentRenderer = $contentRenderer;
78 $this->dbDomain = $dbDomain;
79 $this->saveParseLogger = new NullLogger();
80 }
81
82 /**
83 * @param LoggerInterface $saveParseLogger
84 */
85 public function setLogger( LoggerInterface $saveParseLogger ) {
86 $this->saveParseLogger = $saveParseLogger;
87 }
88
89 // phpcs:disable Generic.Files.LineLength.TooLong
90 /**
91 * @param RevisionRecord $rev
92 * @param ParserOptions|null $options
93 * @param Authority|null $forPerformer User for privileged access. Default is unprivileged
94 * (public) access, unless the 'audience' hint is set to something else RevisionRecord::RAW.
95 * @param array{use-master?:bool,audience?:int,known-revision-output?:ParserOutput,causeAction?:?string,previous-output?:?ParserOutput} $hints
96 * Hints given as an associative array. Known keys:
97 * - 'use-master' Use primary DB when rendering for the parser cache during save.
98 * Default is to use a replica.
99 * - 'audience' the audience to use for content access. Default is
100 * RevisionRecord::FOR_PUBLIC if $forUser is not set, RevisionRecord::FOR_THIS_USER
101 * if $forUser is set. Can be set to RevisionRecord::RAW to disable audience checks.
102 * - 'known-revision-output' a combined ParserOutput for the revision, perhaps from
103 * some cache. the caller is responsible for ensuring that the ParserOutput indeed
104 * matched the $rev and $options. This mechanism is intended as a temporary stop-gap,
105 * for the time until caches have been changed to store RenderedRevision states instead
106 * of ParserOutput objects.
107 * - 'previous-output' A previously-rendered ParserOutput for this page. This
108 * can be used by Parsoid for selective updates.
109 * - 'causeAction' the reason for rendering. This should be informative, for used for
110 * logging and debugging.
111 *
112 * @return RenderedRevision|null The rendered revision, or null if the audience checks fails.
113 * @throws BadRevisionException
114 * @throws RevisionAccessException
115 */
116 // phpcs:enable Generic.Files.LineLength.TooLong
117 public function getRenderedRevision(
118 RevisionRecord $rev,
119 ?ParserOptions $options = null,
120 ?Authority $forPerformer = null,
121 array $hints = []
122 ) {
123 if ( $rev->getWikiId() !== $this->dbDomain ) {
124 throw new InvalidArgumentException( 'Mismatching wiki ID ' . $rev->getWikiId() );
125 }
126
127 $audience = $hints['audience']
128 ?? ( $forPerformer ? RevisionRecord::FOR_THIS_USER : RevisionRecord::FOR_PUBLIC );
129
130 if ( !$rev->audienceCan( RevisionRecord::DELETED_TEXT, $audience, $forPerformer ) ) {
131 // Returning null here is awkward, but consistent with the signature of
132 // RevisionRecord::getContent().
133 return null;
134 }
135
136 if ( !$options ) {
137 $options = $forPerformer ?
138 ParserOptions::newFromUser( $forPerformer->getUser() ) :
139 ParserOptions::newFromAnon();
140 }
141
142 if ( isset( $hints['causeAction'] ) ) {
143 $options->setRenderReason( $hints['causeAction'] );
144 }
145
146 $usePrimary = $hints['use-master'] ?? false;
147
148 $dbIndex = $usePrimary
149 ? DB_PRIMARY // use latest values
150 : DB_REPLICA; // T154554
151
152 $options->setSpeculativeRevIdCallback( function () use ( $dbIndex ) {
153 return $this->getSpeculativeRevId( $dbIndex );
154 } );
155 $options->setSpeculativePageIdCallback( function () use ( $dbIndex ) {
156 return $this->getSpeculativePageId( $dbIndex );
157 } );
158
159 if ( !$rev->getId() && $rev->getTimestamp() ) {
160 // This is an unsaved revision with an already determined timestamp.
161 // Make the "current" time used during parsing match that of the revision.
162 // Any REVISION* parser variables will match up if the revision is saved.
163 $options->setTimestamp( $rev->getTimestamp() );
164 }
165
166 $previousOutput = $hints['previous-output'] ?? null;
167 $renderedRevision = new RenderedRevision(
168 $rev,
169 $options,
170 $this->contentRenderer,
171 function ( RenderedRevision $rrev, array $hints ) use ( $options, $previousOutput ) {
172 $h = [ 'previous-output' => $previousOutput ] + $hints;
173 return $this->combineSlotOutput( $rrev, $options, $h );
174 },
175 $audience,
176 $forPerformer
177 );
178
179 $renderedRevision->setSaveParseLogger( $this->saveParseLogger );
180
181 if ( isset( $hints['known-revision-output'] ) ) {
182 $renderedRevision->setRevisionParserOutput( $hints['known-revision-output'] );
183 }
184
185 return $renderedRevision;
186 }
187
188 private function getSpeculativeRevId( $dbIndex ) {
189 // Use a separate primary DB connection in order to see the latest data, by avoiding
190 // stale data from REPEATABLE-READ snapshots.
191 $flags = ILoadBalancer::CONN_TRX_AUTOCOMMIT;
192
193 $db = $this->loadBalancer->getConnection( $dbIndex, [], $this->dbDomain, $flags );
194
195 return 1 + (int)$db->newSelectQueryBuilder()
196 ->select( 'MAX(rev_id)' )
197 ->from( 'revision' )
198 ->caller( __METHOD__ )->fetchField();
199 }
200
201 private function getSpeculativePageId( $dbIndex ) {
202 // Use a separate primary DB connection in order to see the latest data, by avoiding
203 // stale data from REPEATABLE-READ snapshots.
204 $flags = ILoadBalancer::CONN_TRX_AUTOCOMMIT;
205
206 $db = $this->loadBalancer->getConnection( $dbIndex, [], $this->dbDomain, $flags );
207
208 return 1 + (int)$db->newSelectQueryBuilder()
209 ->select( 'MAX(page_id)' )
210 ->from( 'page' )
211 ->caller( __METHOD__ )->fetchField();
212 }
213
214 /**
215 * This implements the layout for combining the output of multiple slots.
216 *
217 * @todo Use placement hints from SlotRoleHandlers instead of hard-coding the layout.
218 *
219 * @param RenderedRevision $rrev
220 * @param ParserOptions $options
221 * @param array $hints see RenderedRevision::getRevisionParserOutput()
222 *
223 * @return ParserOutput
224 * @throws SuppressedDataException
225 * @throws BadRevisionException
226 * @throws RevisionAccessException
227 */
228 private function combineSlotOutput( RenderedRevision $rrev, ParserOptions $options, array $hints = [] ) {
229 $revision = $rrev->getRevision();
230 $slots = $revision->getSlots()->getSlots();
231
232 $withHtml = $hints['generate-html'] ?? true;
233 $previousOutputs = $this->splitSlotOutput( $rrev, $options, $hints['previous-output'] ?? null );
234
235 // short circuit if there is only the main slot
236 // T351026 hack: if use-parsoid is set, only return main slot output for now
237 // T351113 will remove this hack.
238 if ( array_keys( $slots ) === [ SlotRecord::MAIN ] || $options->getUseParsoid() ) {
239 $h = [ 'previous-output' => $previousOutputs[SlotRecord::MAIN] ] + $hints;
240 return $rrev->getSlotParserOutput( SlotRecord::MAIN, $h );
241 }
242
243 // move main slot to front
244 if ( isset( $slots[SlotRecord::MAIN] ) ) {
245 $slots = [ SlotRecord::MAIN => $slots[SlotRecord::MAIN] ] + $slots;
246 }
247
248 $combinedOutput = new ParserOutput( null );
249 $slotOutput = [];
250
251 $options = $rrev->getOptions();
252 $options->registerWatcher( [ $combinedOutput, 'recordOption' ] );
253
254 foreach ( $slots as $role => $slot ) {
255 $h = [ 'previous-output' => $previousOutputs[$role] ] + $hints;
256 $out = $rrev->getSlotParserOutput( $role, $h );
257 $slotOutput[$role] = $out;
258
259 // XXX: should the SlotRoleHandler be able to intervene here?
260 $combinedOutput->mergeInternalMetaDataFrom( $out );
261 $combinedOutput->mergeTrackingMetaDataFrom( $out );
262 }
263
264 if ( $withHtml ) {
265 $html = '';
266 $first = true;
267 /** @var ParserOutput $out */
268 foreach ( $slotOutput as $role => $out ) {
269 $roleHandler = $this->roleRegistry->getRoleHandler( $role );
270
271 // TODO: put more fancy layout logic here, see T200915.
272 $layout = $roleHandler->getOutputLayoutHints();
273 $display = $layout['display'] ?? 'section';
274
275 if ( $display === 'none' ) {
276 continue;
277 }
278
279 if ( $first ) {
280 // skip header for the first slot
281 $first = false;
282 } else {
283 // NOTE: this placeholder is hydrated by ParserOutput::getText().
284 $headText = Html::element( 'mw:slotheader', [], $role );
285 $html .= Html::rawElement( 'h1', [ 'class' => 'mw-slot-header' ], $headText );
286 $combinedOutput->setOutputFlag( ParserOutputFlags::HAS_SLOT_HEADERS );
287 }
288
289 // XXX: do we want to put a wrapper div around the output?
290 // Do we want to let $roleHandler do that?
291 $html .= $out->getRawText();
292 $combinedOutput->mergeHtmlMetaDataFrom( $out );
293 }
294
295 $combinedOutput->setRawText( $html );
296 }
297
298 $options->registerWatcher( null );
299 return $combinedOutput;
300 }
301
302 /**
303 * This reverses ::combineSlotOutput() in order to enable selective
304 * update of individual slots.
305 *
306 * @todo Currently this doesn't do much other than disable selective
307 * update if there is more than one slot. But in the case where
308 * slot combination is reversible, this should reverse it and attempt
309 * to reconstruct the original split ParserOutputs from the merged
310 * ParserOutput.
311 *
312 * @param RenderedRevision $rrev
313 * @param ParserOptions $options
314 * @param ?ParserOutput $previousOutput A combined ParserOutput for a
315 * previous parse, or null if none available.
316 * @return array<string,?ParserOutput> A mapping from role name to a
317 * previous ParserOutput for that slot in the previous parse
318 */
319 private function splitSlotOutput( RenderedRevision $rrev, ParserOptions $options, ?ParserOutput $previousOutput ) {
320 // If there is no previous parse, then there is nothing to split.
321 $revision = $rrev->getRevision();
322 $revslots = $revision->getSlots();
323 if ( $previousOutput === null ) {
324 return array_fill_keys( $revslots->getSlotRoles(), null );
325 }
326
327 // short circuit if there is only the main slot
328 // T351026 hack: if use-parsoid is set, only return main slot output for now
329 // T351113 will remove this hack.
330 if ( $revslots->getSlotRoles() === [ SlotRecord::MAIN ] || $options->getUseParsoid() ) {
331 return [ SlotRecord::MAIN => $previousOutput ];
332 }
333
334 // @todo Currently slot combination is not reversible
335 return array_fill_keys( $revslots->getSlotRoles(), null );
336 }
337 }