Debian Codegraph @

vendor/wikimedia/parsoid/bin/parse.php

raw
1 <?php
2
3 /**
4 * At present, this script is just used for testing the library and uses a
5 * public MediaWiki API, which means it's expected to be slow.
6 */
7
8 require_once __DIR__ . '/../tools/Maintenance.php';
9
10 use MediaWiki\MediaWikiServices;
11 use MediaWiki\Revision\MutableRevisionRecord;
12 use MediaWiki\Revision\SlotRecord;
13 use Wikimedia\Parsoid\Config\Api\ApiHelper;
14 use Wikimedia\Parsoid\Config\Api\DataAccess;
15 use Wikimedia\Parsoid\Config\Api\PageConfig;
16 use Wikimedia\Parsoid\Config\Api\SiteConfig;
17 use Wikimedia\Parsoid\Config\SiteConfig as ISiteConfig;
18 use Wikimedia\Parsoid\Config\StubMetadataCollector;
19 use Wikimedia\Parsoid\Core\ClientError;
20 use Wikimedia\Parsoid\Core\ContentMetadataCollector;
21 use Wikimedia\Parsoid\Core\PageBundle;
22 use Wikimedia\Parsoid\Core\SelectiveUpdateData;
23 use Wikimedia\Parsoid\Mocks\MockDataAccess;
24 use Wikimedia\Parsoid\Mocks\MockMetrics;
25 use Wikimedia\Parsoid\Mocks\MockPageConfig;
26 use Wikimedia\Parsoid\Mocks\MockPageContent;
27 use Wikimedia\Parsoid\Mocks\MockSiteConfig;
28 use Wikimedia\Parsoid\ParserTests\DummyAnnotation;
29 use Wikimedia\Parsoid\ParserTests\TestUtils;
30 use Wikimedia\Parsoid\Parsoid;
31 use Wikimedia\Parsoid\Tools\ExtendedOptsProcessor;
32 use Wikimedia\Parsoid\Utils\ContentUtils;
33 use Wikimedia\Parsoid\Utils\DOMDataUtils;
34 use Wikimedia\Parsoid\Utils\DOMUtils;
35 use Wikimedia\Parsoid\Utils\PHPUtils;
36 use Wikimedia\Parsoid\Utils\ScriptUtils;
37 use Wikimedia\Parsoid\Utils\Title;
38
39 // phpcs:ignore MediaWiki.Files.ClassMatchesFilename.WrongCase
40 class Parse extends \Wikimedia\Parsoid\Tools\Maintenance {
41 use ExtendedOptsProcessor;
42
43 /** @var ISiteConfig */
44 private $siteConfig;
45
46 /** @var PageConfig */
47 private $pageConfig;
48
49 /** @var ContentMetadataCollector */
50 private $metadata;
51
52 /** @var Parsoid */
53 private $parsoid;
54
55 public function __construct() {
56 parent::__construct();
57 parent::addDefaultParams();
58 $this->addDescription(
59 "Omnibus script to convert between wikitext and HTML, and roundtrip wikitext or HTML. "
60 . "Supports a number of options pertaining to pointing at a specific wiki "
61 . "or enabling various features during these transformations.\n\n"
62 . "If no options are provided, --wt2html is enabled by default.\n"
63 . "See --help for detailed usage help." );
64 $this->addOption( 'wt2html', 'Wikitext -> HTML' );
65 $this->addOption( 'wt2lint', 'Wikitext -> Lint. Enables --linting' );
66 $this->addOption( 'html2wt', 'HTML -> Wikitext' );
67 $this->addOption( 'wt2wt', 'Wikitext -> Wikitext' );
68 $this->addOption( 'html2html', 'HTML -> HTML' );
69 $this->addOption(
70 'body_only',
71 'Just return <body> innerHTML (defaults to true)',
72 false,
73 true
74 );
75 $this->setOptionDefault( 'body_only', true );
76
77 $this->addOption( 'profile', 'Proxy for --trace time' );
78 $this->addOption( 'benchmark', 'Suppress output and show timing summary' );
79 $this->addOption( 'count',
80 'Repeat the operation this many times',
81 false, true );
82 $this->addOption( 'warmup', 'Run the operation once before benchmarking' );
83 $this->addOption( 'delay',
84 'Wait for the specified number of milliseconds after warmup. For use with perf -D.',
85 false, true );
86
87 $this->addOption( 'selser',
88 'Use the selective serializer to go from HTML to Wikitext.' );
89 $this->addOption( 'selpar',
90 'In the wt->html direction, update HTML selectively' );
91 $this->addOption( 'revtextfile',
92 'File containing revision wikitext for selective html/wikitext updates',
93 false, true );
94 $this->addOption( 'revhtmlfile',
95 'File containing revision HTML for selective html/wikitext updates',
96 false, true );
97 $this->addOption( 'editedtemplatetitle',
98 'Title of the edited template (for --selpar)',
99 false, true );
100
101 $this->addOption( 'inputfile', 'File containing input as an alternative to stdin', false, true );
102 $this->addOption( 'logFile', 'File to log trace/dumps to', false, true );
103 $this->addOption(
104 'pbin',
105 'Input pagebundle JSON',
106 false,
107 true
108 );
109 $this->addOption(
110 'pbinfile',
111 'Input pagebundle JSON file',
112 false,
113 true
114 );
115 $this->addOption(
116 'pboutfile',
117 'Output pagebundle JSON to file',
118 false,
119 true
120 );
121 $this->addOption(
122 'pageName',
123 'The page name, returned for {{PAGENAME}}. If no input is given ' .
124 '(ie. empty/stdin closed), it downloads and parses the page. ' .
125 'This should be the actual title of the article (that is, not ' .
126 'including any URL-encoding that might be necessary in wikitext).',
127 false,
128 true
129 );
130 $this->addOption(
131 'restURL',
132 'Parses a RESTBase API URL (as supplied in our logs) and ' .
133 'sets --domain and --pageName. Debugging aid.',
134 false,
135 true
136 );
137 $this->addOption(
138 'pageBundle',
139 'Output pagebundle JSON'
140 );
141 $this->addOption(
142 'wrapSections',
143 // Override the default in Env since the wrappers are annoying in dev-mode
144 'Output <section> tags (default false)'
145 );
146 $this->addOption(
147 'linting',
148 'Parse with linter enabled.'
149 );
150 $this->addOption(
151 'logLinterData',
152 'Log the linter data. Enables --linting. With --integrated, ' .
153 'it attempts to queue up a job to add to the linter table.'
154 );
155 $this->addOption(
156 'addHTMLTemplateParameters',
157 'Parse template parameters to HTML and add them to template data'
158 );
159 $this->addOption(
160 'domain',
161 'Which wiki to use; e.g. "en.wikipedia.org" for English wikipedia, ' .
162 '"es.wikipedia.org" for Spanish, "mediawiki.org" for mediawiki.org',
163 false,
164 true
165 );
166 $this->addOption(
167 'apiURL',
168 'http path to remote API, e.g. http://en.wikipedia.org/w/api.php',
169 false,
170 true
171 );
172 $this->addOption(
173 'offsetType',
174 'Represent DSR as byte/ucs2/char offsets',
175 false,
176 true
177 );
178 $this->addOption(
179 'wtVariantLanguage',
180 'Language variant to use for wikitext',
181 false,
182 true
183 );
184 $this->addOption(
185 'htmlVariantLanguage',
186 'Language variant to use for HTML',
187 false,
188 true
189 );
190 $this->addOption(
191 'flamegraph',
192 "Produce a flamegraph of CPU usage. " .
193 "Assumes existence of Excimer ( https://www.mediawiki.org/wiki/Excimer ). " .
194 "Looks for /usr/local/bin/flamegraph.pl (Set FLAMEGRAPH_PATH env var " .
195 "to use different path). Outputs to /tmp (Set FLAMEGRAPH_OUTDIR " .
196 "env var to output elsewhere)."
197 );
198 $this->addOption(
199 'trace',
200 'Use --trace=help for supported options',
201 false,
202 true
203 );
204 $this->addOption(
205 'dump',
206 'Dump state. Use --dump=help for supported options',
207 false,
208 true
209 );
210 $this->addOption(
211 'debug',
212 'Provide optional flags. Use --debug=help for supported options',
213 false,
214 true
215 );
216 $this->addOption(
217 'revid',
218 'revid of the given page.',
219 false,
220 true
221 );
222 $this->addOption(
223 'normalize',
224 "Normalize the output as parserTests would do. " .
225 "Use --normalize for PHP tests, and --normalize=parsoid for " .
226 "parsoid-only tests",
227 false,
228 false
229 );
230 $this->addOption(
231 'outputContentVersion',
232 'The acceptable content version.',
233 false,
234 true
235 );
236 $this->addOption(
237 'verbose',
238 'Log at level "info" as well'
239 );
240 $this->addOption(
241 'maxdepth',
242 'Maximum expansion depth.',
243 false,
244 true
245 );
246 $this->addOption(
247 'version',
248 'Show version number.'
249 );
250 $this->addOption(
251 'contentmodel',
252 "The content model of the input. Defaults to \"wikitext\" but " .
253 "extensions may support others (for example, \"json\").",
254 false,
255 true
256 );
257 $this->addOption(
258 'metrics',
259 'Dump a log of the metrics methods that were called from a MockMetrics.'
260 );
261 $this->setAllowUnregisteredOptions( false );
262 }
263
264 private function setupMwConfig( array $configOpts ): void {
265 $services = MediaWikiServices::getInstance();
266 $siteConfig = $services->getParsoidSiteConfig();
267 // Overwriting logger so that it logs to console/file
268 $logFilePath = null;
269 if ( $this->hasOption( 'logFile' ) ) {
270 $logFilePath = $this->getOption( 'logFile' );
271 }
272 $siteConfig->setLogger( SiteConfig::createLogger( $logFilePath ) );
273
274 if ( isset( $configOpts['maxDepth'] ) ) {
275 $siteConfig->setMaxTemplateDepth( $configOpts['maxDepth'] );
276 }
277 $dataAccess = $services->getParsoidDataAccess();
278 $pcFactory = $services->getParsoidPageConfigFactory();
279 // XXX we're ignoring 'pageLanguage' & 'pageLanguageDir' in $configOpts
280 $title = isset( $configOpts['title'] )
281 ? \Title::newFromText( $configOpts['title'] )
282 : $siteConfig->mainPageLinkTarget();
283
284 $wikitextOverride = $configOpts['pageContent'] ?? null;
285 $revision = $configOpts['revid'] ?? null;
286 if ( $wikitextOverride === null ) {
287 $revisionRecord = null;
288 } else {
289 // Create a mutable revision record point to the same revision
290 // and set to the desired wikitext.
291 $revisionRecord = new MutableRevisionRecord( $title );
292 if ( $revision !== null ) {
293 $revisionRecord->setId( $revision );
294 }
295 $revisionRecord->setSlot(
296 SlotRecord::newUnsaved(
297 SlotRecord::MAIN,
298 new WikitextContent( $wikitextOverride )
299 )
300 );
301 }
302
303 $this->siteConfig = $siteConfig;
304 $this->pageConfig = $pcFactory->create(
305 $title,
306 null, // UserIdentity
307 $revisionRecord ?? $revision,
308 null,
309 null,
310 $configOpts['ensureAccessibleContent']
311 );
312 $this->metadata = new \ParserOutput();
313 $this->parsoid = new Parsoid( $siteConfig, $dataAccess );
314 }
315
316 private function setupApiConfig( array $configOpts ): void {
317 $api = new ApiHelper( $configOpts );
318
319 $siteConfig = new SiteConfig( $api, $configOpts );
320 if ( $this->hasOption( 'logFile' ) ) {
321 // Overwrite logger so that it logs to file
322 $siteConfig->setLogger( SiteConfig::createLogger( $this->getOption( 'logFile' ) ) );
323 }
324 $dataAccess = new DataAccess( $api, $siteConfig, $configOpts );
325 $this->siteConfig = $siteConfig;
326 $configOpts['title'] = isset( $configOpts['title'] )
327 ? Title::newFromText( $configOpts['title'], $siteConfig )
328 : $siteConfig->mainPageLinkTarget();
329
330 $this->pageConfig = new PageConfig( $api, $siteConfig, $configOpts + [
331 'loadData' => true
332 ] );
333
334 if ( $configOpts['ensureAccessibleContent'] ) {
335 try {
336 $this->pageConfig->getPageMainContent();
337 } catch ( \Error $e ) {
338 throw new \RuntimeException( 'The specified revision does not exist.' );
339 }
340 }
341
342 $this->metadata = new StubMetadataCollector( $siteConfig );
343 $this->parsoid = new Parsoid( $siteConfig, $dataAccess );
344 }
345
346 private function setupMockConfig( array $configOpts ): void {
347 $siteConfig = new MockSiteConfig( $configOpts );
348 $siteConfig->registerExtensionModule( DummyAnnotation::class );
349 $dataAccess = new MockDataAccess( $siteConfig, $configOpts );
350 $pageContent = new MockPageContent( [ 'main' =>
351 $configOpts['pageContent'] ?? '' ] );
352 $this->siteConfig = $siteConfig;
353 $this->pageConfig = new MockPageConfig( $siteConfig, $configOpts, $pageContent );
354 $this->metadata = new StubMetadataCollector( $siteConfig );
355 $this->parsoid = new Parsoid( $siteConfig, $dataAccess );
356 }
357
358 /**
359 * Initialize $this->parsoid and $this->pageConfig
360 *
361 * @param array $configOpts
362 */
363 private function setupConfig( array $configOpts ) {
364 if ( $configOpts['mock'] ) {
365 $this->setupMockConfig( $configOpts );
366 } elseif ( $configOpts['standalone'] ?? true ) {
367 $this->setupApiConfig( $configOpts );
368 } else {
369 $this->setupMwConfig( $configOpts );
370 }
371 }
372
373 /**
374 * @param array $configOpts
375 * @param array $parsoidOpts
376 * @param ?string $wt
377 * @param ?SelectiveUpdateData $selparData
378 * @return string|PageBundle
379 */
380 public function wt2Html(
381 array $configOpts, array $parsoidOpts, ?string $wt,
382 ?SelectiveUpdateData $selparData = null
383 ) {
384 if ( $wt !== null ) {
385 $configOpts["pageContent"] = $wt;
386 }
387 $this->setupConfig( $configOpts );
388
389 try {
390 return $this->parsoid->wikitext2html(
391 $this->pageConfig, $parsoidOpts, $headers, $this->metadata, $selparData
392 );
393 } catch ( ClientError $e ) {
394 $this->error( $e->getMessage() );
395 die( 1 );
396 }
397 }
398
399 /**
400 * @param array $configOpts
401 * @param array $parsoidOpts
402 * @param ?string $wt
403 * @return string
404 */
405 public function wt2lint(
406 array $configOpts, array $parsoidOpts, ?string $wt
407 ) {
408 if ( $wt !== null ) {
409 $configOpts["pageContent"] = $wt;
410 }
411 $this->setupConfig( $configOpts );
412
413 try {
414 $lints = $this->parsoid->wikitext2lint(
415 $this->pageConfig, $parsoidOpts
416 );
417 $lintStr = '';
418 foreach ( $lints as $l ) {
419 $lintStr .= PHPUtils::jsonEncode( $l ) . "\n";
420 }
421 return $lintStr;
422 } catch ( ClientError $e ) {
423 $this->error( $e->getMessage() );
424 die( 1 );
425 }
426 }
427
428 public function html2Wt(
429 array $configOpts, array $parsoidOpts, string $html,
430 ?SelectiveUpdateData $selserData = null
431 ): string {
432 $configOpts["pageContent"] = $selserData->revText ?? ''; // FIXME: T234549
433 $this->setupConfig( $configOpts );
434
435 try {
436 return $this->parsoid->html2wikitext(
437 $this->pageConfig, $html, $parsoidOpts, $selserData
438 );
439 } catch ( ClientError $e ) {
440 $this->error( $e->getMessage() );
441 die( 1 );
442 }
443 }
444
445 private function maybeNormalize( string $html ): string {
446 if ( $this->hasOption( 'normalize' ) ) {
447 $html = TestUtils::normalizeOut(
448 $html, [
449 'parsoidOnly' => $this->getOption( 'normalize' ) === 'parsoid',
450 ]
451 );
452 }
453 return $html;
454 }
455
456 private function maybeVersion() {
457 if ( $this->hasOption( 'version' ) ) {
458 $this->output( Parsoid::version() . "\n" );
459 die( 0 );
460 }
461 }
462
463 public function execute() {
464 $this->maybeHelp();
465 $this->maybeVersion();
466
467 $parsoidOpts = [];
468 ScriptUtils::setDebuggingFlags( $parsoidOpts, $this->getOptions() );
469
470 if ( $this->hasOption( 'flamegraph' ) ) {
471 $this->startFlameGraphProfiler();
472 }
473
474 if ( $this->hasOption( 'inputfile' ) ) {
475 $input = file_get_contents( $this->getOption( 'inputfile' ) );
476 if ( $input === false ) {
477 return;
478 }
479 } else {
480 if ( $this->hasOption( 'restURL' ) ) {
481 $input = '';
482 } else {
483 $input = file_get_contents( 'php://stdin' );
484 }
485 if ( strlen( $input ) === 0 ) {
486 // Parse page if no input
487 if ( $this->hasOption( 'html2wt' ) || $this->hasOption( 'html2html' ) ) {
488 $this->error(
489 'Fetching page content is only supported when starting at wikitext.'
490 );
491 return;
492 } else {
493 $input = null;
494 }
495 }
496 }
497
498 if ( $this->hasOption( 'restURL' ) ) {
499 if ( !preg_match(
500 '#^(?:https?://)?([a-z.]+)/api/rest_v1/page/html/([^/?]+)#',
501 $this->getOption( 'restURL' ), $matches ) &&
502 !preg_match(
503 '#^(?:https?://[a-z.]+)?/w/rest\.php/([a-z.]+)/v3/transform/pagebundle/to/pagebundle/([^/?]+)#',
504 $this->getOption( 'restURL' ), $matches ) &&
505 !preg_match(
506 '#^(?:https?://[a-z.]+)?/w/rest.php/([a-z.]+)/v3/page/pagebundle/([^/?]+)(?:/([^/?]+))?#',
507 $this->getOption( 'restURL' ), $matches ) &&
508 !preg_match(
509 '#^(?:https?://[a-z.]+)?/w/rest\.php/([a-z.]+)/v3/transform/wikitext/to/pagebundle/([^/?]+)#',
510 $this->getOption( 'restURL' ), $matches )
511 ) {
512 # XXX we could extend this to process other URLs, but the
513 # above are the most common seen in error logs
514 $this->error(
515 'Bad rest url.'
516 );
517 return;
518 }
519 # Calling it with the default implicitly sets it as well.
520 $this->getOption( 'domain', $matches[1] );
521 $this->getOption( 'pageName', urldecode( $matches[2] ) );
522 if ( isset( $matches[3] ) ) {
523 $this->getOption( 'revid', $matches[3] );
524 }
525 }
526 $apiURL = "https://en.wikipedia.org/w/api.php";
527 if ( $this->hasOption( 'domain' ) ) {
528 $apiURL = "https://" . $this->getOption( 'domain' ) . "/w/api.php";
529 }
530 if ( $this->hasOption( 'apiURL' ) ) {
531 $apiURL = $this->getOption( 'apiURL' );
532 }
533 $configOpts = [
534 "standalone" => !$this->hasOption( 'integrated' ),
535 "apiEndpoint" => $apiURL,
536 "addHTMLTemplateParameters" => $this->hasOption( 'addHTMLTemplateParameters' ),
537 "linting" => $this->hasOption( 'linting' ) ||
538 $this->hasOption( 'logLinterData' ) ||
539 $this->hasOption( 'wt2lint' ),
540 "mock" => $this->hasOption( 'mock' )
541 ];
542 if ( $this->hasOption( 'pageName' ) ) {
543 $configOpts['title'] = $this->getOption( 'pageName' );
544 }
545 if ( $this->hasOption( 'revid' ) ) {
546 $configOpts['revid'] = (int)$this->getOption( 'revid' );
547 }
548 if ( $this->hasOption( 'maxdepth' ) ) {
549 $configOpts['maxDepth'] = (int)$this->getOption( 'maxdepth' );
550 }
551
552 $parsoidOpts += [
553 "body_only" => ScriptUtils::booleanOption( $this->getOption( 'body_only' ) ),
554 "wrapSections" => $this->hasOption( 'wrapSections' ),
555 "logLinterData" => $this->hasOption( 'logLinterData' ),
556 "pageBundle" =>
557 $this->hasOption( 'pageBundle' ) || $this->hasOption( 'pboutfile' ),
558 ];
559 foreach ( [
560 'offsetType', 'outputContentVersion',
561 'wtVariantLanguage', 'htmlVariantLanguage',
562 'contentmodel'
563 ] as $opt ) {
564 if ( $this->hasOption( $opt ) ) {
565 $parsoidOpts[$opt] = $this->getOption( $opt );
566 }
567 }
568 if ( !$this->hasOption( 'verbose' ) ) {
569 $parsoidOpts['logLevels'] = [ 'fatal', 'error', 'warn' ];
570 }
571
572 if ( $this->hasOption( 'profile' ) ) {
573 $parsoidOpts['traceFlags'] ??= [];
574 $parsoidOpts['traceFlags']['time'] = true;
575 }
576
577 $startsAtHtml = $this->hasOption( 'html2wt' ) ||
578 $this->hasOption( 'html2html' ) ||
579 $this->hasOption( 'selser' );
580
581 $configOpts['ensureAccessibleContent'] = !$startsAtHtml ||
582 isset( $configOpts['revid'] );
583
584 if ( $startsAtHtml ) {
585 $this->transformFromHtml( $configOpts, $parsoidOpts, $input );
586 } else {
587 $this->transformFromWt( $configOpts, $parsoidOpts, $input );
588 }
589
590 if ( $this->hasOption( 'metrics' ) ) {
591 // FIXME: We're just using whatever siteConfig we ended up with,
592 // even though setupConfig may be called multiple times
593 $metrics = $this->siteConfig->metrics();
594 if ( $metrics instanceof MockMetrics ) {
595 $this->error( print_r( $metrics->log, true ) );
596 }
597 }
598 }
599
600 /**
601 * Produce a CPU flamegraph via excimer's profiling
602 */
603 private function startFlameGraphProfiler() {
604 $profiler = new ExcimerProfiler;
605 $profiler->setPeriod( 0.00001 );
606 $profiler->setEventType( EXCIMER_REAL );
607 $profiler->start();
608 register_shutdown_function( static function () use ( $profiler ) {
609 $profiler->stop();
610 $fgPath = getenv( 'FLAMEGRAPH_PATH' ) ?: '/usr/local/bin/flamegraph.pl';
611 $fgOutDir = getenv( 'FLAMEGRAPH_OUTDIR' ) ?: '/tmp';
612 // phpcs:disable MediaWiki.Usage.ForbiddenFunctions.popen
613 $pipe = popen( "$fgPath > $fgOutDir/profile.svg", "w" );
614 fwrite( $pipe, $profiler->getLog()->formatCollapsed() );
615 $report = sprintf( "%-79s %14s %14s\n", 'Function', 'Self', 'Inclusive' );
616 foreach ( $profiler->getLog()->aggregateByFunction() as $id => $info ) {
617 $report .= sprintf( "%-79s %14d %14d\n", $id, $info['self'], $info['inclusive'] );
618 }
619 file_put_contents( "$fgOutDir/aggregated.txt", $report );
620 } );
621 }
622
623 /**
624 * Optionally benchmark a callback. If benchmarking is disabled, just call
625 * it and output the return value.
626 *
627 * @param callable $callback
628 */
629 private function benchmark( $callback ) {
630 if ( $this->hasOption( 'warmup' ) ) {
631 $callback();
632 }
633 if ( $this->hasOption( 'benchmark' ) ) {
634 $count = $this->getOption( 'count', 1 );
635 if ( $this->hasOption( 'delay' ) ) {
636 usleep( $this->getOption( 'delay' ) * 1000 );
637 }
638 $startTime = microtime( true );
639 for ( $i = 0; $i < $count; $i++ ) {
640 $callback();
641 }
642 $total = ( microtime( true ) - $startTime ) * 1000;
643 $this->output( "Total time: $total ms\n" );
644 if ( $count > 1 ) {
645 $mean = $total / $count;
646 $this->output( "Mean: $mean ms\n" );
647 }
648 $this->output( sprintf( "Peak memory usage: %.2f MiB\n",
649 memory_get_peak_usage() / 1048576 ) );
650 } else {
651 $this->output( $callback() );
652 if ( self::posix_isatty( STDOUT ) ) {
653 $this->output( "\n" );
654 }
655 }
656 }
657
658 private function setupSelectiveUpdateData( ?string $mode = null ): ?SelectiveUpdateData {
659 if ( $this->hasOption( 'revtextfile' ) ) {
660 $revText = file_get_contents( $this->getOption( 'revtextfile' ) );
661 if ( $revText === false ) {
662 return null;
663 }
664 } else {
665 $this->error(
666 'Please provide original wikitext via --revtextfile. ' .
667 'Selective Serialization needs it.'
668 );
669 $this->maybeHelp();
670 return null;
671 }
672 $revHTML = null;
673 if ( $this->hasOption( 'revhtmlfile' ) ) {
674 $revHTML = file_get_contents( $this->getOption( 'revhtmlfile' ) );
675 if ( $revHTML === false ) {
676 return null;
677 }
678 $revHTML = $this->getPageBundleXML( $revHTML ) ?? $revHTML;
679 }
680 if ( $this->hasOption( 'selser' ) ) {
681 return new SelectiveUpdateData( $revText, $revHTML );
682 } elseif ( $this->hasOption( 'selpar' ) ) {
683 $revData = new SelectiveUpdateData( $revText, $revHTML, $mode );
684 $revData->templateTitle = $this->getOption( 'editedtemplatetitle' );
685 if ( !$revData->templateTitle ) {
686 $this->error(
687 'Please provide title of the edited template. ' .
688 'Selective Parsing (which right now defaults to template edits only) needs it.'
689 );
690 $this->maybeHelp();
691 return null;
692 }
693 return $revData;
694 }
695 }
696
697 /**
698 * Do html2wt or html2html and output the result
699 *
700 * @param array $configOpts
701 * @param array $parsoidOpts
702 * @param string $input
703 */
704 private function transformFromHtml( $configOpts, $parsoidOpts, $input ) {
705 $input = $this->getPageBundleXML( $input ) ?? $input;
706
707 if ( $this->hasOption( 'selser' ) ) {
708 $selserData = $this->setupSelectiveUpdateData();
709 if ( $selserData === null ) {
710 return;
711 }
712 } else {
713 $selserData = null;
714 }
715
716 if ( $this->hasOption( 'html2html' ) ) {
717 $this->benchmark(
718 function () use ( $configOpts, $parsoidOpts, $input, $selserData ) {
719 $wt = $this->html2Wt( $configOpts, $parsoidOpts, $input, $selserData );
720 $html = $this->wt2Html( $configOpts, $parsoidOpts, $wt );
721 return $this->maybeNormalize( $html );
722 }
723 );
724 } else {
725 $this->benchmark(
726 function () use ( $configOpts, $parsoidOpts, $input, $selserData ) {
727 return $this->html2Wt( $configOpts, $parsoidOpts, $input, $selserData );
728 }
729 );
730 }
731 }
732
733 /**
734 * Get the page bundle XML, or null if pbin/pbinfile was not specified
735 *
736 * @param string $input
737 * @return string|null
738 * @throws ClientError
739 */
740 private function getPageBundleXML( $input ) {
741 if ( !$this->hasOption( 'pbin' ) && !$this->hasOption( 'pbinfile' ) ) {
742 return null;
743 }
744 $doc = DOMUtils::parseHTML( $input );
745 if ( $this->hasOption( 'pbinfile' ) ) {
746 $json = file_get_contents( $this->getOption( 'pbinfile' ) );
747 } else {
748 $json = $this->getOption( 'pbin' );
749 }
750 $pb = PHPUtils::jsonDecode( $json );
751 $pb = new PageBundle(
752 '',
753 $pb['parsoid'] ?? null,
754 [ 'ids' => [] ] // FIXME: ^999.0.0
755 );
756 PageBundle::apply( $doc, $pb );
757 return ContentUtils::toXML( $doc );
758 }
759
760 /**
761 * Do a wt2html or wt2wt operation and output the result
762 *
763 * @param array $configOpts
764 * @param array $parsoidOpts
765 * @param string $input
766 */
767 private function transformFromWt( $configOpts, $parsoidOpts, $input ) {
768 if ( $this->hasOption( 'selpar' ) ) {
769 $selparData = $this->setupSelectiveUpdateData( 'template' );
770 if ( $selparData === null ) {
771 return;
772 }
773 $this->benchmark( function () use ( $configOpts, $parsoidOpts, $input, $selparData ) {
774 return $this->wt2Html( $configOpts, $parsoidOpts, $input, $selparData );
775 } );
776 } elseif ( $this->hasOption( 'wt2wt' ) ) {
777 $this->benchmark( function () use ( $configOpts, $parsoidOpts, $input ) {
778 $html = $this->wt2Html( $configOpts, $parsoidOpts, $input );
779 return $this->html2Wt( $configOpts, $parsoidOpts, $html );
780 } );
781 } elseif ( $this->hasOption( 'wt2lint' ) ) {
782 $this->output( $this->wt2Lint( $configOpts, $parsoidOpts, $input ) );
783 } elseif ( $parsoidOpts['pageBundle'] ?? false ) {
784 if ( $this->hasOption( 'pboutfile' ) ) {
785 $html = $this->wt2Html( $configOpts, $parsoidOpts, $input );
786 file_put_contents(
787 $this->getOption( 'pboutfile' ),
788 PHPUtils::jsonEncode( [
789 'parsoid' => $html->parsoid,
790 'mw' => $html->mw,
791 ] )
792 );
793 $html = $html->html;
794 } elseif ( $this->hasOption( 'pageBundle' ) ) {
795 $html = $this->wt2Html( $configOpts, $parsoidOpts, $input );
796 // Stitch this back in, even though it was just extracted
797 $doc = DOMUtils::parseHTML( $html->html );
798 DOMDataUtils::injectPageBundle(
799 $doc,
800 new PageBundle( '', $html->parsoid, $html->mw )
801 );
802 $html = ContentUtils::toXML( $doc );
803 }
804 $this->output( $this->maybeNormalize( $html ) );
805 } else {
806 $this->benchmark( function () use ( $configOpts, $parsoidOpts, $input ) {
807 return $this->wt2Html( $configOpts, $parsoidOpts, $input );
808 } );
809 }
810 }
811 }
812
813 $maintClass = Parse::class;
814 require_once PARSOID_RUN_MAINTENANCE_IF_MAIN;