Debian Codegraph @

includes/Rest/Handler/Helper/HtmlOutputRendererHelper.php

raw symbols SCIP
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20 namespace MediaWiki\Rest\Handler\Helper;
21
22 use HttpError;
23 use InvalidArgumentException;
24 use MediaWiki\Content\Content;
25 use MediaWiki\Content\IContentHandlerFactory;
26 use MediaWiki\Edit\ParsoidOutputStash;
27 use MediaWiki\Edit\ParsoidRenderID;
28 use MediaWiki\Edit\SelserContext;
29 use MediaWiki\Language\LanguageCode;
30 use MediaWiki\Languages\LanguageFactory;
31 use MediaWiki\Logger\LoggerFactory;
32 use MediaWiki\MainConfigNames;
33 use MediaWiki\Page\PageIdentity;
34 use MediaWiki\Page\PageLookup;
35 use MediaWiki\Page\PageRecord;
36 use MediaWiki\Page\ParserOutputAccess;
37 use MediaWiki\Parser\ParserOptions;
38 use MediaWiki\Parser\ParserOutput;
39 use MediaWiki\Parser\Parsoid\Config\SiteConfig as ParsoidSiteConfig;
40 use MediaWiki\Parser\Parsoid\HtmlTransformFactory;
41 use MediaWiki\Parser\Parsoid\PageBundleParserOutputConverter;
42 use MediaWiki\Permissions\Authority;
43 use MediaWiki\Rest\Handler;
44 use MediaWiki\Rest\HttpException;
45 use MediaWiki\Rest\LocalizedHttpException;
46 use MediaWiki\Rest\ResponseInterface;
47 use MediaWiki\Revision\MutableRevisionRecord;
48 use MediaWiki\Revision\RevisionAccessException;
49 use MediaWiki\Revision\RevisionLookup;
50 use MediaWiki\Revision\RevisionRecord;
51 use MediaWiki\Revision\RevisionRenderer;
52 use MediaWiki\Revision\SlotRecord;
53 use MediaWiki\Status\Status;
54 use MediaWiki\Title\Title;
55 use MWUnknownContentModelException;
56 use Wikimedia\Assert\Assert;
57 use Wikimedia\Bcp47Code\Bcp47Code;
58 use Wikimedia\Bcp47Code\Bcp47CodeValue;
59 use Wikimedia\Message\MessageValue;
60 use Wikimedia\ParamValidator\ParamValidator;
61 use Wikimedia\Parsoid\Core\ClientError;
62 use Wikimedia\Parsoid\Core\PageBundle;
63 use Wikimedia\Parsoid\Core\ResourceLimitExceededException;
64 use Wikimedia\Parsoid\DOM\Element;
65 use Wikimedia\Parsoid\Parsoid;
66 use Wikimedia\Parsoid\Utils\ContentUtils;
67 use Wikimedia\Parsoid\Utils\DOMCompat;
68 use Wikimedia\Parsoid\Utils\DOMUtils;
69 use Wikimedia\Parsoid\Utils\WTUtils;
70 use Wikimedia\Stats\StatsFactory;
71
72 /**
73 * Helper for getting output of a given wikitext page rendered by parsoid.
74 *
75 * @since 1.36
76 *
77 * @unstable Pending consolidation of the Parsoid extension with core code.
78 */
79 class HtmlOutputRendererHelper implements HtmlOutputHelper {
80 use RestAuthorizeTrait;
81 use RestStatusTrait;
82
83 /**
84 * @internal
85 */
86 public const CONSTRUCTOR_OPTIONS = [
87 MainConfigNames::ParsoidCacheConfig
88 ];
89
90 private const OUTPUT_FLAVORS = [ 'view', 'stash', 'fragment', 'edit' ];
91
92 /** @var PageIdentity|null */
93 private $page = null;
94
95 /** @var RevisionRecord|int|null */
96 private $revisionOrId = null;
97
98 /** @var Bcp47Code|null */
99 private $pageLanguage = null;
100
101 /** @var ?string One of the flavors from OUTPUT_FLAVORS */
102 private $flavor = null;
103
104 /** @var bool */
105 private $stash = false;
106
107 /** @var Authority */
108 private $authority;
109
110 /** @var ParserOutput */
111 private $parserOutput;
112
113 /** @var ParserOutput */
114 private $processedParserOutput;
115
116 /** @var ?Bcp47Code */
117 private $sourceLanguage = null;
118
119 /** @var ?Bcp47Code */
120 private $targetLanguage = null;
121
122 /**
123 * Should we ignore mismatches between $page and the page that $revision belongs to?
124 * Usually happens because of page moves. This should be set to true only for internal API calls.
125 */
126 private bool $lenientRevHandling = false;
127
128 /**
129 * Flags to be passed as $options to ParserOutputAccess::getParserOutput,
130 * to control parser cache access.
131 *
132 * @var int Use ParserOutputAccess::OPT_*
133 */
134 private $parserOutputAccessOptions = 0;
135
136 /**
137 * @see the $options parameter on Parsoid::wikitext2html
138 * @var array
139 */
140 private $parsoidOptions = [];
141
142 /**
143 * Whether the result can be cached in the parser cache and the web cache.
144 * Set to false when bespoke options are set.
145 *
146 * @var bool
147 */
148 private $isCacheable = true;
149
150 private ParsoidOutputStash $parsoidOutputStash;
151 private StatsFactory $statsFactory;
152 private ParserOutputAccess $parserOutputAccess;
153 private PageLookup $pageLookup;
154 private RevisionLookup $revisionLookup;
155 private RevisionRenderer $revisionRenderer;
156 private ParsoidSiteConfig $parsoidSiteConfig;
157 private HtmlTransformFactory $htmlTransformFactory;
158 private IContentHandlerFactory $contentHandlerFactory;
159 private LanguageFactory $languageFactory;
160
161 /**
162 * @param ParsoidOutputStash $parsoidOutputStash
163 * @param StatsFactory $statsFactory
164 * @param ParserOutputAccess $parserOutputAccess
165 * @param PageLookup $pageLookup
166 * @param RevisionLookup $revisionLookup
167 * @param RevisionRenderer $revisionRenderer
168 * @param ParsoidSiteConfig $parsoidSiteConfig
169 * @param HtmlTransformFactory $htmlTransformFactory
170 * @param IContentHandlerFactory $contentHandlerFactory
171 * @param LanguageFactory $languageFactory
172 * @param PageIdentity|null $page
173 * @param array $parameters
174 * @param Authority|null $authority
175 * @param RevisionRecord|int|null $revision
176 * @param bool $lenientRevHandling Should we ignore mismatches between
177 * $page and the page that $revision belongs to? Usually happens
178 * because of page moves. This should be set to true only for
179 * internal API calls.
180 * @note Since 1.43, setting $page and $authority arguments to null
181 * has been deprecated.
182 */
183 public function __construct(
184 ParsoidOutputStash $parsoidOutputStash,
185 StatsFactory $statsFactory,
186 ParserOutputAccess $parserOutputAccess,
187 PageLookup $pageLookup,
188 RevisionLookup $revisionLookup,
189 RevisionRenderer $revisionRenderer,
190 ParsoidSiteConfig $parsoidSiteConfig,
191 HtmlTransformFactory $htmlTransformFactory,
192 IContentHandlerFactory $contentHandlerFactory,
193 LanguageFactory $languageFactory,
194 ?PageIdentity $page = null,
195 array $parameters = [],
196 ?Authority $authority = null,
197 $revision = null,
198 bool $lenientRevHandling = false
199 ) {
200 $this->parsoidOutputStash = $parsoidOutputStash;
201 $this->statsFactory = $statsFactory;
202 $this->parserOutputAccess = $parserOutputAccess;
203 $this->pageLookup = $pageLookup;
204 $this->revisionLookup = $revisionLookup;
205 $this->revisionRenderer = $revisionRenderer;
206 $this->parsoidSiteConfig = $parsoidSiteConfig;
207 $this->htmlTransformFactory = $htmlTransformFactory;
208 $this->contentHandlerFactory = $contentHandlerFactory;
209 $this->languageFactory = $languageFactory;
210 $this->lenientRevHandling = $lenientRevHandling;
211 if ( $page === null || $authority === null ) {
212 // Constructing without $page and $authority parameters
213 // is deprecated since 1.43.
214 wfDeprecated( __METHOD__ . ' without $page or $authority', '1.43' );
215 } else {
216 $this->initInternal( $page, $parameters, $authority, $revision );
217 }
218 }
219
220 /**
221 * Sets the given flavor to use for Wikitext -> HTML transformations.
222 *
223 * Flavors may influence parser options, parsoid options, and DOM transformations.
224 * They will be reflected by the ETag returned by getETag().
225 *
226 * @note This method should not be called if stashing mode is enabled.
227 * @see setStashingEnabled
228 * @see getFlavor()
229 *
230 * @param string $flavor
231 *
232 * @return void
233 */
234 public function setFlavor( string $flavor ): void {
235 if ( !in_array( $flavor, self::OUTPUT_FLAVORS ) ) {
236 throw new InvalidArgumentException( 'Invalid flavor supplied' );
237 }
238
239 if ( $this->stash ) {
240 // XXX: throw?
241 $flavor = 'stash';
242 }
243
244 $this->flavor = $flavor;
245 }
246
247 /**
248 * Returns the flavor of HTML that will be generated.
249 * @see setFlavor()
250 * @return string
251 */
252 public function getFlavor(): string {
253 return $this->flavor;
254 }
255
256 /**
257 * Set the desired Parsoid profile version for the output.
258 * The actual output version is selected to be compatible with the one given here,
259 * per the rules of semantic versioning.
260 *
261 * @note Will disable caching if the effective output version is different from the default.
262 *
263 * @param string $version
264 *
265 * @throws HttpException If the given version is not supported (status 406)
266 */
267 public function setOutputProfileVersion( $version ) {
268 $outputContentVersion = Parsoid::resolveContentVersion( $version );
269
270 if ( !$outputContentVersion ) {
271 throw new LocalizedHttpException(
272 new MessageValue( "rest-unsupported-profile-version", [ $version ] ), 406
273 );
274 }
275
276 // Only set the option if the value isn't the default!
277 if ( $outputContentVersion !== Parsoid::defaultHTMLVersion() ) {
278 throw new LocalizedHttpException(
279 new MessageValue( "rest-unsupported-profile-version", [ $version ] ), 406
280 );
281
282 // TODO: (T347426) At some later point, we may reintroduce support for
283 // non-default content versions as part of work on the content
284 // negotiation protocol.
285 //
286 // // See Parsoid::wikitext2html
287 // $this->parsoidOptions['outputContentVersion'] = $outputContentVersion;
288 // $this->isCacheable = false;
289 }
290 }
291
292 /**
293 * Determine whether stashing should be applied.
294 *
295 * @param bool $stash
296 *
297 * @return void
298 */
299 public function setStashingEnabled( bool $stash ): void {
300 $this->stash = $stash;
301
302 if ( $stash ) {
303 $this->setFlavor( 'stash' );
304 } elseif ( $this->flavor === 'stash' ) {
305 $this->setFlavor( 'view' );
306 }
307 }
308
309 /**
310 * Set the revision to render.
311 *
312 * This can take a fake RevisionRecord when rendering for previews
313 * or when switching the editor from source mode to visual mode.
314 *
315 * In that case, $revisionOrId->getId() must return 0 to indicate
316 * that the ParserCache should be bypassed. Stashing may still apply.
317 *
318 * @param RevisionRecord|int $revisionOrId
319 */
320 public function setRevision( $revisionOrId ): void {
321 Assert::parameterType( [ RevisionRecord::class, 'integer' ], $revisionOrId, '$revision' );
322
323 if ( is_int( $revisionOrId ) && $revisionOrId <= 0 ) {
324 throw new HttpError( 400, "Bad revision ID: $revisionOrId" );
325 }
326
327 $this->revisionOrId = $revisionOrId;
328
329 if ( $this->getRevisionId() === null ) {
330 // If we have a RevisionRecord but no revision ID, we are dealing with a fake
331 // revision used for editor previews or mode switches. The wikitext is coming
332 // from the request, not the database, so the result is not cacheable for re-use
333 // by others (though it can be stashed for use by the same client).
334 $this->isCacheable = false;
335 }
336 }
337
338 /**
339 * Set the content to render. Useful when rendering for previews
340 * or when switching the editor from source mode to visual mode.
341 *
342 * This will create a fake revision for rendering, the revision ID will be 0.
343 *
344 * @see setRevision
345 * @see setContentSource
346 *
347 * @param Content $content
348 */
349 public function setContent( Content $content ): void {
350 $rev = new MutableRevisionRecord( $this->page );
351 $rev->setId( 0 );
352 $rev->setPageId( $this->page->getId() );
353 $rev->setContent( SlotRecord::MAIN, $content );
354 $this->setRevision( $rev );
355 }
356
357 /**
358 * Set the content to render. Useful when rendering for previews
359 * or when switching the editor from source mode to visual mode.
360 *
361 * This will create a fake revision for rendering. The revision ID will be 0.
362 *
363 * @param string $source The source data, e.g. wikitext
364 * @param string $model The content model indicating how to interpret $source, e.g. CONTENT_MODEL_WIKITEXT
365 *
366 * @see setRevision
367 * @see setContent
368 */
369 public function setContentSource( string $source, string $model ): void {
370 try {
371 $handler = $this->contentHandlerFactory->getContentHandler( $model );
372 $content = $handler->unserializeContent( $source );
373 $this->setContent( $content );
374 } catch ( MWUnknownContentModelException $ex ) {
375 throw new LocalizedHttpException( new MessageValue( "rest-bad-content-model", [ $model ] ), 400 );
376 }
377 }
378
379 /**
380 * This is equivalent to 'pageLanguageOverride' in PageConfigFactory
381 * For example, when clients call the REST API with the 'content-language'
382 * header to affect language variant conversion.
383 *
384 * @param Bcp47Code|string $pageLanguage the page language, as a Bcp47Code
385 * or a BCP-47 string.
386 */
387 public function setPageLanguage( $pageLanguage ): void {
388 if ( is_string( $pageLanguage ) ) {
389 $pageLanguage = new Bcp47CodeValue( $pageLanguage );
390 }
391 $this->pageLanguage = $pageLanguage;
392 }
393
394 /**
395 * Initializes the helper with the given parameters like the page
396 * we're dealing with, parameters gotten from the request inputs,
397 * and the revision if any is available.
398 *
399 * @param PageIdentity $page
400 * @param array $parameters
401 * @param Authority $authority
402 * @param RevisionRecord|int|null $revision
403 * @deprecated since 1.43, use parameters in constructor instead
404 */
405 public function init(
406 PageIdentity $page,
407 array $parameters,
408 Authority $authority,
409 $revision = null
410 ) {
411 wfDeprecated( __METHOD__, '1.43' );
412 $this->initInternal( $page, $parameters, $authority, $revision );
413 }
414
415 private function initInternal(
416 PageIdentity $page,
417 array $parameters,
418 Authority $authority,
419 $revision = null
420 ) {
421 $this->page = $page;
422 $this->authority = $authority;
423 $this->stash = $parameters['stash'] ?? false;
424
425 if ( $revision !== null ) {
426 $this->setRevision( $revision );
427 }
428
429 if ( $this->stash ) {
430 $this->setFlavor( 'stash' );
431 } else {
432 $this->setFlavor( $parameters['flavor'] ?? 'view' );
433 }
434 }
435
436 /**
437 * @inheritDoc
438 */
439 public function setVariantConversionLanguage(
440 $targetLanguage,
441 $sourceLanguage = null
442 ): void {
443 if ( is_string( $targetLanguage ) ) {
444 $targetLanguage = $this->getAcceptedTargetLanguage( $targetLanguage );
445 $targetLanguage = LanguageCode::normalizeNonstandardCodeAndWarn(
446 $targetLanguage
447 );
448 }
449 if ( is_string( $sourceLanguage ) ) {
450 $sourceLanguage = LanguageCode::normalizeNonstandardCodeAndWarn(
451 $sourceLanguage
452 );
453 }
454 $this->targetLanguage = $targetLanguage;
455 $this->sourceLanguage = $sourceLanguage;
456 }
457
458 /**
459 * Get a target language from an accept header
460 */
461 private function getAcceptedTargetLanguage( string $targetLanguage ): string {
462 // We could try to identify the most desirable language here,
463 // following the rules for Accept-Language headers in RFC9100.
464 // For now, just take the first language code.
465
466 if ( preg_match( '/^\s*([-\w]+)/', $targetLanguage, $m ) ) {
467 return $m[1];
468 } else {
469 // "undetermined" per RFC5646
470 return 'und';
471 }
472 }
473
474 /**
475 * @inheritDoc
476 */
477 public function getHtml(): ParserOutput {
478 if ( $this->processedParserOutput ) {
479 return $this->processedParserOutput;
480 }
481
482 $parserOutput = $this->getParserOutput();
483
484 if ( $this->stash ) {
485 $this->authorizeWriteOrThrow( $this->authority, 'stashbasehtml', $this->page );
486
487 $isFakeRevision = $this->getRevisionId() === null;
488 $parsoidStashKey = ParsoidRenderID::newFromParserOutput( $parserOutput );
489 $stashSuccess = $this->parsoidOutputStash->set(
490 $parsoidStashKey,
491 new SelserContext(
492 PageBundleParserOutputConverter::pageBundleFromParserOutput( $parserOutput ),
493 $parsoidStashKey->getRevisionID(),
494 $isFakeRevision ? $this->revisionOrId->getContent( SlotRecord::MAIN ) : null
495 )
496 );
497 if ( !$stashSuccess ) {
498 $this->statsFactory->getCounter( 'htmloutputrendererhelper_stash_total' )
499 ->setLabel( 'status', 'fail' )
500 ->copyToStatsdAt( 'htmloutputrendererhelper.stash.fail' )
501 ->increment();
502
503 $errorData = [ 'parsoid-stash-key' => $parsoidStashKey ];
504 LoggerFactory::getInstance( 'HtmlOutputRendererHelper' )->error(
505 "Parsoid stash failure",
506 $errorData
507 );
508 throw new LocalizedHttpException(
509 MessageValue::new( 'rest-html-stash-failure' ),
510 500,
511 $errorData
512 );
513 }
514 $this->statsFactory->getCounter( 'htmloutputrendererhelper_stash_total' )
515 ->setLabel( 'status', 'save' )
516 ->copyToStatsdAt( 'htmloutputrendererhelper.stash.save' )
517 ->increment();
518 }
519
520 if ( $this->flavor === 'edit' ) {
521 $pb = $this->getPageBundle();
522
523 // Inject data-parsoid and data-mw attributes.
524 // XXX: Would be nice if we had a DOM handy.
525 $doc = DOMUtils::parseHTML( $parserOutput->getRawText() );
526 PageBundle::apply( $doc, $pb );
527 $parserOutput->setRawText( ContentUtils::toXML( $doc ) );
528 }
529
530 // Check if variant conversion has to be performed
531 // NOTE: Variant conversion is performed on the fly, and kept outside the stash.
532 if ( $this->targetLanguage ) {
533 $languageVariantConverter = $this->htmlTransformFactory->getLanguageVariantConverter( $this->page );
534 $parserOutput = $languageVariantConverter->convertParserOutputVariant(
535 $parserOutput,
536 $this->targetLanguage,
537 $this->sourceLanguage
538 );
539 }
540
541 $this->processedParserOutput = $parserOutput;
542 return $parserOutput;
543 }
544
545 /**
546 * @inheritDoc
547 */
548 public function getETag( string $suffix = '' ): ?string {
549 $parserOutput = $this->getParserOutput();
550
551 $renderID = ParsoidRenderID::newFromParserOutput( $parserOutput )->getKey();
552
553 if ( $suffix !== '' ) {
554 $eTag = "$renderID/{$this->flavor}/$suffix";
555 } else {
556 $eTag = "$renderID/{$this->flavor}";
557 }
558
559 if ( $this->targetLanguage ) {
560 $eTag .= "+lang:{$this->targetLanguage->toBcp47Code()}";
561 }
562
563 return "\"{$eTag}\"";
564 }
565
566 /**
567 * @inheritDoc
568 */
569 public function getLastModified(): ?string {
570 return $this->getParserOutput()->getCacheTime();
571 }
572
573 /**
574 * @inheritDoc
575 */
576 public static function getParamSettings(): array {
577 return [
578 'stash' => [
579 Handler::PARAM_SOURCE => 'query',
580 ParamValidator::PARAM_TYPE => 'boolean',
581 ParamValidator::PARAM_DEFAULT => false,
582 ParamValidator::PARAM_REQUIRED => false,
583 ],
584 'flavor' => [
585 Handler::PARAM_SOURCE => 'query',
586 ParamValidator::PARAM_TYPE => self::OUTPUT_FLAVORS,
587 ParamValidator::PARAM_DEFAULT => 'view',
588 ParamValidator::PARAM_REQUIRED => false,
589 ],
590 ];
591 }
592
593 private function getDefaultPageLanguage( ParserOptions $options ): Bcp47Code {
594 // NOTE: keep in sync with Parser::getTargetLanguage!
595
596 // XXX: Inject a TitleFactory just for this?! We need a better way to determine the page language...
597 $title = Title::castFromPageIdentity( $this->page );
598
599 if ( $options->getInterfaceMessage() ) {
600 return $options->getUserLangObj();
601 }
602
603 return $title->getPageLanguage();
604 }
605
606 /**
607 * @return ParserOutput
608 */
609 private function getParserOutput(): ParserOutput {
610 if ( !$this->parserOutput ) {
611 $parserOptions = ParserOptions::newFromAnon();
612 $parserOptions->setRenderReason( __METHOD__ );
613
614 $defaultLanguage = $this->getDefaultPageLanguage( $parserOptions );
615
616 if ( $this->pageLanguage
617 && $this->pageLanguage->toBcp47Code() !== $defaultLanguage->toBcp47Code()
618 ) {
619 $languageObj = $this->languageFactory->getLanguage( $this->pageLanguage );
620 $parserOptions->setTargetLanguage( $languageObj );
621 // Ensure target language splits the parser cache, when
622 // non-default; targetLangauge is not in
623 // ParserOptions::$cacheVaryingOptionsHash for the legacy
624 // parser.
625 $parserOptions->addExtraKey( 'target=' . $languageObj->getCode() );
626 }
627
628 try {
629 $status = $this->getParserOutputInternal( $parserOptions );
630 } catch ( RevisionAccessException $e ) {
631 throw new LocalizedHttpException(
632 MessageValue::new( 'rest-nonexistent-title' ),
633 404,
634 [ 'reason' => $e->getMessage() ]
635 );
636 }
637
638 if ( !$status->isOK() ) {
639 if ( $status->hasMessage( 'parsoid-client-error' ) ) {
640 $this->throwExceptionForStatus( $status, 'rest-html-backend-error', 400 );
641 } elseif ( $status->hasMessage( 'parsoid-resource-limit-exceeded' ) ) {
642 $this->throwExceptionForStatus( $status, 'rest-resource-limit-exceeded', 413 );
643 } elseif ( $status->hasMessage( 'missing-revision-permission' ) ) {
644 $this->throwExceptionForStatus( $status, 'rest-permission-denied-revision', 403 );
645 } elseif ( $status->hasMessage( 'parsoid-revision-access' ) ) {
646 $this->throwExceptionForStatus( $status, 'rest-specified-revision-unavailable', 404 );
647 } else {
648 $this->logStatusError( $status, 'Parsoid backend error', 'HtmlOutputRendererHelper' );
649 $this->throwExceptionForStatus( $status, 'rest-html-backend-error', 500 );
650 }
651 }
652
653 $this->parserOutput = $status->getValue();
654 }
655
656 Assert::invariant( $this->parserOutput->getRenderId() !== null, "no render id" );
657 return $this->parserOutput;
658 }
659
660 /**
661 * The content language of the HTML output after parsing.
662 *
663 * @return Bcp47Code The language, as a BCP-47 code
664 */
665 public function getHtmlOutputContentLanguage(): Bcp47Code {
666 $contentLanguage = $this->getHtml()->getLanguage();
667
668 // This shouldn't happen, but don't crash if it does:
669 if ( !$contentLanguage ) {
670 if ( $this->pageLanguage ) {
671 LoggerFactory::getInstance( 'HtmlOutputRendererHelper' )->warning(
672 "ParserOutput does not specify a language"
673 );
674
675 $contentLanguage = $this->pageLanguage;
676 } else {
677 LoggerFactory::getInstance( 'HtmlOutputRendererHelper' )->warning(
678 "ParserOutput does not specify a language and no page language set in helper."
679 );
680
681 $title = Title::newFromPageIdentity( $this->page );
682 $contentLanguage = $title->getPageLanguage();
683 }
684 }
685
686 return $contentLanguage;
687 }
688
689 /**
690 * @inheritDoc
691 */
692 public function putHeaders( ResponseInterface $response, bool $forHtml = true ): void {
693 if ( $forHtml ) {
694 // For HTML, we want to set the Content-Language. For JSON, we probably don't.
695 $response->setHeader( 'Content-Language', $this->getHtmlOutputContentLanguage()->toBcp47Code() );
696
697 $pb = $this->getPageBundle();
698 ParsoidFormatHelper::setContentType( $response, ParsoidFormatHelper::FORMAT_HTML, $pb->version );
699 }
700
701 if ( $this->targetLanguage ) {
702 $response->addHeader( 'Vary', 'Accept-Language' );
703 }
704
705 // XXX: if Parsoid returns Vary headers, set them here?!
706
707 if ( !$this->isCacheable ) {
708 $response->setHeader( 'Cache-Control', 'private,no-cache,s-maxage=0' );
709 }
710
711 // TODO: cache control for stable HTML? See ContentHelper::setCacheControl
712
713 if ( $this->getRevisionId() ) {
714 $response->setHeader( 'Content-Revision-Id', (string)$this->getRevisionId() );
715 }
716 }
717
718 /**
719 * Returns the rendered HTML as a PageBundle object.
720 *
721 * @return PageBundle
722 */
723 public function getPageBundle(): PageBundle {
724 // XXX: converting between PageBundle and ParserOutput is inefficient!
725 $parserOutput = $this->getParserOutput();
726 $pb = PageBundleParserOutputConverter::pageBundleFromParserOutput( $parserOutput );
727
728 // Check if variant conversion has to be performed
729 // NOTE: Variant conversion is performed on the fly, and kept outside the stash.
730 if ( $this->targetLanguage ) {
731 $languageVariantConverter = $this->htmlTransformFactory->getLanguageVariantConverter( $this->page );
732 $pb = $languageVariantConverter->convertPageBundleVariant(
733 $pb,
734 $this->targetLanguage,
735 $this->sourceLanguage
736 );
737 }
738
739 return $pb;
740 }
741
742 /**
743 * Returns the ID of the revision that is being rendered.
744 *
745 * This will return 0 if no revision has been specified, so the current revision
746 * will be rendered.
747 *
748 * This wil return null if RevisionRecord has been set but that RevisionRecord
749 * does not have a revision ID, e.g. when rendering a preview.
750 *
751 * @return ?int
752 */
753 public function getRevisionId(): ?int {
754 if ( !$this->revisionOrId ) {
755 // If we don't have a revision set, or it's 0, we are rendering the current revision.
756 return 0;
757 }
758
759 if ( is_object( $this->revisionOrId ) ) {
760 // NOTE: return null even if getId() gave us 0
761 return $this->revisionOrId->getId() ?: null;
762 }
763
764 // It's a revision ID, just return it
765 return (int)$this->revisionOrId;
766 }
767
768 /**
769 * Strip Parsoid's section wrappers
770 *
771 * TODO: Should we move this to Parsoid's ContentUtils class?
772 * There already is a stripUnnecessaryWrappersAndSyntheticNodes but
773 * it targets html2wt and does a lot more than just section unwrapping.
774 *
775 * @param Element $elt
776 */
777 private function stripParsoidSectionTags( Element $elt ): void {
778 $n = $elt->firstChild;
779 while ( $n ) {
780 $next = $n->nextSibling;
781 if ( $n instanceof Element ) {
782 // Recurse into subtree before stripping this
783 $this->stripParsoidSectionTags( $n );
784 // Strip <section> tags and synthetic extended-annotation-region wrappers
785 if ( WTUtils::isParsoidSectionTag( $n ) ) {
786 $parent = $n->parentNode;
787 // Help out phan
788 '@phan-var Element $parent';
789 DOMUtils::migrateChildren( $n, $parent, $n );
790 $parent->removeChild( $n );
791 }
792 }
793 $n = $next;
794 }
795 }
796
797 /**
798 * @param ParserOptions $parserOptions
799 *
800 * @return Status
801 */
802 private function getParserOutputInternal( ParserOptions $parserOptions ): Status {
803 // NOTE: ParserOutputAccess::getParserOutput() should be used for revisions
804 // that come from the database. Either this revision is null to indicate
805 // the current revision or the revision must have an ID.
806 // If we have a revision and the ID is 0 or null, then it's a fake revision
807 // representing a preview.
808 $parsoidOptions = $this->parsoidOptions;
809 // NOTE: VisualEditor would set this flavor when transforming from Wikitext to HTML
810 // for the purpose of editing when doing parsefragment (in body only mode).
811 if ( $this->flavor === 'fragment' || $this->getRevisionId() === null ) {
812 $this->isCacheable = false;
813 }
814
815 // TODO: Decide whether we want to allow stale content for speed for the
816 // 'view' flavor. In that case, we would want to use PoolCounterWork,
817 // either directly or through ParserOutputAccess.
818
819 $flags = $this->parserOutputAccessOptions;
820 // Resolve revision
821 $page = $this->page;
822 $revision = $this->revisionOrId;
823 if ( $page === null ) {
824 throw new RevisionAccessException( "No page" );
825 }
826 // NOTE: If we have a RevisionRecord already and this is
827 // not cacheable, just use it, there is no need to
828 // resolve $page to a PageRecord (and it may not be
829 // possible if the page doesn't exist).
830 if ( $this->isCacheable || !$revision instanceof RevisionRecord ) {
831 if ( !$page instanceof PageRecord ) {
832 $name = "$page";
833 $page = $this->pageLookup->getPageByReference( $page );
834 if ( !$page ) {
835 throw new RevisionAccessException(
836 'Page {name} not found',
837 [ 'name' => $name ]
838 );
839 }
840 }
841
842 $revision ??= $page->getLatest();
843
844 if ( is_int( $revision ) ) {
845 $revId = $revision;
846 $revision = $this->revisionLookup->getRevisionById( $revId );
847
848 if ( !$revision ) {
849 throw new RevisionAccessException(
850 'Revision {revId} not found',
851 [ 'revId' => $revId ]
852 );
853 }
854 }
855
856 if ( $page->getId() !== $revision->getPageId() ) {
857 if ( $this->lenientRevHandling ) {
858 $page = $this->pageLookup->getPageById( $revision->getPageId() );
859 if ( !$page ) {
860 // This should ideally never trigger!
861 throw new \RuntimeException(
862 "Unexpected NULL page for pageid " . $revision->getPageId() .
863 " from revision " . $revision->getId()
864 );
865 }
866 // Don't cache this!
867 $flags |= ParserOutputAccess::OPT_NO_UPDATE_CACHE;
868 } else {
869 throw new RevisionAccessException(
870 'Revision {revId} does not belong to page {name}',
871 [ 'name' => $page->getDBkey(), 'revId' => $revision->getId() ]
872 );
873 }
874 }
875 }
876
877 $mainSlot = $revision->getSlot( SlotRecord::MAIN );
878 $contentModel = $mainSlot->getModel();
879 if ( $this->parsoidSiteConfig->supportsContentModel( $contentModel ) ) {
880 $parserOptions->setUseParsoid();
881 }
882 if ( $this->isCacheable ) {
883 // phan can't tell that we must have used the block above to
884 // resolve $page to a PageRecord if we've made it to this block.
885 '@phan-var PageRecord $page';
886 try {
887 $status = $this->parserOutputAccess->getParserOutput(
888 $page, $parserOptions, $revision, $flags
889 );
890 } catch ( ClientError $e ) {
891 $status = Status::newFatal( 'parsoid-client-error', $e->getMessage() );
892 } catch ( ResourceLimitExceededException $e ) {
893 $status = Status::newFatal( 'parsoid-resource-limit-exceeded', $e->getMessage() );
894 }
895 Assert::invariant( $status->isOK() ? $status->getValue()->getRenderId() !== null : true, "no render id" );
896 } else {
897 $status = $this->parseUncacheable(
898 $page,
899 $parserOptions,
900 $revision,
901 $this->lenientRevHandling
902 );
903
904 // @phan-suppress-next-line PhanSuspiciousValueComparison
905 if ( $status->isOK() && $this->flavor === 'fragment' ) {
906 // Unwrap sections and return body_only content
907 // NOTE: This introduces an extra html -> dom -> html roundtrip
908 // This will get addressed once HtmlHolder work is complete
909 $parserOutput = $status->getValue();
910 $body = DOMCompat::getBody( DOMUtils::parseHTML( $parserOutput->getRawText() ) );
911 if ( $body ) {
912 $this->stripParsoidSectionTags( $body );
913 $parserOutput->setText( DOMCompat::getInnerHTML( $body ) );
914 }
915 }
916 Assert::invariant( $status->isOK() ? $status->getValue()->getRenderId() !== null : true, "no render id" );
917 }
918
919 return $status;
920 }
921
922 // See ParserOutputAccess::renderRevision() -- but of course this method
923 // bypasses any caching.
924 private function parseUncacheable(
925 PageIdentity $page,
926 ParserOptions $parserOptions,
927 RevisionRecord $revision,
928 bool $lenientRevHandling = false
929 ): Status {
930 // Enforce caller expectation
931 $revId = $revision->getId();
932 if ( $revId !== 0 && $revId !== null ) {
933 return Status::newFatal( 'parsoid-revision-access',
934 "parseUncacheable should not be called for a real revision" );
935 }
936 try {
937 $renderedRev = $this->revisionRenderer->getRenderedRevision(
938 $revision,
939 $parserOptions,
940 // ParserOutputAccess uses 'null' for the authority and
941 // 'audience' => RevisionRecord::RAW, presumably because
942 // the access checks are already handled by the
943 // RestAuthorizeTrait
944 $this->authority,
945 [ 'audience' => RevisionRecord::RAW ]
946 );
947 if ( $renderedRev === null ) {
948 return Status::newFatal( 'parsoid-revision-access' );
949 }
950 $parserOutput = $renderedRev->getRevisionParserOutput();
951 // Ensure this isn't accidentally cached
952 $parserOutput->updateCacheExpiry( 0 );
953 return Status::newGood( $parserOutput );
954 } catch ( ClientError $e ) {
955 return Status::newFatal( 'parsoid-client-error', $e->getMessage() );
956 } catch ( ResourceLimitExceededException $e ) {
957 return Status::newFatal( 'parsoid-resource-limit-exceeded', $e->getMessage() );
958 }
959 }
960 }