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