Merge "API: Validate API error codes"
[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 string|bool */
54 private $wikiId;
55
56 /**
57 * @param ILoadBalancer $loadBalancer
58 * @param bool|string $wikiId
59 */
60 public function __construct( ILoadBalancer $loadBalancer, $wikiId = false ) {
61 $this->loadBalancer = $loadBalancer;
62 $this->wikiId = $wikiId;
63
64 $this->saveParseLogger = new NullLogger();
65 }
66
67 /**
68 * @param LoggerInterface $saveParseLogger
69 */
70 public function setLogger( LoggerInterface $saveParseLogger ) {
71 $this->saveParseLogger = $saveParseLogger;
72 }
73
74 /**
75 * @param RevisionRecord $rev
76 * @param ParserOptions|null $options
77 * @param User|null $forUser User for privileged access. Default is unprivileged (public)
78 * access, unless the 'audience' hint is set to something else RevisionRecord::RAW.
79 * @param array $hints Hints given as an associative array. Known keys:
80 * - 'use-master' Use master when rendering for the parser cache during save.
81 * Default is to use a replica.
82 * - 'audience' the audience to use for content access. Default is
83 * RevisionRecord::FOR_PUBLIC if $forUser is not set, RevisionRecord::FOR_THIS_USER
84 * if $forUser is set. Can be set to RevisionRecord::RAW to disable audience checks.
85 * - 'known-revision-output' a combined ParserOutput for the revision, perhaps from
86 * some cache. the caller is responsible for ensuring that the ParserOutput indeed
87 * matched the $rev and $options. This mechanism is intended as a temporary stop-gap,
88 * for the time until caches have been changed to store RenderedRevision states instead
89 * of ParserOutput objects.
90 *
91 * @return RenderedRevision|null The rendered revision, or null if the audience checks fails.
92 */
93 public function getRenderedRevision(
94 RevisionRecord $rev,
95 ParserOptions $options = null,
96 User $forUser = null,
97 array $hints = []
98 ) {
99 if ( $rev->getWikiId() !== $this->wikiId ) {
100 throw new InvalidArgumentException( 'Mismatching wiki ID ' . $rev->getWikiId() );
101 }
102
103 $audience = $hints['audience']
104 ?? ( $forUser ? RevisionRecord::FOR_THIS_USER : RevisionRecord::FOR_PUBLIC );
105
106 if ( !$rev->audienceCan( RevisionRecord::DELETED_TEXT, $audience, $forUser ) ) {
107 // Returning null here is awkward, but consist with the signature of
108 // Revision::getContent() and RevisionRecord::getContent().
109 return null;
110 }
111
112 if ( !$options ) {
113 $options = ParserOptions::newCanonical( $forUser ?: 'canonical' );
114 }
115
116 $useMaster = $hints['use-master'] ?? false;
117
118 $dbIndex = $useMaster
119 ? DB_MASTER // use latest values
120 : DB_REPLICA; // T154554
121
122 $options->setSpeculativeRevIdCallback( function () use ( $dbIndex ) {
123 return $this->getSpeculativeRevId( $dbIndex );
124 } );
125
126 $title = Title::newFromLinkTarget( $rev->getPageAsLinkTarget() );
127
128 $renderedRevision = new RenderedRevision(
129 $title,
130 $rev,
131 $options,
132 function ( RenderedRevision $rrev, array $hints ) {
133 return $this->combineSlotOutput( $rrev, $hints );
134 },
135 $audience,
136 $forUser
137 );
138
139 $renderedRevision->setSaveParseLogger( $this->saveParseLogger );
140
141 if ( isset( $hints['known-revision-output'] ) ) {
142 $renderedRevision->setRevisionParserOutput( $hints['known-revision-output'] );
143 }
144
145 return $renderedRevision;
146 }
147
148 private function getSpeculativeRevId( $dbIndex ) {
149 // Use a fresh master connection in order to see the latest data, by avoiding
150 // stale data from REPEATABLE-READ snapshots.
151 // HACK: But don't use a fresh connection in unit tests, since it would not have
152 // the fake tables. This should be handled by the LoadBalancer!
153 $flags = defined( 'MW_PHPUNIT_TEST' ) || $dbIndex === DB_REPLICA
154 ? 0 : ILoadBalancer::CONN_TRX_AUTOCOMMIT;
155
156 $db = $this->loadBalancer->getConnectionRef( $dbIndex, [], $this->wikiId, $flags );
157
158 return 1 + (int)$db->selectField(
159 'revision',
160 'MAX(rev_id)',
161 [],
162 __METHOD__
163 );
164 }
165
166 /**
167 * This implements the layout for combining the output of multiple slots.
168 *
169 * @todo Use placement hints from SlotRoleHandlers instead of hard-coding the layout.
170 *
171 * @param RenderedRevision $rrev
172 * @param array $hints see RenderedRevision::getRevisionParserOutput()
173 *
174 * @return ParserOutput
175 */
176 private function combineSlotOutput( RenderedRevision $rrev, array $hints = [] ) {
177 $revision = $rrev->getRevision();
178 $slots = $revision->getSlots()->getSlots();
179
180 $withHtml = $hints['generate-html'] ?? true;
181
182 // short circuit if there is only the main slot
183 if ( array_keys( $slots ) === [ SlotRecord::MAIN ] ) {
184 return $rrev->getSlotParserOutput( SlotRecord::MAIN );
185 }
186
187 // TODO: put fancy layout logic here, see T200915.
188
189 // move main slot to front
190 if ( isset( $slots[SlotRecord::MAIN] ) ) {
191 $slots = [ SlotRecord::MAIN => $slots[SlotRecord::MAIN] ] + $slots;
192 }
193
194 $combinedOutput = new ParserOutput( null );
195 $slotOutput = [];
196
197 $options = $rrev->getOptions();
198 $options->registerWatcher( [ $combinedOutput, 'recordOption' ] );
199
200 foreach ( $slots as $role => $slot ) {
201 $out = $rrev->getSlotParserOutput( $role, $hints );
202 $slotOutput[$role] = $out;
203
204 $combinedOutput->mergeInternalMetaDataFrom( $out, $role );
205 $combinedOutput->mergeTrackingMetaDataFrom( $out );
206 }
207
208 if ( $withHtml ) {
209 $html = '';
210 $first = true;
211 /** @var ParserOutput $out */
212 foreach ( $slotOutput as $role => $out ) {
213 if ( $first ) {
214 // skip header for the first slot
215 $first = false;
216 } else {
217 // NOTE: this placeholder is hydrated by ParserOutput::getText().
218 $headText = Html::element( 'mw:slotheader', [], $role );
219 $html .= Html::rawElement( 'h1', [ 'class' => 'mw-slot-header' ], $headText );
220 }
221
222 $html .= $out->getRawText();
223 $combinedOutput->mergeHtmlMetaDataFrom( $out );
224 }
225
226 $combinedOutput->setText( $html );
227 }
228
229 $options->registerWatcher( null );
230 return $combinedOutput;
231 }
232
233 }