Debian Codegraph @

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