Migrate remaining usages of Title::userCan() to PermissionManager
[lhc/web/wiklou.git] / includes / Revision / RevisionRenderer.php
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 Html;
26 use InvalidArgumentException;
27 use ParserOptions;
28 use ParserOutput;
29 use Psr\Log\LoggerInterface;
30 use Psr\Log\NullLogger;
31 use Title;
32 use User;
33 use Wikimedia\Rdbms\ILoadBalancer;
34
35 /**
36 * The RevisionRenderer service provides access to rendered output for revisions.
37 * It does so be acting as a factory for RenderedRevision instances, which in turn
38 * provide lazy access to ParserOutput objects.
39 *
40 * One key responsibility of RevisionRenderer is implementing the layout used to combine
41 * the output of multiple slots.
42 *
43 * @since 1.32
44 */
45 class RevisionRenderer {
46
47 /** @var LoggerInterface */
48 private $saveParseLogger;
49
50 /** @var ILoadBalancer */
51 private $loadBalancer;
52
53 /** @var SlotRoleRegistry */
54 private $roleRegistery;
55
56 /** @var string|bool */
57 private $wikiId;
58
59 /**
60 * @param ILoadBalancer $loadBalancer
61 * @param SlotRoleRegistry $roleRegistry
62 * @param bool|string $wikiId
63 */
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
76 /**
77 * @param LoggerInterface $saveParseLogger
78 */
79 public function setLogger( LoggerInterface $saveParseLogger ) {
80 $this->saveParseLogger = $saveParseLogger;
81 }
82
83 /**
84 * @param RevisionRecord $rev
85 * @param ParserOptions|null $options
86 * @param User|null $forUser User for privileged access. Default is unprivileged (public)
87 * access, unless the 'audience' hint is set to something else RevisionRecord::RAW.
88 * @param array $hints Hints given as an associative array. Known keys:
89 * - 'use-master' Use master when rendering for the parser cache during save.
90 * Default is to use a replica.
91 * - 'audience' the audience to use for content access. Default is
92 * RevisionRecord::FOR_PUBLIC if $forUser is not set, RevisionRecord::FOR_THIS_USER
93 * if $forUser is set. Can be set to RevisionRecord::RAW to disable audience checks.
94 * - 'known-revision-output' a combined ParserOutput for the revision, perhaps from
95 * some cache. the caller is responsible for ensuring that the ParserOutput indeed
96 * matched the $rev and $options. This mechanism is intended as a temporary stop-gap,
97 * for the time until caches have been changed to store RenderedRevision states instead
98 * of ParserOutput objects.
99 *
100 * @return RenderedRevision|null The rendered revision, or null if the audience checks fails.
101 */
102 public function getRenderedRevision(
103 RevisionRecord $rev,
104 ParserOptions $options = null,
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']
113 ?? ( $forUser ? RevisionRecord::FOR_THIS_USER : RevisionRecord::FOR_PUBLIC );
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 $title = Title::newFromLinkTarget( $rev->getPageAsLinkTarget() );
136
137 $renderedRevision = new RenderedRevision(
138 $title,
139 $rev,
140 $options,
141 function ( RenderedRevision $rrev, array $hints ) {
142 return $this->combineSlotOutput( $rrev, $hints );
143 },
144 $audience,
145 $forUser
146 );
147
148 $renderedRevision->setSaveParseLogger( $this->saveParseLogger );
149
150 if ( isset( $hints['known-revision-output'] ) ) {
151 $renderedRevision->setRevisionParserOutput( $hints['known-revision-output'] );
152 }
153
154 return $renderedRevision;
155 }
156
157 private function getSpeculativeRevId( $dbIndex ) {
158 // Use a fresh master connection in order to see the latest data, by avoiding
159 // stale data from REPEATABLE-READ snapshots.
160 // HACK: But don't use a fresh connection in unit tests, since it would not have
161 // the fake tables. This should be handled by the LoadBalancer!
162 $flags = defined( 'MW_PHPUNIT_TEST' ) || $dbIndex === DB_REPLICA
163 ? 0 : ILoadBalancer::CONN_TRX_AUTOCOMMIT;
164
165 $db = $this->loadBalancer->getConnectionRef( $dbIndex, [], $this->wikiId, $flags );
166
167 return 1 + (int)$db->selectField(
168 'revision',
169 'MAX(rev_id)',
170 [],
171 __METHOD__
172 );
173 }
174
175 /**
176 * This implements the layout for combining the output of multiple slots.
177 *
178 * @todo Use placement hints from SlotRoleHandlers instead of hard-coding the layout.
179 *
180 * @param RenderedRevision $rrev
181 * @param array $hints see RenderedRevision::getRevisionParserOutput()
182 *
183 * @return ParserOutput
184 */
185 private function combineSlotOutput( RenderedRevision $rrev, array $hints = [] ) {
186 $revision = $rrev->getRevision();
187 $slots = $revision->getSlots()->getSlots();
188
189 $withHtml = $hints['generate-html'] ?? true;
190
191 // short circuit if there is only the main slot
192 if ( array_keys( $slots ) === [ SlotRecord::MAIN ] ) {
193 return $rrev->getSlotParserOutput( SlotRecord::MAIN );
194 }
195
196 // move main slot to front
197 if ( isset( $slots[SlotRecord::MAIN] ) ) {
198 $slots = [ SlotRecord::MAIN => $slots[SlotRecord::MAIN] ] + $slots;
199 }
200
201 $combinedOutput = new ParserOutput( null );
202 $slotOutput = [];
203
204 $options = $rrev->getOptions();
205 $options->registerWatcher( [ $combinedOutput, 'recordOption' ] );
206
207 foreach ( $slots as $role => $slot ) {
208 $out = $rrev->getSlotParserOutput( $role, $hints );
209 $slotOutput[$role] = $out;
210
211 // XXX: should the SlotRoleHandler be able to intervene here?
212 $combinedOutput->mergeInternalMetaDataFrom( $out, $role );
213 $combinedOutput->mergeTrackingMetaDataFrom( $out );
214 }
215
216 if ( $withHtml ) {
217 $html = '';
218 $first = true;
219 /** @var ParserOutput $out */
220 foreach ( $slotOutput as $role => $out ) {
221 $roleHandler = $this->roleRegistery->getRoleHandler( $role );
222
223 // TODO: put more fancy layout logic here, see T200915.
224 $layout = $roleHandler->getOutputLayoutHints();
225 $display = $layout['display'] ?? 'section';
226
227 if ( $display === 'none' ) {
228 continue;
229 }
230
231 if ( $first ) {
232 // skip header for the first slot
233 $first = false;
234 } else {
235 // NOTE: this placeholder is hydrated by ParserOutput::getText().
236 $headText = Html::element( 'mw:slotheader', [], $role );
237 $html .= Html::rawElement( 'h1', [ 'class' => 'mw-slot-header' ], $headText );
238 }
239
240 // XXX: do we want to put a wrapper div around the output?
241 // Do we want to let $roleHandler do that?
242 $html .= $out->getRawText();
243 $combinedOutput->mergeHtmlMetaDataFrom( $out );
244 }
245
246 $combinedOutput->setText( $html );
247 }
248
249 $options->registerWatcher( null );
250 return $combinedOutput;
251 }
252
253 }