Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
63.61% covered (warning)
63.61%
215 / 338
7.69% covered (danger)
7.69%
1 / 13
CRAP
0.00% covered (danger)
0.00%
0 / 1
HtmlInputTransformHelper
63.61% covered (warning)
63.61%
215 / 338
7.69% covered (danger)
7.69%
1 / 13
509.80
0.00% covered (danger)
0.00%
0 / 1
 __construct
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
2.01
 getParamSettings
0.00% covered (danger)
0.00%
0 / 44
0.00% covered (danger)
0.00%
0 / 1
2
 normalizeParameters
72.73% covered (warning)
72.73%
16 / 22
0.00% covered (danger)
0.00%
0 / 1
21.19
 init
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 initInternal
79.10% covered (warning)
79.10%
53 / 67
0.00% covered (danger)
0.00%
0 / 1
25.02
 getTransform
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 setMetrics
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 setOriginal
73.68% covered (warning)
73.68%
56 / 76
0.00% covered (danger)
0.00%
0 / 1
32.64
 getContent
72.22% covered (warning)
72.22%
13 / 18
0.00% covered (danger)
0.00%
0 / 1
4.34
 putContent
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
2
 fetchParserOutputFromParsoid
73.68% covered (warning)
73.68%
28 / 38
0.00% covered (danger)
0.00%
0 / 1
13.21
 fetchSelserContextFromStash
