Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
51.96% covered (warning)
51.96%
159 / 306
11.11% covered (danger)
11.11%
2 / 18
CRAP
0.00% covered (danger)
0.00%
0 / 1
Parsoid
51.96% covered (warning)
51.96%
159 / 306
11.11% covered (danger)
11.11%
2 / 18
629.86
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 version
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 defaultHTMLVersion
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 resolveContentVersion
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
20
 setupCommonOptions
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
42
 parseWikitext
0.00% covered (danger)
0.00%
0 / 30
0.00% covered (danger)
0.00%
0 / 1
72
 wikitext2html
97.44% covered (success)
97.44%
38 / 39
0.00% covered (danger)
0.00%
0 / 1
7
 recordParseMetrics
50.00% covered (danger)
50.00%
34 / 68
0.00% covered (danger)
0.00%
0 / 1
19.12
 wikitext2lint
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 dom2wikitext
95.45% covered (success)
95.45%
21 / 22
0.00% covered (danger)
0.00%
0 / 1
3
 recordSerializationMetrics
72.41% covered (warning)
72.41%
21 / 29
0.00% covered (danger)
0.00%
0 / 1
4.34
 html2wikitext
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 pb2pb
97.44% covered (success)
97.44%
38 / 39
0.00% covered (danger)
0.00%
0 / 1
6
 findDowngrade
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
20
 downgrade
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
42
 downgrade999to2
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
2
 prepareAndLoadDocOrBundle
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
30
 pageBundleHeaders
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2declare( strict_types = 1 );
3
4namespace Wikimedia\Parsoid;
5
6use Composer\InstalledVersions;
7use Composer\Semver\Comparator;
8use Composer\Semver\Semver;
9use InvalidArgumentException;
10use LogicException;
11use Wikimedia\Assert\Assert;
12use Wikimedia\Parsoid\Config\DataAccess;
13use Wikimedia\Parsoid\Config\Env;
14use Wikimedia\Parsoid\Config\PageConfig;
15use Wikimedia\Parsoid\Config\SiteConfig;
16use Wikimedia\Parsoid\Config\StubMetadataCollector;
17use Wikimedia\Parsoid\Core\ContentMetadataCollector;
18use Wikimedia\Parsoid\Core\DOMCompat;
19use Wikimedia\Parsoid\Core\DomPageBundle;
20use Wikimedia\Parsoid\Core\HtmlPageBundle;
21use Wikimedia\Parsoid\Core\ResourceLimitExceededException;
22use Wikimedia\Parsoid\Core\SelectiveUpdateData;
23use Wikimedia\Parsoid\DOM\Document;
24use Wikimedia\Parsoid\Ext\ParsoidExtensionAPI;
25use Wikimedia\Parsoid\Logger\LintLogger;
26use Wikimedia\Parsoid\Mocks\MockSiteConfig;
27use Wikimedia\Parsoid\Utils\ComputeSelectiveStats;
28use Wikimedia\Parsoid\Utils\ContentUtils;
29use Wikimedia\Parsoid\Utils\DOMDataUtils;
30use Wikimedia\Parsoid\Utils\DOMUtils;
31use Wikimedia\Parsoid\Utils\Histogram;
32use Wikimedia\Parsoid\Utils\PHPUtils;
33use Wikimedia\Parsoid\Utils\Timing;
34use Wikimedia\Parsoid\Wt2Html\DOM\Processors\AddRedLinks;
35use Wikimedia\Parsoid\Wt2Html\DOM\Processors\ConvertOffsets;
36
37class Parsoid {
38
39    /**
40     * Available HTML content versions.
41     * @see https://www.mediawiki.org/wiki/Parsoid/API#Content_Negotiation
42     * @see https://www.mediawiki.org/wiki/Specs/HTML#Versioning
43     */
44    public const AVAILABLE_VERSIONS = [ '2.8.0', '999.0.0' ];
45
46    private const DOWNGRADES = [
47        [ 'from' => '999.0.0', 'to' => '2.0.0', 'func' => 'downgrade999to2' ],
48    ];
49
50    /** @var SiteConfig */
51    private $siteConfig;
52
53    /** @var DataAccess */
54    private $dataAccess;
55    private Histogram $histogram;
56
57    public function __construct(
58        SiteConfig $siteConfig, DataAccess $dataAccess
59    ) {
60        $this->siteConfig = $siteConfig;
61        $this->dataAccess = $dataAccess;
62        $this->histogram = new Histogram( $this->siteConfig );
63    }
64
65    /**
66     * Returns the currently-installed version of Parsoid.
67     * @return string
68     */
69    public static function version(): string {
70        try {
71            // See https://getcomposer.org/doc/07-runtime.md#knowing-the-version-of-package-x
72            return InstalledVersions::getVersion( 'wikimedia/parsoid' ) ??
73                // From the composer runtime API docs:
74                // "It is nonetheless a good idea to make sure you
75                // handle the null return value as gracefully as
76                // possible for safety."
77                'null';
78        } catch ( \Throwable ) {
79            // Belt-and-suspenders protection against parts of the composer
80            // runtime API being absent in production.
81            return 'error';
82        }
83    }
84
85    /**
86     * Returns the default HTML content version
87     * @return string
88     */
89    public static function defaultHTMLVersion(): string {
90        return self::AVAILABLE_VERSIONS[0];
91    }
92
93    /**
94     * See if any content version Parsoid knows how to produce satisfies the
95     * the supplied version, when interpreted with semver caret semantics.
96     * This will allow us to make backwards compatible changes, without the need
97     * for clients to bump the version in their headers all the time.
98     */
99    public static function resolveContentVersion( string $version ): ?string {
100        foreach ( self::AVAILABLE_VERSIONS as $a ) {
101            if ( Semver::satisfies( $a, "^{$version}" ) &&
102                // The section wrapping in 1.6.x should have induced a major
103                // version bump, since it requires upgrading clients to
104                // handle it.  We therefore hardcode this in so that we can
105                // fail hard.
106                Comparator::greaterThanOrEqualTo( $version, '1.6.0' )
107            ) {
108                return $a;
109            }
110        }
111        return null;
112    }
113
114    private function setupCommonOptions( array $options ): array {
115        $envOptions = [];
116        if ( isset( $options['offsetType'] ) ) {
117            $envOptions['offsetType'] = $options['offsetType'];
118        }
119        if ( isset( $options['traceFlags'] ) ) {
120            $envOptions['traceFlags'] = $options['traceFlags'];
121        }
122        if ( isset( $options['dumpFlags'] ) ) {
123            $envOptions['dumpFlags'] = $options['dumpFlags'];
124        }
125        if ( isset( $options['debugFlags'] ) ) {
126            $envOptions['debugFlags'] = $options['debugFlags'];
127        }
128        if ( isset( $options['logLevels'] ) ) {
129            $envOptions['logLevels'] = $options['logLevels'];
130        }
131        return $envOptions;
132    }
133
134    /**
135     * Parsing code shared between the next two methods.
136     *
137     * @param PageConfig $pageConfig
138     * @param ContentMetadataCollector $metadata
139     * @param array $options See wikitext2html.
140     * @param ?SelectiveUpdateData $selparData See wikitext2html.
141     * @return list{Env,Document,?string}
142     *  The returned document is in "prepared and loaded" form.
143     */
144    private function parseWikitext(
145        PageConfig $pageConfig,
146        ContentMetadataCollector $metadata,
147        array $options = [],
148        ?SelectiveUpdateData $selparData = null
149    ): array {
150        $envOptions = $this->setupCommonOptions( $options );
151        if ( isset( $options['outputContentVersion'] ) ) {
152            $envOptions['outputContentVersion'] = $options['outputContentVersion'];
153        }
154        if ( isset( $options['wrapSections'] ) ) {
155            $envOptions['wrapSections'] = (bool)$options['wrapSections'];
156        }
157        if ( isset( $options['pageBundle'] ) ) {
158            $envOptions['pageBundle'] = (bool)$options['pageBundle'];
159        }
160        if ( isset( $options['logLinterData'] ) ) {
161            $envOptions['logLinterData'] = (bool)$options['logLinterData'];
162        }
163        if ( isset( $options['linterOverrides'] ) ) {
164            $envOptions['linterOverrides'] = $options['linterOverrides'];
165        }
166        $envOptions['nativeTemplateExpansion'] =
167            $options['nativeTemplateExpansion'] ?? false;
168        $env = new Env(
169            $this->siteConfig, $pageConfig, $this->dataAccess, $metadata, $envOptions
170        );
171        // XXX: T405759 Frame::getSource() is deprecated; this resource bump
172        // should probably be done elsewhere, like at the start of the parser
173        // pipeline where we have a $wikitext string.
174        if ( !$env->compareWt2HtmlLimit(
175            'wikitextSize', strlen( $env->topFrame->getSource()->getSrcText() )
176        ) ) {
177            throw new ResourceLimitExceededException(
178                "wt2html: wikitextSize limit exceeded"
179            );
180        }
181        $contentmodel = $options['contentmodel'] ?? null;
182        $handler = $env->getContentHandler( $contentmodel );
183        $extApi = new ParsoidExtensionAPI( $env );
184        $doc = $handler->toDOM( $extApi, $selparData );
185        if ( !DOMDataUtils::isPreparedAndLoaded( $doc ) ) {
186            // DEPRECATED. Extensions for other content types might still
187            // be returning plain/stored docs here.  Prepare and load them
188            // for consistency.
189            $dpb = new DomPageBundle( $doc );
190            $doc = $dpb->toDom( siteConfig: $this->siteConfig );
191        }
192        return [ $env, $doc, $contentmodel ];
193    }
194
195    /**
196     * Parse the wikitext supplied in a `PageConfig` to HTML.
197     *
198     * @param PageConfig $pageConfig
199     * @param array $options [
200     *   'wrapSections'         => (bool) Whether `<section>` wrappers should be added.
201     *   'pageBundle'           => (bool) Sets ids on nodes and stores
202     *                                    data-* attributes in a JSON blob.
203     *   'body_only'            => (bool|null) Only return the <body> children (T181657)
204     *   'outputContentVersion' => (string|null) Version of HTML to output.
205     *                                           `null` returns the default version.
206     *   'contentmodel'         => (string|null) The content model of the input.
207     *   'offsetType'           => (string) ucs2, char, byte are valid values
208     *                                      what kind of source offsets should be emitted?
209     *   'logLinterData'        => (bool) Should we log linter data if linting is enabled?
210     *   'linterOverrides'      => (array) Override the site linting configs.
211     *   // Debugging options, not for use in production
212     *   'traceFlags'           => (array) associative array with tracing options
213     *   'dumpFlags'            => (array) associative array with dump options
214     *   'debugFlags'           => (array) associative array with debug options
215     *   'logLevels'            => (string[]) Levels to log
216     *   // Experimental options, not considered stable
217     *   'useFragmentBank'      => (bool) Alternative encoding of embedded HTML
218     *   'sampleStats'          => (bool) If true, okay to perform "expensive"
219     *                             analysis to generate metrics.
220     *   'renderReason'         => (?string) Passed through from MediaWiki core
221     *                             to classify metrics; see
222     *                             ParserOptions::getRenderReason()
223     *   'previousInput'        => (?PageConfig) wikitext, revision ID, etc of
224     *                             some recent parse of this page.
225     *                             Not guaranteed to be usable for selective
226     *                             update, and could even be from a "newer"
227     *                             revision (if this is a render of an old
228     *                             revision).
229     *   'previousOutput'       => (?HtmlPageBundle) output of the prior parse of
230     *                             'previousInput'
231     * ]
232     * @param ?array &$headers
233     * @param ?ContentMetadataCollector $metadata Pass in a CMC in order to
234     *  collect and retrieve metadata about the parse.
235     * @param ?SelectiveUpdateData $selparData
236     * @return HtmlPageBundle|string
237     */
238    public function wikitext2html(
239        PageConfig $pageConfig, array $options = [], ?array &$headers = null,
240        ?ContentMetadataCollector $metadata = null, ?SelectiveUpdateData $selparData = null
241    ) {
242        if ( $metadata === null ) {
243            $metadata = new StubMetadataCollector( $this->siteConfig );
244        }
245
246        $parseTiming = Timing::start();
247        [ $env, $doc, $contentmodel ] = $this->parseWikitext( $pageConfig, $metadata, $options, $selparData );
248        DOMDataUtils::visitAndStoreDataAttribs( DOMCompat::getBody( $doc ), [
249            'storeInPageBundle' => $env->pageBundle,
250            'outputContentVersion' => $env->getOutputContentVersion(),
251            'useFragmentBank' => $options['useFragmentBank'] ?? false,
252            'idIndex' => $env->pageBundle ?
253                DOMDataUtils::usedIdIndex( $env->getSiteConfig(), $doc ) : null,
254        ] );
255        $parseTimeMs = $parseTiming->end();
256
257        // FIXME: Does this belong in parseWikitext so that the other endpoint
258        // is covered as well?  It probably depends on expectations of the
259        // Rest API.  If callers of /page/lint/ assume that will update the
260        // results on the Special page.
261        if ( $env->linting() ) {
262            ( new LintLogger( $env ) )->logLintOutput();
263        }
264
265        $headers = self::pageBundleHeaders( $env );
266        $body_only = !empty( $options['body_only'] );
267        $node = $body_only ? DOMCompat::getBody( $doc ) : $doc;
268
269        if ( $env->pageBundle ) {
270            $out = [
271                'pb' => HtmlPageBundle::fromDomPageBundle( $env->pageBundle, [
272                    'body_only' => $body_only,
273                    'contentversion' => $env->getOutputContentVersion(),
274                    'headers' => $headers,
275                    'contentmodel' => $contentmodel,
276                    'offsetType' => $env->getCurrentOffsetType(),
277                ] ),
278            ];
279            $out['html'] = $out['pb']->html; // for use in metrics
280        } else {
281            $out = [
282                'html' => ContentUtils::toXML( $node, [
283                    'innerXML' => $body_only,
284                ] ),
285            ];
286        }
287
288        $this->recordParseMetrics(
289            $env, $parseTimeMs, $out, $headers, $contentmodel, $options
290        );
291
292        if ( $env->pageBundle ) {
293            return $out['pb'];
294        } else {
295            return $out['html'];
296        }
297    }
298
299    private function recordParseMetrics(
300        Env $env, float $parseTimeMs,
301        array $out, ?array $headers, string $contentmodel,
302        array $options
303    ): void {
304        $metrics = $this->siteConfig->metrics();
305
306        $pageConfig = $env->getPageConfig();
307
308        // This is somewhat suspect because ParsoidHandler::tryToCreatePageConfig
309        // can set a revision id on a MutableRevisionRecord, but it might be simpler
310        // to make that go away
311        if ( $pageConfig->getRevisionId() ) {
312            $mstr = 'pageWithOldid';
313        } else {
314            $mstr = 'wt';
315        }
316
317        $timing = Timing::fakeTiming( $this->siteConfig, $parseTimeMs );
318        $timing->end( "entry.wt2html.{$mstr}.parse", 'wt2html_parse_seconds', [ 'type' => $mstr ] );
319        $version = 'default';
320
321        if ( Semver::satisfies(
322            $env->getOutputContentVersion(), '!=' . self::defaultHTMLVersion()
323        ) ) {
324            if ( $metrics ) {
325                $metrics->increment( 'entry.wt2html.parse.version.notdefault' );
326            }
327            $version = 'non-default';
328        }
329
330        $this->siteConfig->incrementCounter( 'wt2html_parse_total', [
331            'type' => $mstr,
332            'version' => $version
333        ] );
334
335        // TODO: Remove fake timing after migration to histogram is complete
336        // @phan-suppress-next-line PhanDeprecatedFunction
337        $inSize = $pageConfig->getPageMainContent();
338        $timing = Timing::fakeTiming( $this->siteConfig, strlen( $inSize ), false );
339        $timing->end(
340            "entry.wt2html.{$mstr}.size.input",
341            "legacy_wt2html_size_input_bytes",
342            [ "type" => $mstr ]
343        );
344        $this->histogram->observe(
345            "wt2html_size_input_bytes",
346            strlen( $inSize ),
347            [ "type" => $mstr ]
348        );
349
350        $outSize = strlen( $out['html'] );
351        // TODO: Remove fake timing after migration to histogram is complete
352        $timing = Timing::fakeTiming( $this->siteConfig, $outSize, false );
353        $timing->end( "entry.wt2html.{$mstr}.size.output", "legacy_wt2html_size_output_bytes", [ "type" => $mstr ] );
354        $this->histogram->observe( "wt2html_size_output_bytes", $outSize, [ "type" => $mstr ] );
355
356        if ( $parseTimeMs > 10 && $outSize > 100 ) {
357            // * Don't bother with this metric for really small parse times
358            //   p99 for initialization time is ~7ms according to grafana.
359            //   So, 10ms ensures that startup overheads don't skew the metrics
360            // * For body_only=false requests, <head> section isn't generated
361            //   and if the output is small, per-request overheads can skew
362            //   the timePerKB metrics.
363            //
364            // NOTE: This is slightly misleading since there are fixed costs
365            // for generating output like the <head> section and should be factored in,
366            // but this is good enough for now as a useful first degree of approxmation.
367
368            // TODO: Remove fake timing after migration to histogram is complete
369            $msPerKB = $parseTimeMs * 1024 / $outSize;
370            $timing = Timing::fakeTiming( $this->siteConfig, $msPerKB );
371            $timing->end(
372                'entry.wt2html.timePerKB',
373                'legacy_wt2html_msPerKB',
374                []
375            );
376            $this->histogram->observe( 'wt2html_msPerKB', $msPerKB );
377        }
378
379        // Expensive analyses: sampleStats is randomly sampled will not be
380        // true "often"
381        $doSample = $options['sampleStats'] ?? false;
382        if ( !$doSample ) {
383            return;
384        }
385
386        try {
387            // create new page bundle for this computation to ensure we
388            // don't inadvertently corrupt the main document result.
389            $newPb = new HtmlPageBundle(
390                $out['html'],
391                $out['pb']->parsoid ?? null, $out['pb']->mw ?? null,
392                $out['pb']->counters ?? null,
393                $env->getOutputContentVersion(),
394                $headers,
395                $contentmodel
396            );
397            $labels = ComputeSelectiveStats::classify(
398                $env,
399                $options['previousInput'] ?? null,
400                $options['previousOutput'] ?? null,
401                $pageConfig,
402                $newPb
403            );
404            $labels['wiki'] = $this->siteConfig->iwp();
405            $labels['reason'] = $options['renderReason'] ?? 'unknown';
406            $labels['useragent'] = ComputeSelectiveStats::filterUserAgent( $options['userAgent'] ?: null );
407
408            $this->siteConfig->incrementCounter( 'selective_update_total', $labels );
409            $this->siteConfig->incrementCounter( 'selective_update_seconds', $labels, $parseTimeMs / 1000. );
410        } catch ( \Throwable $t ) {
411            // Don't ever allow bugs in the classification code to
412            // impact the availability of content for read views/editing,
413            // just log.
414            $env->log( 'warn', 'Classification failure', $t->getTraceAsString() );
415        }
416    }
417
418    /**
419     * Lint the wikitext supplied in a `PageConfig`.
420     *
421     * @param PageConfig $pageConfig
422     * @param array $options See wikitext2html.
423     * @param ?ContentMetadataCollector $metadata Pass in a CMC in order to
424     *  collect and retrieve metadata about the parse.
425     * @return array
426     */
427    public function wikitext2lint(
428        PageConfig $pageConfig, array $options = [],
429        ?ContentMetadataCollector $metadata = null
430    ): array {
431        if ( $metadata === null ) {
432            $metadata = new StubMetadataCollector( $this->siteConfig );
433        }
434        [ $env, ] = $this->parseWikitext( $pageConfig, $metadata, $options );
435        return $env->getLints();
436    }
437
438    /**
439     * Serialize DOM to wikitext.
440     *
441     * @param PageConfig $pageConfig
442     * @param Document|HtmlPageBundle|DomPageBundle $doc This is either a page
443     *   bundle or a "naive" DOM without special handling of
444     *   data-parsoid/data-mw etc.  A naive DOM can either be in "single
445     *   document" form (data attributes in an element in the <head>) or in
446     *   "inline attributes" form.
447     * @param array $options [
448     *   'inputContentVersion' => (string) The content version of the input.
449     *     Necessary if it differs from the current default in order to
450     *     account for any serialization differences.
451     *   'offsetType'          => (string) ucs2, char, byte are valid values
452     *                                     what kind of source offsets are present in the HTML?
453     *   'contentmodel'        => (string|null) The content model of the input.
454     *   'traceFlags'          => (array) associative array with tracing options
455     *   'dumpFlags'           => (array) associative array with dump options
456     *   'debugFlags'          => (array) associative array with debug options
457     *   'logLevels'           => (string[]) Levels to log
458     *   'htmlSize'            => (int) Size of the HTML that generated $doc
459     * ]
460     * @param ?SelectiveUpdateData $selserData
461     * @return string
462     */
463    public function dom2wikitext(
464        PageConfig $pageConfig, $doc, array $options = [],
465        ?SelectiveUpdateData $selserData = null
466    ): string {
467        if ( $doc instanceof Document ) {
468            Assert::invariant(
469                !DOMDataUtils::isPreparedAndLoaded( $doc ),
470                "document should not be already prepared and loaded"
471            );
472        }
473        $envOptions = $this->setupCommonOptions( $options );
474        if ( isset( $options['inputContentVersion'] ) ) {
475            $envOptions['inputContentVersion'] = $options['inputContentVersion'];
476        }
477        $envOptions['topLevelDoc'] = self::prepareAndLoadDocOrBundle( $doc, $this->siteConfig );
478        $metadata = new StubMetadataCollector( $this->siteConfig );
479        $env = new Env(
480            $this->siteConfig, $pageConfig, $this->dataAccess, $metadata, $envOptions
481        );
482        $env->bumpHtml2WtResourceUse( 'htmlSize', $options['htmlSize'] ?? 0 );
483        $contentmodel = $options['contentmodel'] ?? null;
484        $handler = $env->getContentHandler( $contentmodel );
485        $extApi = new ParsoidExtensionAPI( $env );
486
487        $serialTiming = Timing::start();
488        $wikitext = $handler->fromDOM( $extApi, $selserData );
489        $serialTime = $serialTiming->end();
490
491        $this->recordSerializationMetrics( $options, $serialTime, $wikitext );
492
493        return $wikitext;
494    }
495
496    private function recordSerializationMetrics(
497        array $options, float $serialTime, string $wikitext
498    ): void {
499        $siteConfig = $this->siteConfig;
500        $metrics = $siteConfig->metrics();
501
502        $htmlSize = $options['htmlSize'] ?? 0;
503        $timing = Timing::fakeTiming( $this->siteConfig, $htmlSize, false );
504        // TODO: Remove fake timing after migration to histogram is complete
505        $timing->end( 'entry.html2wt.size.input', 'legacy_html2wt_size_input_bytes' );
506        $this->histogram->observe( 'html2wt_size_input_bytes', $htmlSize );
507
508        if ( isset( $options['inputContentVersion'] ) ) {
509            if ( $metrics ) {
510                $metrics->increment(
511                    'entry.html2wt.original.version.' . $options['inputContentVersion']
512                );
513            }
514            $this->siteConfig->incrementCounter(
515                'html2wt_original_version',
516                [ 'input_content_version' => $options['inputContentVersion'] ]
517            );
518        }
519
520        $timing = Timing::fakeTiming( $this->siteConfig, $serialTime );
521        $timing->end( 'entry.html2wt.total', 'html2wt_total_seconds', [] );
522
523        $timing = Timing::fakeTiming( $this->siteConfig, strlen( $wikitext ), false );
524        // TODO: Remove fake timing after migration to histogram is complete
525        $timing->end( 'entry.html2wt.size.output', 'legacy_html2wt_size_output_bytes', [] );
526        $this->histogram->observe( 'html2wt_size_output_bytes', strlen( $wikitext ) );
527
528        if ( $htmlSize ) {  // Avoid division by zero
529            // NOTE: the name timePerInputKB is misleading, since $htmlSize is
530            //       in characters, not bytes.
531            $msPerKB = $serialTime * 1024 / $htmlSize;
532            // TODO: Remove fake timing after migration to histogram is complete
533            $timing = Timing::fakeTiming( $this->siteConfig, $msPerKB );
534            $timing->end(
535                'entry.html2wt.timePerInputKB',
536                'legacy_html2wt_msPerKB',
537                []
538            );
539            $this->histogram->observe( 'html2wt_msPerKB', $msPerKB );
540        }
541    }
542
543    /**
544     * Serialize HTML to wikitext.  Convenience method for dom2wikitext.
545     *
546     * @param PageConfig $pageConfig
547     * @param string $html
548     * @param array $options
549     * @param ?SelectiveUpdateData $selserData
550     * @return string
551     */
552    public function html2wikitext(
553        PageConfig $pageConfig, string $html, array $options = [],
554        ?SelectiveUpdateData $selserData = null
555    ): string {
556        $doc = DOMUtils::parseHTML( $html, true );
557        $options['htmlSize'] ??= mb_strlen( $html );
558        return $this->dom2wikitext( $pageConfig, $doc, $options, $selserData );
559    }
560
561    /**
562     * Update the supplied HtmlPageBundle based on the `$update` type.
563     *
564     *   'convertoffsets': Convert offsets between formats (byte, char, ucs2)
565     *   'redlinks': Refreshes the classes of known, missing, etc. links.
566     *   'variant': Converts the HTML based on the supplied variant.
567     *
568     * Note that these are DOM transforms, and not roundtrips through wikitext.
569     *
570     * @param PageConfig $pageConfig
571     * @param string $update 'redlinks'|'variant'
572     * @param HtmlPageBundle|DomPageBundle $pb
573     * @param array $options
574     * @return HtmlPageBundle
575     */
576    public function pb2pb(
577        PageConfig $pageConfig, string $update, $pb,
578        array $options = []
579    ): HtmlPageBundle {
580        $envOptions = [
581            'pageBundle' => true,
582            'topLevelDoc' => self::prepareAndLoadDocOrBundle( $pb, $this->siteConfig ),
583        ];
584        $metadata = new StubMetadataCollector( $this->siteConfig );
585        $env = new Env(
586            $this->siteConfig, $pageConfig, $this->dataAccess, $metadata, $envOptions
587        );
588        $doc = $env->getTopLevelDoc();
589
590        // NOTE: When $doc is prepared (with eager loading of attributes),
591        // 'parsoid' and 'mw' attributes are stashed in DataBag, and the
592        // 'annotation' and 'transclusion' counters in DataBag are also
593        // initialized. But $pb->counters['nodedata'] is not, because it
594        // is in encoded base64 form.
595        //
596        // FIXME: We should ideally be initializing $env->pageBundle
597        // from $pb in self::prepareAndLoadDocOrBundle, but it needs
598        // a bunch of code rejiggering in this file and in Env. That will
599        // be a followup refactoring when we work on lazy loading.
600        if ( isset( $pb->counters['nodedata'] ) ) {
601            $env->pageBundle->counters['nodedata'] = $pb->counters['nodedata'];
602        }
603
604        switch ( $update ) {
605            case 'convertoffsets':
606                // This method also calls Env::setCurrentOffsetType, which
607                // is used by HtmlPageBundle::fromDomPageBundle() below to set
608                // 'offsetType' in the 'parsoid' property of the page bundle
609                ContentUtils::convertOffsets(
610                    $env, $doc, $options['inputOffsetType'], $options['outputOffsetType']
611                );
612                break;
613
614            case 'redlinks':
615                ContentUtils::convertOffsets(
616                    $env, $doc, $env->getRequestOffsetType(), 'byte'
617                );
618                ( new AddRedLinks() )->run( $env, DOMCompat::getBody( $doc ) );
619                ( new ConvertOffsets() )->run( $env, DOMCompat::getBody( $doc ), [], true );
620                break;
621
622            default:
623                throw new LogicException( $update . 'is an unknown transformation' );
624        }
625
626        DOMDataUtils::visitAndStoreDataAttribs(
627            DOMCompat::getBody( $doc ), [
628                'storeInPageBundle' => $env->pageBundle,
629                'outputContentVersion' => $env->getOutputContentVersion(),
630                'idIndex' => $env->pageBundle ?
631                    DOMDataUtils::usedIdIndex( $env->getSiteConfig(), $doc ) : null,
632            ]
633        );
634        return HtmlPageBundle::fromDomPageBundle( $env->pageBundle, [
635            'body_only' => !empty( $options['body_only'] ),
636            // Prefer the passed in version, since this was just a transformation
637            'contentversion' => $pb->getContentVersion() ?? $env->getOutputContentVersion(),
638            'headers' => self::pageBundleHeaders( $env ),
639            // Prefer the passed in content model
640            'contentmodel' => $pb->contentmodel ?? $pageConfig->getContentModel(),
641            'offsetType' => $env->getCurrentOffsetType(),
642        ] );
643    }
644
645    /**
646     * Check whether a given content version can be downgraded to the requested
647     * content version.
648     *
649     * @param string $from Current content version
650     * @param string $to Requested content version
651     * @return string[]|null The downgrade that will fulfill the request, as
652     *   [ 'from' => <old version>, 'to' => <new version> ], or null if it
653     *   can't be fulfilled.
654     */
655    public static function findDowngrade( string $from, string $to ): ?array {
656        foreach ( self::DOWNGRADES as [ 'from' => $dgFrom, 'to' => $dgTo ] ) {
657            if (
658                Semver::satisfies( $from, "^$dgFrom" ) &&
659                Semver::satisfies( $to, "^$dgTo" )
660            ) {
661                // FIXME: Make this a class?
662                return [ 'from' => $dgFrom, 'to' => $dgTo ];
663            }
664        }
665        return null;
666    }
667
668    /**
669     * Downgrade a document to an older content version.
670     *
671     * @param string[] $dg Value returned by findDowngrade().
672     * @param HtmlPageBundle $pageBundle
673     */
674    public static function downgrade(
675        array $dg, HtmlPageBundle $pageBundle, ?SiteConfig $siteConfig = null
676    ): void {
677        if ( $siteConfig === null ) {
678            PHPUtils::deprecated( __METHOD__ . ' without siteConfig', '0.23' );
679            $siteConfig = new MockSiteConfig( [] );
680        }
681        foreach ( self::DOWNGRADES as [ 'from' => $dgFrom, 'to' => $dgTo, 'func' => $dgFunc ] ) {
682            if ( $dg['from'] === $dgFrom && $dg['to'] === $dgTo ) {
683                self::$dgFunc( $pageBundle, $siteConfig );
684
685                // FIXME: Maybe this resolve should just be part of the $dg
686                $pageBundle->setContentVersion( self::resolveContentVersion( $dg['to'] ) );
687
688                // FIXME: Maybe this should be a helper to avoid the rt
689                $doc = DOMUtils::parseHTML( $pageBundle->html );
690                // Match the http-equiv meta to the content-type header
691                $meta = DOMCompat::querySelector( $doc,
692                    'meta[property="mw:htmlVersion"], meta[property="mw:html:version"]' );
693                if ( $meta ) {
694                    $meta->setAttribute( 'content', $pageBundle->getContentVersion() );
695                    $pageBundle->html = ContentUtils::toXML( $doc );
696                }
697
698                return;
699            }
700        }
701        throw new InvalidArgumentException(
702            "Unsupported downgrade: {$dg['from']} -> {$dg['to']}"
703        );
704    }
705
706    /**
707     * Downgrade the given document and pagebundle from 999.x to 2.x.
708     *
709     * @param HtmlPageBundle $pageBundle
710     */
711    private static function downgrade999to2( HtmlPageBundle $pageBundle, SiteConfig $siteConfig ): void {
712        // Effectively, skip applying data-parsoid.  Note that if we were to
713        // support a pb2html downgrade, we'd need to apply the full thing,
714        // but that would create complications where ids would be left behind.
715        // See the doc comment for `DomPageBundle::apply()`
716        $newHtmlPageBundle = new HtmlPageBundle(
717            $pageBundle->html,
718            null,
719            $pageBundle->mw,
720            $pageBundle->counters
721        );
722        $pageBundle->html = $newHtmlPageBundle->toInlineAttributeHtml( siteConfig: $siteConfig );
723
724        // Now, modify the pagebundle to the expected form.  This is important
725        // since, at least in the serialization path, the original pb will be
726        // applied to the modified content and its presence could cause lost
727        // deletions.
728        $pageBundle->mw = [ 'ids' => [] ];
729    }
730
731    /**
732     * Convert an input document in a variety of formats (page bundle, etc)
733     * to a "prepared and loaded" document suitable to be given to
734     * Env::setupTopLevelDoc()
735     * @param Document|HtmlPageBundle|DomPageBundle $topLevelDoc
736     * @param SiteConfig $siteConfig
737     * @return Document
738     */
739    private static function prepareAndLoadDocOrBundle( $topLevelDoc, $siteConfig ): Document {
740        // Recognize a "single document" page bundle.
741        if (
742            $topLevelDoc instanceof Document &&
743            DomPageBundle::isSingleDocument( $topLevelDoc )
744        ) {
745            $topLevelDoc = DomPageBundle::fromSingleDocument( $topLevelDoc );
746        }
747        // Convert a HtmlPageBundle (string html) to a DomPageBundle (DOM)
748        if ( $topLevelDoc instanceof HtmlPageBundle ) {
749            $topLevelDoc = DomPageBundle::fromHtmlPageBundle( $topLevelDoc );
750        }
751        // Use DomPageBundle::toDom() to efficiently apply and load
752        // (without necessarily having to add attributes to the DOM)
753        if ( $topLevelDoc instanceof DomPageBundle ) {
754            // Skip preparation and loading, it's already done.
755            return $topLevelDoc->toDom( siteConfig: $siteConfig );
756        }
757
758        // This is an unprepared/unloaded Document.
759        Assert::invariant(
760            !DOMDataUtils::isPreparedAndLoaded( $topLevelDoc ),
761            "toplevelDoc should not be prepared and loaded already"
762        );
763        DOMDataUtils::prepareAndLoadDoc( $topLevelDoc, $siteConfig );
764        return $topLevelDoc;
765    }
766
767    /** Return appropriate HTTP headers for Parsoid output. */
768    private static function pageBundleHeaders( Env $env ): array {
769        return [
770            'content-language' => $env->htmlContentLanguageBcp47()->toBcp47Code(),
771            'vary' => $env->htmlVary(),
772        ];
773    }
774}