Debian Codegraph @

includes/parser/Parsoid/HtmlToContentTransform.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Parser\Parsoid;
4
5 use Composer\Semver\Semver;
6 use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface;
7 use LogicException;
8 use MediaWiki\Content\Content;
9 use MediaWiki\Content\ContentHandler;
10 use MediaWiki\Content\IContentHandlerFactory;
11 use MediaWiki\Page\PageIdentity;
12 use MediaWiki\Parser\Parsoid\Config\PageConfigFactory;
13 use MediaWiki\Rest\HttpException;
14 use MediaWiki\Rest\LocalizedHttpException;
15 use MediaWiki\Revision\MutableRevisionRecord;
16 use MediaWiki\Revision\RevisionAccessException;
17 use MediaWiki\Revision\RevisionRecord;
18 use MediaWiki\Revision\SlotRecord;
19 use Wikimedia\Bcp47Code\Bcp47Code;
20 use Wikimedia\Message\MessageValue;
21 use Wikimedia\Parsoid\Config\PageConfig;
22 use Wikimedia\Parsoid\Core\ClientError;
23 use Wikimedia\Parsoid\Core\PageBundle;
24 use Wikimedia\Parsoid\Core\ResourceLimitExceededException;
25 use Wikimedia\Parsoid\Core\SelserData;
26 use Wikimedia\Parsoid\DOM\Document;
27 use Wikimedia\Parsoid\DOM\Element;
28 use Wikimedia\Parsoid\Parsoid;
29 use Wikimedia\Parsoid\Utils\ContentUtils;
30 use Wikimedia\Parsoid\Utils\DOMCompat;
31 use Wikimedia\Parsoid\Utils\DOMUtils;
32 use Wikimedia\Stats\StatsFactory;
33
34 /**
35 * This class allows HTML to be transformed to a page content source format such as wikitext.
36 *
37 * @since 1.40
38 * @unstable should be stable before 1.40 release
39 */
40 class HtmlToContentTransform {
41 private array $options = [];
42 private ?int $oldid = null;
43 private ?Bcp47Code $contentLanguage = null;
44 private ?Content $originalContent = null;
45 private ?RevisionRecord $originalRevision = null;
46 /**
47 * Whether $this->doc has had any necessary processing applied,
48 * such as injecting data-parsoid attributes from a PageBundle.
49 */
50 private bool $docHasBeenProcessed = false;
51 private ?Document $doc = null;
52 private ?Element $originalBody = null;
53 protected ?StatsFactory $metrics = null;
54 private PageBundle $modifiedPageBundle;
55 private PageBundle $originalPageBundle;
56 private ?PageConfig $pageConfig = null;
57 private Parsoid $parsoid;
58 private array $parsoidSettings;
59 private PageIdentity $page;
60 private PageConfigFactory $pageConfigFactory;
61 private IContentHandlerFactory $contentHandlerFactory;
62
63 /**
64 * @param string $modifiedHTML
65 * @param PageIdentity $page
66 * @param Parsoid $parsoid
67 * @param array $parsoidSettings
68 * @param PageConfigFactory $pageConfigFactory
69 * @param IContentHandlerFactory $contentHandlerFactory
70 */
71 public function __construct(
72 string $modifiedHTML,
73 PageIdentity $page,
74 Parsoid $parsoid,
75 array $parsoidSettings,
76 PageConfigFactory $pageConfigFactory,
77 IContentHandlerFactory $contentHandlerFactory
78 ) {
79 $this->parsoid = $parsoid;
80 $this->parsoidSettings = $parsoidSettings;
81 $this->modifiedPageBundle = new PageBundle( $modifiedHTML );
82 $this->originalPageBundle = new PageBundle( '' );
83 $this->page = $page;
84 $this->pageConfigFactory = $pageConfigFactory;
85 $this->contentHandlerFactory = $contentHandlerFactory;
86 }
87
88 /**
89 * Set metrics sink.
90 *
91 * @note Passing a StatsdDataFactoryInterface here has been deprecated
92 * since 1.43.
93 *
94 * @param StatsFactory|StatsdDataFactoryInterface $metrics
95 */
96 public function setMetrics( $metrics ): void {
97 if ( $metrics instanceof StatsdDataFactoryInterface ) {
98 wfDeprecated( __METHOD__ . ' with StatsdDataFactoryInterface', '1.43' );
99 return;
100 }
101 $this->metrics = $metrics;
102 }
103
104 private function incrementMetrics( string $key, array $labels, ?string $statsdKey ) {
105 if ( $this->metrics ) {
106 $counter = $this->metrics->getCounter( $key )->setLabels( $labels );
107 if ( $statsdKey ) {
108 $counter = $counter->copyToStatsdAt( $statsdKey );
109 }
110 $counter->increment();
111 }
112 }
113
114 public function setOptions( array $options ) {
115 $this->options = $options;
116 }
117
118 /**
119 * @param RevisionRecord $rev
120 */
121 public function setOriginalRevision( RevisionRecord $rev ): void {
122 if ( $this->pageConfig ) {
123 throw new LogicException( 'Cannot set revision after using the PageConfig' );
124 }
125 if ( $this->originalRevision ) {
126 throw new LogicException( 'Cannot set revision again' );
127 }
128
129 $this->originalRevision = $rev;
130 $this->oldid = $rev->getId();
131 }
132
133 /**
134 * @param int $oldid
135 */
136 public function setOriginalRevisionId( int $oldid ): void {
137 if ( $this->pageConfig ) {
138 throw new LogicException( 'Cannot set revision ID after using the PageConfig' );
139 }
140 if ( $this->originalRevision ) {
141 throw new LogicException( 'Cannot set revision again' );
142 }
143
144 $this->oldid = $oldid;
145 }
146
147 /**
148 * @param Bcp47Code $lang
149 */
150 public function setContentLanguage( Bcp47Code $lang ): void {
151 if ( $this->pageConfig ) {
152 throw new LogicException( 'Cannot set content language after using the PageConfig' );
153 }
154
155 $this->contentLanguage = $lang;
156 }
157
158 /**
159 * Sets the original source text (usually wikitext).
160 *
161 * @param string $text
162 */
163 public function setOriginalText( string $text ): void {
164 $content = $this->getContentHandler()->unserializeContent( $text );
165 $this->setOriginalContent( $content );
166 }
167
168 /**
169 * Sets the original content (such as wikitext).
170 *
171 * @param Content $content
172 */
173 public function setOriginalContent( Content $content ): void {
174 if ( $this->pageConfig ) {
175 throw new LogicException( 'Cannot set text after using the PageConfig' );
176 }
177 if ( $this->originalRevision ) {
178 throw new LogicException( 'Cannot set wikitext after using the PageConfig' );
179 }
180
181 $this->options['contentmodel'] = $content->getModel();
182 $this->originalContent = $content;
183 }
184
185 private function validatePageBundle( PageBundle $pb ) {
186 if ( !$pb->version ) {
187 return;
188 }
189
190 $errorMessage = '';
191 if ( !$pb->validate( $pb->version, $errorMessage ) ) {
192 throw new ClientError( $errorMessage );
193 }
194 }
195
196 /**
197 * @note Call this after all original data has been set!
198 *
199 * @param array $modifiedDataMW
200 */
201 public function setModifiedDataMW( array $modifiedDataMW ): void {
202 // Relies on setOriginalSchemaVersion having been called already.
203 if ( !Semver::satisfies( $this->getSchemaVersion(), '^999.0.0' ) ) {
204 throw new ClientError( 'Modified data-mw is not supported by schema version '
205 . $this->getSchemaVersion() );
206 }
207
208 $this->modifiedPageBundle->mw = $modifiedDataMW;
209 }
210
211 /**
212 * @param string $originalSchemaVeraion
213 */
214 public function setOriginalSchemaVersion( string $originalSchemaVeraion ): void {
215 $this->originalPageBundle->version = $originalSchemaVeraion;
216 }
217
218 /**
219 * @param string $originalHtml
220 */
221 public function setOriginalHtml( string $originalHtml ): void {
222 if ( $this->doc ) {
223 throw new LogicException( __FUNCTION__ . ' cannot be called after' .
224 ' getModifiedDocument()' );
225 }
226
227 $this->originalPageBundle->html = $originalHtml;
228 }
229
230 /**
231 * @param array $originalDataMW
232 */
233 public function setOriginalDataMW( array $originalDataMW ): void {
234 if ( $this->doc ) {
235 throw new LogicException( __FUNCTION__ . ' cannot be called after getModifiedDocument()' );
236 }
237
238 $this->originalPageBundle->mw = $originalDataMW;
239
240 // Modified data-mw is going to be the same as original data-mw,
241 // unless specified otherwise.
242 if ( $this->modifiedPageBundle->mw === null ) {
243 $this->modifiedPageBundle->mw = $originalDataMW;
244 }
245 }
246
247 /**
248 * @param array $originalDataParsoid
249 */
250 public function setOriginalDataParsoid( array $originalDataParsoid ): void {
251 if ( $this->doc ) {
252 throw new LogicException( __FUNCTION__ . ' cannot be called after getModifiedDocument()' );
253 }
254
255 // data-parsoid is going to be the same for original and modified.
256 $this->originalPageBundle->parsoid = $originalDataParsoid;
257 $this->modifiedPageBundle->parsoid = $originalDataParsoid;
258 }
259
260 /**
261 * @return PageConfig
262 */
263 private function getPageConfig(): PageConfig {
264 if ( !$this->pageConfig ) {
265
266 // XXX: do we even have to support wikitext overrides? What's the use case?
267 if ( $this->originalContent !== null ) {
268 // Create a mutable revision record point to the same revision
269 // and set to the desired content.
270 $revision = new MutableRevisionRecord( $this->page );
271 if ( $this->oldid ) {
272 $revision->setId( $this->oldid );
273 }
274
275 $revision->setSlot(
276 SlotRecord::newUnsaved(
277 SlotRecord::MAIN,
278 $this->originalContent
279 )
280 );
281 } else {
282 // NOTE: PageConfigFactory allows $revision to be an int ID or a RevisionRecord.
283 $revision = $this->originalRevision ?: $this->oldid;
284 }
285
286 try {
287 $this->pageConfig = $this->pageConfigFactory->create(
288 $this->page,
289 null,
290 $revision,
291 null,
292 $this->contentLanguage
293 );
294 } catch ( RevisionAccessException $exception ) {
295 // TODO: Throw a different exception, this class should not know
296 // about HTTP status codes.
297 throw new LocalizedHttpException( new MessageValue( "rest-specified-revision-unavailable" ), 404 );
298 }
299 }
300
301 return $this->pageConfig;
302 }
303
304 /**
305 * The size of the modified HTML in characters.
306 *
307 * @return int
308 */
309 public function getModifiedHtmlSize(): int {
310 return mb_strlen( $this->modifiedPageBundle->html );
311 }
312
313 private function getModifiedDocumentRaw(): Document {
314 if ( !$this->doc ) {
315 $this->doc = $this->parseHTML( $this->modifiedPageBundle->html, true );
316 $this->modifiedPageBundle->version = DOMUtils::extractInlinedContentVersion( $this->doc );
317 }
318
319 return $this->doc;
320 }
321
322 public function getModifiedDocument(): Document {
323 $doc = $this->getModifiedDocumentRaw();
324
325 if ( !$this->docHasBeenProcessed ) {
326 $this->applyPageBundle( $this->doc, $this->modifiedPageBundle );
327
328 $this->docHasBeenProcessed = true;
329 }
330
331 return $doc;
332 }
333
334 /**
335 * NOTE: The return value of this method depends on
336 * setOriginalData() having been called first.
337 *
338 * @return bool
339 */
340 public function hasOriginalHtml(): bool {
341 return $this->originalPageBundle->html !== null && $this->originalPageBundle->html !== '';
342 }
343
344 /**
345 * NOTE: The return value of this method depends on
346 * setOriginalData() having been called first.
347 *
348 * @return bool
349 */
350 public function hasOriginalDataParsoid(): bool {
351 return $this->originalPageBundle->parsoid !== null;
352 }
353
354 /**
355 * Returns the original HTML, with any necessary processing applied.
356 *
357 * @todo Make this method redundant, nothing should operate on HTML strings.
358 *
359 * @return string
360 */
361 public function getOriginalHtml(): string {
362 // NOTE: Schema version should have been set explicitly,
363 // so don't call getOriginalSchemaVersion,
364 // which will silently fall back to the default.
365 if ( !$this->originalPageBundle->version ) {
366 throw new ClientError(
367 'Content-type of original html is missing.'
368 );
369 }
370
371 if ( !$this->originalBody ) {
372 // NOTE: Make sure we called getOriginalBody() at least once before we
373 // return the original HTML, so downgrades can be applied,
374 // data-parsoid can be injected, and $this->originalPageBundle->html
375 // is updated accordingly.
376
377 if ( $this->hasOriginalDataParsoid() || $this->needsDowngrade( $this->originalPageBundle ) ) {
378 $this->getOriginalBody();
379 }
380 }
381
382 return $this->originalPageBundle->html ?: '';
383 }
384
385 /**
386 * @param string $html
387 * @param bool $validateXMLNames
388 *
389 * @return Document
390 * @throws ClientError
391 */
392 protected function parseHTML( string $html, bool $validateXMLNames = false ): Document {
393 return DOMUtils::parseHTML( $html, $validateXMLNames );
394 }
395
396 /**
397 * NOTE: The return value of this method depends on
398 * setOriginalData() having been called first.
399 *
400 * @return Element
401 * @throws ClientError
402 */
403 public function getOriginalBody(): Element {
404 if ( !$this->hasOriginalHtml() ) {
405 throw new LogicException(
406 'No original data supplied, call hasOriginalHtml() first.'
407 );
408 }
409
410 if ( $this->originalBody ) {
411 return $this->originalBody;
412 }
413
414 // NOTE: Schema version should have been set explicitly,
415 // so don't call getOriginalSchemaVersion,
416 // which will silently fall back to the default.
417 if ( !$this->originalPageBundle->version ) {
418 throw new ClientError(
419 'Content-type of original html is missing.'
420 );
421 }
422
423 if ( $this->needsDowngrade( $this->originalPageBundle ) ) {
424 $this->downgradeOriginalData( $this->originalPageBundle, $this->getSchemaVersion() );
425 }
426
427 $doc = $this->parseHTML( $this->originalPageBundle->html );
428
429 $this->applyPageBundle( $doc, $this->originalPageBundle );
430
431 $this->originalBody = DOMCompat::getBody( $doc );
432
433 // XXX: use a separate field??
434 $this->originalPageBundle->html = ContentUtils::toXML( $this->originalBody );
435
436 return $this->originalBody;
437 }
438
439 public function getOriginalSchemaVersion(): string {
440 return $this->originalPageBundle->version ?: $this->getSchemaVersion();
441 }
442
443 /**
444 * NOTE: The return value of this method depends on
445 * setOriginalData() having been called first.
446 *
447 * @return string
448 */
449 public function getSchemaVersion(): string {
450 // Get the content version of the edited doc, if available.
451 // Make sure $this->modifiedPageBundle->version is initialized.
452 $this->getModifiedDocumentRaw();
453 $inputContentVersion = $this->modifiedPageBundle->version;
454
455 if ( !$inputContentVersion ) {
456 $this->incrementMetrics(
457 'html2wt_original_version_total',
458 [ 'input_content_version' => 'none' ],
459 'html2wt.original.version.notinline'
460 );
461 $inputContentVersion = $this->originalPageBundle->version ?: Parsoid::defaultHTMLVersion();
462 }
463
464 return $inputContentVersion;
465 }
466
467 public function getOriginalRevisionId(): ?int {
468 return $this->oldid;
469 }
470
471 public function knowsOriginalContent(): bool {
472 return $this->originalRevision || $this->oldid || $this->originalContent !== null;
473 }
474
475 public function getContentModel(): string {
476 return $this->options['contentmodel'] ?? CONTENT_MODEL_WIKITEXT;
477 }
478
479 public function getOffsetType(): string {
480 return $this->options['offsetType'] ?? 'byte';
481 }
482
483 private function needsDowngrade( PageBundle $pb ): bool {
484 $vOriginal = $pb->version;
485 $vEdited = $this->getSchemaVersion();
486
487 // Downgrades are only expected to be between major version
488 //
489 // RESTBase was only expected to store latest version. If a client asked for a version
490 // not satisfied by the latest version, it would downgrade the stored version where
491 // possible. So, it's the original version that needs to satisfy the edited version,
492 // otherwise it needs downgrading.
493 //
494 // There's also the case where an old version is not stored and a re-parse must occur.
495 // Here again the original version generated will be the latest, either satisfying
496 // the edited or needing downgrading.
497 return $vOriginal !== null && !Semver::satisfies( $vOriginal, "^{$vEdited}" );
498 }
499
500 private function downgradeOriginalData( PageBundle $pb, string $targetSchemaVersion ) {
501 if ( $pb->version === null ) {
502 throw new ClientError( 'Missing schema version' );
503 }
504
505 if ( $targetSchemaVersion === $pb->version ) {
506 // nothing to do.
507 return;
508 }
509
510 if ( !$pb->parsoid ) {
511 // XXX: Should we also support downgrades if $pb->html has everything inlined?
512 // XXX: The downgrade should really be an operation on the DOM.
513 return;
514 }
515
516 // We need to downgrade the original to match the edited doc's version.
517 $downgrade = Parsoid::findDowngrade( $pb->version, $targetSchemaVersion );
518
519 if ( !$downgrade ) {
520 throw new ClientError(
521 "No downgrade possible from schema version {$pb->version} to {$targetSchemaVersion}."
522 );
523 }
524
525 $this->incrementMetrics(
526 "downgrade_total",
527 [ 'from' => $downgrade['from'], 'to' => $downgrade['to'] ],
528 "downgrade.from.{$downgrade['from']}.to.{$downgrade['to']}"
529 );
530
531 $downgradeTime = microtime( true );
532 Parsoid::downgrade( $downgrade, $pb );
533 if ( $this->metrics ) {
534 $this->metrics
535 ->getTiming( 'downgrade_time_ms' )
536 ->copyToStatsdAt( 'downgrade.time' )
537 ->observe( ( microtime( true ) - $downgradeTime ) * 1000 );
538 }
539 // NOTE: Set $this->originalBody to null so getOriginalBody() will re-generate it.
540 // XXX: Parsoid::downgrade operates on the parsed Document, would be nice
541 // if we could get that instead of getting back HTML which we have to
542 // parse again!
543 $this->originalBody = null;
544 }
545
546 /**
547 * @param Document $doc
548 * @param PageBundle $pb
549 *
550 * @throws ClientError
551 */
552 private function applyPageBundle( Document $doc, PageBundle $pb ): void {
553 if ( $pb->parsoid === null && $pb->mw === null ) {
554 return;
555 }
556
557 // Verify that the top-level parsoid object either doesn't contain
558 // offsetType, or that it matches the conversion that has been
559 // explicitly requested.
560 if ( isset( $pb->parsoid['offsetType'] ) ) {
561 $offsetType = $this->getOffsetType();
562 $origOffsetType = $pb->parsoid['offsetType'] ?? $offsetType;
563 if ( $origOffsetType !== $offsetType ) {
564 throw new ClientError(
565 'DSR offsetType mismatch: ' . $origOffsetType . ' vs ' . $offsetType
566 );
567 }
568 }
569
570 $this->validatePageBundle( $pb );
571 PageBundle::apply( $doc, $pb );
572 }
573
574 /**
575 * Get a selective serialization (selser) data object. This
576 * can be null if selser is not enabled or oldid is not available.
577 *
578 * @return SelserData|null
579 * @throws HttpException
580 */
581 private function getSelserData(): ?SelserData {
582 $oldhtml = $this->hasOriginalHtml() ? $this->getOriginalHtml() : null;
583
584 // Selser requires knowledge of the original wikitext.
585 $knowsOriginal = $this->knowsOriginalContent();
586
587 if ( $knowsOriginal && !empty( $this->parsoidSettings['useSelser'] ) ) {
588 if ( !$this->getPageConfig()->getRevisionContent() ) {
589 throw new LocalizedHttpException( new MessageValue( "rest-previous-revision-unavailable" ),
590 409 );
591 }
592
593 // TODO: T234548/T234549 - $pageConfig->getPageMainContent() is deprecated:
594 // should use $env->topFrame->getSrcText()
595 $selserData = new SelserData( $this->getPageConfig()->getPageMainContent(),
596 $oldhtml );
597 } else {
598 $selserData = null;
599 }
600
601 return $selserData;
602 }
603
604 private function getContentHandler(): ContentHandler {
605 $model = $this->getContentModel();
606
607 return $this->contentHandlerFactory
608 ->getContentHandler( $model );
609 }
610
611 /**
612 * Returns a Content object derived from the supplied HTML.
613 *
614 * @return Content
615 */
616 public function htmlToContent(): Content {
617 $text = $this->htmlToText();
618 $content = $this->getContentHandler()->unserializeContent( $text );
619
620 return $content;
621 }
622
623 /**
624 * Converts the input HTML to source format, typically wikitext.
625 *
626 * @see Parsoid::dom2wikitext
627 *
628 * @return string
629 */
630 private function htmlToText(): string {
631 $doc = $this->getModifiedDocument();
632 $htmlSize = $this->getModifiedHtmlSize();
633 $inputContentVersion = $this->getSchemaVersion();
634 $selserData = $this->getSelserData();
635
636 try {
637 $text = $this->parsoid->dom2wikitext( $this->getPageConfig(), $doc, [
638 'inputContentVersion' => $inputContentVersion,
639 'offsetType' => $this->getOffsetType(),
640 'contentmodel' => $this->getContentModel(),
641 'htmlSize' => $htmlSize, // used to trigger status 413 if the input is too big
642 ], $selserData );
643 } catch ( ClientError $e ) {
644 throw new LocalizedHttpException( new MessageValue( "rest-parsoid-error", [ $e->getMessage() ] ), 400 );
645 } catch ( ResourceLimitExceededException $e ) {
646 throw new LocalizedHttpException(
647 new MessageValue( "rest-parsoid-resource-exceeded", [ $e->getMessage() ] ), 413
648 );
649 }
650
651 return $text;
652 }
653
654 }