91.18% covered (success)
91.18%
31 / 34
0.00% covered (danger)
0.00%
0 / 1
5.02
 throwHttpExceptionForStatus
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
12
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\UnknownContentModelException;
11use MediaWiki\Edit\ParsoidOutputStash;
12use MediaWiki\Edit\ParsoidRenderID;
13use MediaWiki\Edit\SelserContext;
14use MediaWiki\Language\LanguageCode;
15use MediaWiki\MainConfigNames;
16use MediaWiki\Page\PageIdentity;
17use MediaWiki\Page\PageLookup;
18use MediaWiki\Page\PageRecord;
19use MediaWiki\Page\ParserOutputAccess;
20use MediaWiki\Parser\ParserOptions;
21use MediaWiki\Parser\ParserOutput;
22use MediaWiki\Parser\Parsoid\HtmlToContentTransform;
23use MediaWiki\Parser\Parsoid\HtmlTransformFactory;
24use MediaWiki\Parser\Parsoid\PageBundleParserOutputConverter;
25use MediaWiki\Rest\Handler;
26use MediaWiki\Rest\HttpException;
27use MediaWiki\Rest\LocalizedHttpException;
28use MediaWiki\Rest\ResponseInterface;
29use MediaWiki\Revision\RevisionAccessException;
30use MediaWiki\Revision\RevisionLookup;
31use MediaWiki\Revision\RevisionRecord;
32use MediaWiki\Status\Status;
33use Wikimedia\Bcp47Code\Bcp47Code;
34use Wikimedia\Message\MessageValue;
35use Wikimedia\ParamValidator\ParamValidator;
36use Wikimedia\Parsoid\Core\ClientError;
37use Wikimedia\Parsoid\Core\HtmlPageBundle;
38use Wikimedia\Parsoid\Core\ResourceLimitExceededException;
39use Wikimedia\Parsoid\Parsoid;
40use Wikimedia\Stats\StatsFactory;
41
42/**
43 * REST helper for converting HTML to page content source (e.g. wikitext).
44 *
45 * @since 1.40
46 *
47 * @unstable Pending consolidation of the Parsoid extension with core code.
48 */
49class HtmlInputTransformHelper {
50    /**
51     * @internal
52     */
53    public const CONSTRUCTOR_OPTIONS = [
54        MainConfigNames::ParsoidCacheConfig
55    ];
56
57    private ?PageIdentity $page = null;
58    private ?HtmlToContentTransform $transform = null;
59    private array $envOptions;
60
61    /**
62     * @param StatsFactory $statsFactory
63     * @param HtmlTransformFactory $htmlTransformFactory
64     * @param ParsoidOutputStash $parsoidOutputStash
65     * @param ParserOutputAccess $parserOutputAccess
66     * @param PageLookup $pageLookup
67     * @param RevisionLookup $revisionLookup
68     * @param PageBundleParserOutputConverter $pageBundleParserOutputConverter
69     * @param array $envOptions
70     * @param ?PageIdentity $page
71     * @param array|string $body Body structure, or an HTML string
72     * @param array $parameters
73     * @param RevisionRecord|null $originalRevision
74     * @param Bcp47Code|null $pageLanguage
75     */
76    public function __construct(
77        private StatsFactory $statsFactory,
78        private readonly HtmlTransformFactory $htmlTransformFactory,
79        private readonly ParsoidOutputStash $parsoidOutputStash,
80        private readonly ParserOutputAccess $parserOutputAccess,
81        private readonly PageLookup $pageLookup,
82        private readonly RevisionLookup $revisionLookup,
83        private readonly PageBundleParserOutputConverter $pageBundleParserOutputConverter,
84        array $envOptions = [],
85        ?PageIdentity $page = null,
86        $body = '',
87        array $parameters = [],
88        ?RevisionRecord $originalRevision = null,
89        ?Bcp47Code $pageLanguage = null
90    ) {
91        $this->envOptions = $envOptions + [
92            'outputContentVersion' => Parsoid::defaultHTMLVersion(),
93            'offsetType' => 'byte',
94        ];
95        if ( $page === null ) {
96            wfDeprecated( __METHOD__ . ' without $page', '1.43' );
97        } else {
98            $this->initInternal( $page, $body, $parameters, $originalRevision, $pageLanguage );
99        }
100    }
101
102    public function getParamSettings(): array {
103        // JSON body schema:
104        /*
105        doc:
106            properties:
107                headers:
108                    type: array
109                    items:
110                        type: string
111                body:
112                    type: [ string, object ]
113            required: [ body ]
114
115        body:
116            properties:
117                offsetType:
118                    type: string
119                revid:
120                    type: integer
121                renderid:
122                    type: string
123                etag:
124                    type: string
125                html:
126                    type: [ doc, string ]
127                data-mw:
128                    type: doc
129                original:
130                    properties:
131                        html:
132                            type: doc
133                        source:
134                            type: doc
135                        data-mw:
136                            type: doc
137                        data-parsoid:
138                            type: doc
139            required: [ html ]
140         */
141
142        // FUTURE: more params
143        // - slot (for loading the base content)
144
145        return [
146            // XXX: should we really declare this here? Or should end endpoint do this?
147            //      We are not reading this property...
148            'title' => [
149                Handler::PARAM_SOURCE => 'path',
150                ParamValidator::PARAM_TYPE => 'string',
151                ParamValidator::PARAM_DEFAULT => '',
152                ParamValidator::PARAM_REQUIRED => false,
153                Handler::PARAM_DESCRIPTION => new MessageValue( 'rest-param-desc-html-input-title' )
154            ],
155            // XXX: Needed for compatibility with the parsoid transform endpoint.
156            //      But revid should just be part of the info about the original data
157            //      in the body.
158            'oldid' => [
159                Handler::PARAM_SOURCE => 'path',
160                ParamValidator::PARAM_TYPE => 'int',
161                ParamValidator::PARAM_DEFAULT => 0,
162                ParamValidator::PARAM_REQUIRED => false,
163                Handler::PARAM_DESCRIPTION => new MessageValue( 'rest-param-desc-html-input-oldid' )
164            ],
165            // XXX: Supported for compatibility with the parsoid transform endpoint.
166            //      If given, it should be 'html' or 'pagebundle'.
167            'from' => [
168                Handler::PARAM_SOURCE => 'path',
169                ParamValidator::PARAM_TYPE => 'string',
170                ParamValidator::PARAM_DEFAULT => '',
171                ParamValidator::PARAM_REQUIRED => false,
172                Handler::PARAM_DESCRIPTION => new MessageValue( 'rest-param-desc-html-input-from' )
173            ],
174            // XXX: Supported for compatibility with the parsoid transform endpoint.
175            //      Ignored.
176            'format' => [
177                Handler::PARAM_SOURCE => 'path',
178                ParamValidator::PARAM_TYPE => 'string',
179                ParamValidator::PARAM_DEFAULT => '',
180                ParamValidator::PARAM_REQUIRED => false,
181                Handler::PARAM_DESCRIPTION => new MessageValue( 'rest-param-desc-html-input-format' )
182            ],
183            'contentmodel' => [ // XXX: get this from the Accept header?
184                Handler::PARAM_SOURCE => 'query',
185                ParamValidator::PARAM_TYPE => 'string',
186                ParamValidator::PARAM_DEFAULT => '',
187                ParamValidator::PARAM_REQUIRED => false,
188                Handler::PARAM_DESCRIPTION => new MessageValue( 'rest-param-desc-html-input-contentmodel' )
189            ],
190            'language' => [ // TODO: get this from Accept-Language header?!
191                Handler::PARAM_SOURCE => 'query',
192                ParamValidator::PARAM_TYPE => 'string',
193                ParamValidator::PARAM_DEFAULT => '',
194                ParamValidator::PARAM_REQUIRED => false,
195                Handler::PARAM_DESCRIPTION => new MessageValue( 'rest-param-desc-html-input-language' )
196            ]
197        ];
198    }
199
200    /**
201     * Modify body and parameters to provide compatibility with legacy endpoints.
202     *
203     * @see ParsoidHandler::getRequestAttributes
204     *
205     * @param array<string,mixed> &$body
206     * @param array<string,mixed> &$parameters
207     *
208     * @throws HttpException
209     *
210     * @return void
211     */
212    private static function normalizeParameters( array &$body, array &$parameters ) {
213        // If the revision ID is given in the path, pretend it was given in the body.
214        if ( isset( $parameters['oldid'] ) && (int)$parameters['oldid'] > 0 ) {
215            $body['original']['revid'] = (int)$parameters['oldid'];
216        }
217
218        // If an etag is given in the body, use it as the render ID.
219        // Note that we support ETag format in the renderid field.
220        if ( !empty( $body['original']['etag'] ) ) {
221            // @phan-suppress-next-line PhanTypeInvalidDimOffset false positive
222            $body['original']['renderid'] = $body['original']['etag'];
223        }
224
225        // Accept 'wikitext' as an alias for 'source'.
226        if ( isset( $body['original']['wikitext'] ) ) {
227            // @phan-suppress-next-line PhanTypeInvalidDimOffset false positive
228            $body['original']['source'] = $body['original']['wikitext'];
229            unset( $body['original']['wikitext'] );
230        }
231
232        // If 'from' is not set, we accept page bundle style input as well as full HTML.
233        // If 'from' is set, we only accept page bundle style input if it is set to FORMAT_PAGEBUNDLE.
234        if (
235            isset( $parameters['from'] ) && $parameters['from'] !== '' &&
236            $parameters['from'] !== ParsoidFormatHelper::FORMAT_PAGEBUNDLE
237        ) {
238            unset( $body['original']['data-parsoid']['body'] );
239            unset( $body['original']['data-mw']['body'] );
240            unset( $body['data-mw']['body'] );
241        }
242
243        // If 'from' is given, it must be html or pagebundle.
244        if (
245            isset( $parameters['from'] ) && $parameters['from'] !== '' &&
246            $parameters['from'] !== ParsoidFormatHelper::FORMAT_HTML &&
247            $parameters['from'] !== ParsoidFormatHelper::FORMAT_PAGEBUNDLE
248        ) {
249            throw new LocalizedHttpException(
250                new MessageValue( "rest-unsupported-transform-input", [ $parameters['from'] ] ), 400
251            );
252        }
253
254        if ( isset( $body['contentmodel'] ) && $body['contentmodel'] !== '' ) {
255            $parameters['contentmodel'] = $body['contentmodel'];
256        } elseif ( isset( $parameters['format'] ) && $parameters['format'] !== '' ) {
257            $parameters['contentmodel'] = $parameters['format'];
258        }
259    }
260
261    /**
262     * @param PageIdentity $page
263     * @param array|string $body Body structure, or an HTML string
264     * @param array $parameters
265     * @param RevisionRecord|null $originalRevision
266     * @param Bcp47Code|null $pageLanguage
267     *
268     * @throws HttpException
269     * @deprecated since 1.43; pass arguments to constructor instead
270     */
271    public function init(
272        PageIdentity $page,
273        $body,
274        array $parameters,
275        ?RevisionRecord $originalRevision = null,
276        ?Bcp47Code $pageLanguage = null
277    ) {
278        wfDeprecated( __METHOD__, '1.43' );
279        $this->initInternal( $page, $body, $parameters, $originalRevision, $pageLanguage );
280    }
281
282    /**
283     * @param PageIdentity $page
284     * @param array|string $body Body structure, or an HTML string
285     * @param array $parameters
286     * @param RevisionRecord|null $originalRevision
287     * @param Bcp47Code|null $pageLanguage
288     *
289     * @throws HttpException
290     */
291    private function initInternal(
292        PageIdentity $page,
293        $body,
294        array $parameters,
295        ?RevisionRecord $originalRevision = null,
296        ?Bcp47Code $pageLanguage = null
297    ) {
298        if ( is_string( $body ) ) {
299            $body = [ 'html' => $body ];
300        }
301
302        self::normalizeParameters( $body, $parameters );
303
304        $this->page = $page;
305
306        if ( !isset( $body['html'] ) ) {
307            throw new LocalizedHttpException( new MessageValue( "rest-missing-body-field", [ 'html' ] ) );
308        }
309
310        $html = is_array( $body['html'] ) ? $body['html']['body'] : $body['html'];
311
312        // TODO: validate $body against a proper schema.
313        $this->transform = $this->htmlTransformFactory->getHtmlToContentTransform(
314            $html,
315            $this->page
316        );
317
318        $this->transform->setMetrics( $this->statsFactory );
319
320        // NOTE: Env::getContentModel will fall back to the page's recorded content model
321        //       if none is set here.
322        $this->transform->setOptions( [
323            'contentmodel' => $parameters['contentmodel'] ?? null,
324            'offsetType' => $body['offsetType'] ?? $this->envOptions['offsetType'],
325        ] );
326
327        $original = $body['original'] ?? [];
328        $originalRendering = null;
329
330        if ( !isset( $original['html'] ) && !empty( $original['renderid'] ) ) {
331            $key = $original['renderid'];
332            if ( preg_match( '!^(W/)?".*"$!', $key ) ) {
333                $originalRendering = ParsoidRenderID::newFromETag( $key );
334
335                if ( !$originalRendering ) {
336                    throw new LocalizedHttpException( new MessageValue( "rest-bad-etag", [ $key ] ), 400 );
337                }
338            } else {
339                try {
340                    $originalRendering = ParsoidRenderID::newFromKey( $key );
341                } catch ( InvalidArgumentException ) {
342                    throw new LocalizedHttpException(
343                        new MessageValue( 'rest-parsoid-bad-render-id', [ $key ] ),
344                        400
345                    );
346                }
347            }
348        } elseif ( !empty( $original['html'] ) || !empty( $original['data-parsoid'] ) ) {
349            // NOTE: We might have an incomplete HtmlPageBundle here, with no HTML but with data-parsoid!
350            // XXX: Do we need to support that, or can that just be a 400?
351            $originalRendering = HtmlPageBundle::newFromJsonArray( [
352                'html' => $original['html']['body'] ?? '',
353                'parsoid' => $original['data-parsoid']['body'] ?? null,
354                'mw' => $original['data-mw']['body'] ?? null,
355                'counters' => $original['counters']['body'] ?? null,
356                'version' => null, // will be derived from $original['html']['headers']['content-type']
357                'headers' => $original['html']['headers'] ?? []
358            ] );
359        }
360
361        if ( !$originalRevision && !empty( $original['revid'] ) ) {
362            $originalRevision = (int)$original['revid'];
363        }
364
365        if ( $originalRevision || $originalRendering ) {
366            $this->setOriginal( $originalRevision, $originalRendering );
367        } else {
368            if ( $this->page->exists() ) {
369                $this->statsFactory
370                    ->getCounter( 'html_input_transform_total' )
371                    ->setLabel( 'original_html_given', 'false' )
372                    ->setLabel( 'page_exists', 'true' )
373                    ->setLabel( 'status', 'unknown' )
374                    ->increment();
375            } else {
376                $this->statsFactory
377                    ->getCounter( 'html_input_transform_total' )
378                    ->setLabel( 'original_html_given', 'false' )
379                    ->setLabel( 'page_exists', 'false' )
380                    ->setLabel( 'status', 'unknown' )
381                    ->increment();
382            }
383        }
384
385        if ( isset( $body['data-mw']['body'] ) ) {
386            $this->transform->setModifiedDataMW( $body['data-mw']['body'] );
387        }
388
389        if ( $pageLanguage ) {
390            $this->transform->setContentLanguage( $pageLanguage );
391        } elseif ( isset( $parameters['language'] ) && $parameters['language'] !== '' ) {
392            $pageLanguage = LanguageCode::normalizeNonstandardCodeAndWarn(
393                $parameters['language']
394            );
395            $this->transform->setContentLanguage( $pageLanguage );
396        }
397
398        if ( isset( $original['source']['body'] ) ) {
399            // XXX: do we really have to support wikitext overrides?
400            $this->transform->setOriginalText( $original['source']['body'] );
401        }
402    }
403
404    /**
405     * Return HTMLTransform object, so additional context can be provided by calling setters on it.
406     * @throws \RuntimeException If initInternal() has not yet been called
407     */
408    public function getTransform(): HtmlToContentTransform {
409        if ( !$this->transform ) {
410            throw new \RuntimeException( 'initInternal() must be called before getTransform()' );
411        }
412        return $this->transform;
413    }
414
415    /**
416     * Set metrics sink.
417     */
418    public function setMetrics( StatsFactory $statsFactory ) {
419        $this->statsFactory = $statsFactory;
420
421        if ( $this->transform ) {
422            $this->transform->setMetrics( $statsFactory );
423        }
424    }
425
426    /**
427     * Supply information about the revision and rendering that was the original basis of
428     * the input HTML. This is used to apply selective serialization (selser), if possible.
429     *
430     * @param RevisionRecord|int|null $rev
431     * @param ParsoidRenderID|HtmlPageBundle|ParserOutput|null $originalRendering
432     */
433    public function setOriginal( $rev, $originalRendering ) {
434        if ( $originalRendering instanceof ParsoidRenderID ) {
435            $renderId = $originalRendering;
436
437            // If the client asked for a render ID, load original data from stash
438            try {
439                $selserContext = $this->fetchSelserContextFromStash( $renderId );
440            } catch ( InvalidArgumentException $ex ) {
441                $this->statsFactory
442                    ->getCounter( 'html_input_transform_total' )
443                    ->setLabel( 'original_html_given', 'as_renderid' )
444                    ->setLabel( 'page_exists', 'unknown' )
445                    ->setLabel( 'status', 'bad_renderid' )
446                    ->increment();
447                throw new LocalizedHttpException( new MessageValue( "rest-bad-stash-key" ),
448                    400,
449                    [
450                        'reason' => $ex->getMessage(),
451                        'key' => "$renderId"
452                    ]
453                );
454            }
455
456            if ( !$selserContext ) {
457                // NOTE: When the client asked for a specific stash key (resp. etag),
458                //       we should fail with a 412 if we don't have the specific rendering.
459                //       On the other hand, of the client only provided a base revision ID,
460                //       we can re-parse and hope for the best.
461
462                throw new LocalizedHttpException(
463                    new MessageValue( "rest-no-stashed-content", [ $renderId->getKey() ] ), 412
464                );
465
466                // TODO: This class should provide getETag and getLastModified methods for use by
467                //       the REST endpoint, to provide proper support for conditionals.
468                //       However, that requires some refactoring of how HTTP conditional checks
469                //       work in the Handler base class.
470            }
471
472            if ( !$rev ) {
473                $rev = $renderId->getRevisionID();
474            }
475
476            $originalRendering = $selserContext->getPageBundle();
477            $content = $selserContext->getContent();
478
479            if ( $content ) {
480                $this->transform->setOriginalContent( $content );
481            }
482        } elseif ( !$originalRendering && $rev ) {
483            // The client provided a revision ID, but not stash key.
484            // Try to get a rendering for the given revision, and use it as the basis for selser.
485            // Chances are good that the resulting diff will be reasonably clean.
486            // NOTE: If we don't have a revision ID, we should not attempt selser!
487            // @phan-suppress-next-line PhanTypeMismatchArgumentNullable $this->page is not null
488            $originalRendering = $this->fetchParserOutputFromParsoid( $this->page, $rev, true );
489
490            if ( $originalRendering ) {
491                $this->statsFactory->getCounter( 'html_input_transform_total' )
492                    ->setLabel( 'original_html_given', 'as_revid' )
493                    ->setLabel( 'page_exists', 'unknown' )
494                    ->setLabel( 'status', 'found' )
495                    ->increment();
496            } else {
497                $this->statsFactory->getCounter( 'html_input_transform_total' )
498                    ->setLabel( 'original_html_given', 'as_revid' )
499                    ->setLabel( 'page_exists', 'unknown' )
500                    ->setLabel( 'status', 'not_found' )
501                    ->increment();
502            }
503        } elseif ( $originalRendering ) {
504            $this->statsFactory->getCounter( 'html_input_transform_total' )
505                ->setLabel( 'original_html_given', 'true' )
506                ->setLabel( 'page_exists', 'unknown' )
507                ->setLabel( 'status', 'verbatim' )
508                ->increment();
509        }
510
511        if ( $originalRendering instanceof ParserOutput ) {
512            // Selser expects a full document (head + body). Request
513            // it explicitly so this keeps working once the canonical
514            // ParserOutput is body-only (T393295)
515            $originalRendering = $this->pageBundleParserOutputConverter->htmlPageBundleFromParserOutput(
516                $originalRendering, bodyOnly: false,
517            );
518
519            // NOTE: Use the default if we got a ParserOutput object.
520            //       Don't apply the default if we got passed a HtmlPageBundle,
521            //       in that case, we want to require the version to be explicit.
522            if ( $originalRendering->getContentVersion() === null &&
523                !isset( $originalRendering->headers['content-type'] )
524            ) {
525                $originalRendering->setContentVersion( Parsoid::defaultHTMLVersion() );
526            }
527        }
528
529        if ( !$originalRendering instanceof HtmlPageBundle ) {
530            return;
531        }
532
533        $vOriginal = $originalRendering->getContentVersion();
534        if ( $vOriginal !== null ) {
535            $this->transform->setOriginalSchemaVersion( $vOriginal );
536        } elseif ( !empty( $originalRendering->headers['content-type'] ) ) {
537            $vOriginal = ParsoidFormatHelper::parseContentTypeHeader(
538                // @phan-suppress-next-line PhanTypeArraySuspiciousNullable Silly Phan, we just checked.
539                $originalRendering->headers['content-type']
540            );
541
542            if ( $vOriginal ) {
543                $this->transform->setOriginalSchemaVersion( $vOriginal );
544            }
545        }
546
547        if ( $rev instanceof RevisionRecord ) {
548            $this->transform->setOriginalRevision( $rev );
549        } elseif ( $rev && is_int( $rev ) ) {
550            $this->transform->setOriginalRevisionId( $rev );
551        }
552
553        // NOTE: We might have an incomplete HtmlPageBundle here, with no HTML.
554        //       HtmlPageBundle::$html is declared to not be nullable, so it would be set to the empty
555        //       string if not given.
556        if ( $originalRendering->html !== '' ) {
557            $this->transform->setOriginalHtml( $originalRendering->html );
558        }
559
560        $originalDataParsoid = $originalRendering->parsoid;
561        if ( $originalDataParsoid !== null ) {
562            $this->transform->setOriginalDataParsoid( $originalDataParsoid );
563        }
564
565        $originalDataMW = $originalRendering->mw;
566        if ( $originalDataMW !== null ) {
567            $this->transform->setOriginalDataMW( $originalDataMW );
568        }
569    }
570
571    /**
572     * @return Content the content derived from the input HTML.
573     * @throws HttpException
574     */
575    public function getContent(): Content {
576        try {
577            return $this->transform->htmlToContent();
578        } catch ( ClientError $e ) {
579            throw new LocalizedHttpException(
580                new MessageValue( 'rest-html-backend-error', [ $e->getMessage() ] ),
581                400,
582                [ 'reason' => $e->getMessage() ]
583            );
584        } catch ( ResourceLimitExceededException $e ) {
585            throw new LocalizedHttpException(
586                new MessageValue( 'rest-resource-limit-exceeded' ),
587                413,
588                [ 'reason' => $e->getMessage() ]
589            );
590        } catch ( UnknownContentModelException $e ) {
591            throw new LocalizedHttpException(
592                new MessageValue( "rest-unknown-content-model", [ $e->getModelId() ] ),
593                400
594            );
595        }
596    }
597
598    /**
599     * Creates a response containing the content derived from the input HTML.
600     * This will set the appropriate Content-Type header.
601     */
602    public function putContent( ResponseInterface $response ) {
603        $content = $this->getContent();
604        $data = $content->serialize();
605
606        try {
607            $contentType = ParsoidFormatHelper::getContentType(
608                $content->getModel(),
609                $this->envOptions['outputContentVersion']
610            );
611        } catch ( InvalidArgumentException ) {
612            // If Parsoid doesn't know the content type,
613            // ask the ContentHandler!
614            $contentType = $content->getDefaultFormat();
615        }
616
617        $response->setHeader( 'Content-Type', $contentType );
618        $response->getBody()->write( $data );
619    }
620
621    /**
622     * @param PageIdentity $page
623     * @param RevisionRecord|int $revision
624     * @param bool $mayParse
625     *
626     * @return ParserOutput|null
627     * @throws HttpException
628     */
629    private function fetchParserOutputFromParsoid( PageIdentity $page, $revision, bool $mayParse ): ?ParserOutput {
630        $parserOptions = ParserOptions::newFromAnon();
631        $parserOptions->setUseParsoid();
632
633        try {
634            if ( !$page instanceof PageRecord ) {
635                $name = "$page";
636                $page = $this->pageLookup->getPageByReference( $page );
637                if ( !$page ) {
638                    throw new RevisionAccessException( 'Page {name} not found',
639                        [ 'name' => $name ] );
640                }
641            }
642
643            if ( is_int( $revision ) ) {
644                $revId = $revision;
645                // Don't pass $page here: on a page mismatch RevisionStore would assert
646                // and fail hard (500). Let the explicit check below return a clean 404. (T433351)
647                $revision = $this->revisionLookup->getRevisionById( $revId );
648
649                if ( !$revision ) {
650                    throw new RevisionAccessException( 'Revision {revId} not found',
651                        [ 'revId' => $revId ] );
652                }
653            }
654
655            if ( $page->getId() !== $revision->getPageId() ) {
656                throw new RevisionAccessException( 'Revision {revId} does not belong to page {name}',
657                    [ 'name' => $page->getDBkey(),
658                        'revId' => $revision->getId() ] );
659            }
660
661            if ( $mayParse ) {
662                try {
663                    $status = $this->parserOutputAccess->getParserOutput(
664                        $page, $parserOptions, $revision
665                    );
666                } catch ( ClientError $e ) {
667                    $status = Status::newFatal( 'parsoid-client-error', $e->getMessage() );
668                } catch ( ResourceLimitExceededException $e ) {
669                    $status = Status::newFatal( 'parsoid-resource-limit-exceeded', $e->getMessage() );
670                }
671
672                if ( !$status->isOK() ) {
673                    $this->throwHttpExceptionForStatus( $status );
674                }
675
676                $parserOutput = $status->getValue();
677            } else {
678                $parserOutput = $this->parserOutputAccess->getCachedParserOutput(
679                    $page, $parserOptions, $revision
680                );
681            }
682        } catch ( RevisionAccessException $e ) {
683            // The client supplied bad revision ID, or the revision was deleted or suppressed.
684            throw new LocalizedHttpException( new MessageValue( "rest-specified-revision-unavailable" ),
685                404,
686                [ 'reason' => $e->getMessage() ]
687            );
688        }
689
690        return $parserOutput;
691    }
692
693    /**
694     * @param ParsoidRenderID $renderID
695     *
696     * @return SelserContext|null
697     */
698    private function fetchSelserContextFromStash( $renderID ): ?SelserContext {
699        $selserContext = $this->parsoidOutputStash->get( $renderID );
700        $labels = [
701            'original_html_given' => 'as_renderid',
702            'page_exists' => 'unknown',
703            'status' => 'hit-stashed'
704        ];
705        $counter = $this->statsFactory->getCounter( 'html_input_transform_total' );
706        if ( $selserContext ) {
707            $counter->setLabels( $labels )
708                ->increment();
709            return $selserContext;
710        } else {
711            // Looks like the rendering is gone from stash (or the client send us a bogus key).
712            // Try to load it from the parser cache instead.
713            // On a wiki with low edit frequency, there is a good chance that it's still there.
714            try {
715                // @phan-suppress-next-line PhanTypeMismatchArgumentNullable $this->page is not null
716                $parserOutput = $this->fetchParserOutputFromParsoid( $this->page, $renderID->getRevisionID(), false );
717
718                if ( !$parserOutput ) {
719                    $labels[ 'status' ] = 'miss-fallback_not_found';
720                    $counter->setLabels( $labels )->increment();
721                    return null;
722                }
723
724                $cachedRenderID = ParsoidRenderID::newFromParserOutput( $parserOutput );
725                if ( $cachedRenderID->getKey() !== $renderID->getKey() ) {
726                    $labels[ 'status' ] = 'mismatch-fallback_not_found';
727                    $counter->setLabels( $labels )
728                        ->increment();
729
730                    // It's not the correct rendering.
731                    return null;
732                }
733                $labels[ 'status' ] = 'hit-fallback_found';
734                $counter->setLabels( $labels )
735                    ->increment();
736
737                // Full document (head + body) for selser; see the note above.
738                $pb = $this->pageBundleParserOutputConverter->htmlPageBundleFromParserOutput(
739                    $parserOutput, bodyOnly: false,
740                );
741                return new SelserContext( $pb, $renderID->getRevisionID() );
742            } catch ( HttpException ) {
743                $labels[ 'status' ] = 'failed-fallback_not_found';
744                $counter->setLabels( $labels )
745                    ->increment();
746
747                // If the revision isn't found, don't trigger a 404. Return null to trigger a 412.
748                return null;
749            }
750        }
751    }
752
753    /**
754     * @param Status $status
755     *
756     * @return never
757     * @throws HttpException
758     */
759    private function throwHttpExceptionForStatus( Status $status ) {
760        // TODO: make this nicer.
761        if ( $status->hasMessage( 'parsoid-resource-limit-exceeded' ) ) {
762            throw new LocalizedHttpException( new MessageValue( "rest-parsoid-resource-exceeded" ),
763                413,
764                [ 'reason' => $status->getHTML() ]
765            );
766        } elseif ( $status->hasMessage( 'missing-revision-permission' ) ) {
767            throw new LocalizedHttpException( new MessageValue( 'rest-permission-denied-revision' ),
768                403,
769                [ 'reason' => $status->getHTML() ]
770            );
771        } else {
772            throw new LocalizedHttpException( new MessageValue( "rest-parsoid-error" ),
773                400,
774                [ 'reason' => $status->getHTML() ]
775            );
776        }
777    }
778
779}