Debian Codegraph @

tests/phpunit/integration/includes/Rest/Handler/ParsoidHandlerTest.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Tests\Rest\Handler;
4
5 use Composer\Semver\Semver;
6 use Exception;
7 use Generator;
8 use MediaWiki\Content\JavaScriptContent;
9 use MediaWiki\Content\WikitextContent;
10 use MediaWiki\Language\Language;
11 use MediaWiki\Language\LanguageCode;
12 use MediaWiki\MainConfigNames;
13 use MediaWiki\Page\PageIdentity;
14 use MediaWiki\Parser\ParserCache;
15 use MediaWiki\Parser\ParserCacheFactory;
16 use MediaWiki\Parser\Parsoid\Config\PageConfigFactory;
17 use MediaWiki\Parser\Parsoid\HtmlToContentTransform;
18 use MediaWiki\Parser\Parsoid\HtmlTransformFactory;
19 use MediaWiki\Parser\RevisionOutputCache;
20 use MediaWiki\Permissions\UltimateAuthority;
21 use MediaWiki\Registration\ExtensionRegistry;
22 use MediaWiki\Rest\Handler\Helper\HtmlInputTransformHelper;
23 use MediaWiki\Rest\Handler\Helper\ParsoidFormatHelper;
24 use MediaWiki\Rest\Handler\ParsoidHandler;
25 use MediaWiki\Rest\HttpException;
26 use MediaWiki\Rest\LocalizedHttpException;
27 use MediaWiki\Rest\RequestData;
28 use MediaWiki\Rest\RequestInterface;
29 use MediaWiki\Rest\Response;
30 use MediaWiki\Rest\ResponseFactory;
31 use MediaWiki\Revision\MutableRevisionRecord;
32 use MediaWiki\Revision\RevisionLookup;
33 use MediaWiki\Revision\RevisionRecord;
34 use MediaWiki\Revision\SlotRecord;
35 use MediaWiki\Tests\Rest\RestTestTrait;
36 use MediaWiki\Tests\Unit\DummyServicesTrait;
37 use MediaWiki\Title\TitleValue;
38 use MediaWiki\User\UserIdentityValue;
39 use MediaWikiIntegrationTestCase;
40 use PHPUnit\Framework\MockObject\MockObject;
41 use Wikimedia\Message\MessageValue;
42 use Wikimedia\Parsoid\Config\DataAccess;
43 use Wikimedia\Parsoid\Config\PageConfig;
44 use Wikimedia\Parsoid\Config\SiteConfig;
45 use Wikimedia\Parsoid\Core\ClientError;
46 use Wikimedia\Parsoid\Core\ResourceLimitExceededException;
47 use Wikimedia\Parsoid\DOM\Document;
48 use Wikimedia\Parsoid\Parsoid;
49 use Wikimedia\Stats\StatsFactory;
50
51 /**
52 * @group Database
53 * @covers \MediaWiki\Rest\Handler\ParsoidHandler
54 * @covers \MediaWiki\Parser\Parsoid\HtmlToContentTransform
55 */
56 class ParsoidHandlerTest extends MediaWikiIntegrationTestCase {
57 use DummyServicesTrait;
58 use RestTestTrait;
59
60 /**
61 * Default request attributes, see ParsoidHandler::getRequestAttributes()
62 */
63 private const DEFAULT_ATTRIBS = [
64 'pageName' => '',
65 'oldid' => null,
66 'body_only' => null,
67 'errorEnc' => 'plain',
68 'iwp' => 'exwiki',
69 'subst' => null,
70 'offsetType' => 'byte',
71 'opts' => [],
72 'envOptions' => [
73 'prefix' => 'exwiki',
74 'domain' => 'wiki.example.com',
75 'pageName' => '',
76 'cookie' => '',
77 'reqId' => 'test+test+test',
78 'userAgent' => 'UTAgent',
79 'htmlVariantLanguage' => null,
80 'outputContentVersion' => Parsoid::AVAILABLE_VERSIONS[0],
81 ],
82 ];
83
84 /** @var string Imperfect wikitext to be preserved if selser is applied. Corresponds to Selser.html. */
85 private const IMPERFECT_WIKITEXT = "<div >Turaco</DIV>";
86
87 /** @var string Normalized version of IMPERFECT_WIKITEXT, expected when no selser is applied. */
88 private const NORMALIZED_WIKITEXT = "<div>Turaco</div>";
89
90 public function setUp(): void {
91 // enable Pig Latin variant conversion
92 $this->overrideConfigValues( [
93 MainConfigNames::UsePigLatinVariant => true,
94 MainConfigNames::ParsoidSettings => [
95 'useSelser' => true,
96 'linting' => true,
97 ]
98 ] );
99 }
100
101 private function createRouter( $authority, $request ) {
102 return $this->newRouter( [
103 'authority' => $authority,
104 'request' => $request,
105 ] );
106 }
107
108 private function newParsoidHandler( $methodOverrides = [], $serviceOverrides = [] ): ParsoidHandler {
109 $method = 'POST';
110
111 $revisionLookup = $this->getServiceContainer()->getRevisionLookup();
112 $dataAccess = $serviceOverrides['ParsoidDataAccess'] ?? $this->getServiceContainer()->getParsoidDataAccess();
113 $siteConfig = $serviceOverrides['ParsoidSiteConfig'] ?? $this->getServiceContainer()->getParsoidSiteConfig();
114 $pageConfigFactory = $serviceOverrides['ParsoidPageConfigFactory']
115 ?? $this->getServiceContainer()->getParsoidPageConfigFactory();
116
117 $handler = new class (
118 $this,
119 $revisionLookup,
120 $siteConfig,
121 $pageConfigFactory,
122 $dataAccess,
123 $methodOverrides
124 ) extends ParsoidHandler {
125 private $testCase;
126 private $overrides;
127
128 public function __construct(
129 $testCase,
130 RevisionLookup $revisionLookup,
131 SiteConfig $siteConfig,
132 PageConfigFactory $pageConfigFactory,
133 DataAccess $dataAccess,
134 array $overrides
135 ) {
136 parent::__construct(
137 $revisionLookup,
138 $siteConfig,
139 $pageConfigFactory,
140 $dataAccess
141 );
142
143 $this->testCase = $testCase;
144 $this->overrides = $overrides;
145 }
146
147 protected function parseHTML( string $html, bool $validateXMLNames = false ): Document {
148 if ( isset( $this->overrides['parseHTML'] ) ) {
149 return $this->overrides['parseHTML']( $html, $validateXMLNames );
150 }
151
152 return parent::parseHTML(
153 $html,
154 $validateXMLNames
155 );
156 }
157
158 protected function newParsoid(): Parsoid {
159 if ( isset( $this->overrides['newParsoid'] ) ) {
160 return $this->overrides['newParsoid']();
161 }
162
163 return parent::newParsoid();
164 }
165
166 public function getRequest(): RequestInterface {
167 if ( isset( $this->overrides['getRequest'] ) ) {
168 return $this->overrides['getRequest']();
169 }
170
171 return parent::getRequest();
172 }
173
174 protected function getHtmlInputTransformHelper(
175 array $attribs,
176 string $html,
177 PageIdentity $page
178 ): HtmlInputTransformHelper {
179 if ( isset( $this->overrides['getHtmlInputHelper'] ) ) {
180 return $this->overrides['getHtmlInputHelper']();
181 }
182
183 return parent::getHtmlInputTransformHelper(
184 $attribs,
185 $html,
186 $page
187 );
188 }
189
190 public function execute(): Response {
191 ParsoidHandlerTest::fail( 'execute was not expected to be called' );
192 }
193
194 public function &getRequestAttributes(): array {
195 if ( isset( $this->overrides['getRequestAttributes'] ) ) {
196 return $this->overrides['getRequestAttributes']();
197 }
198
199 return parent::getRequestAttributes();
200 }
201
202 public function acceptable( array &$attribs ): bool {
203 if ( isset( $this->overrides['acceptable'] ) ) {
204 return $this->overrides['acceptable']( $attribs );
205 }
206
207 return parent::acceptable( $attribs );
208 }
209
210 public function tryToCreatePageConfig(
211 array $attribs, ?string $wikitext = null, bool $html2WtMode = false
212 ): PageConfig {
213 if ( isset( $this->overrides['tryToCreatePageConfig'] ) ) {
214 return $this->overrides['tryToCreatePageConfig'](
215 $attribs, $wikitext, $html2WtMode
216 );
217 }
218 $attribs += [
219 'pagelanguage' => $this->testCase->createLanguageMock( 'en' ),
220 ];
221
222 return parent::tryToCreatePageConfig(
223 $attribs, $wikitext, $html2WtMode
224 );
225 }
226
227 public function wt2html(
228 PageConfig $pageConfigConfig,
229 array $attribs,
230 ?string $wikitext = null
231 ) {
232 return parent::wt2html(
233 $pageConfigConfig,
234 $attribs,
235 $wikitext
236 );
237 }
238
239 public function html2wt( $page, array $attribs, string $html ) {
240 return parent::html2wt(
241 $page,
242 $attribs,
243 $html
244 );
245 }
246
247 public function pb2pb( array $attribs ) {
248 return parent::pb2pb( $attribs );
249 }
250
251 public function updateRedLinks(
252 PageConfig $pageConfig,
253 array $attribs,
254 array $revision
255 ) {
256 return parent::updateRedLinks(
257 $pageConfig,
258 $attribs,
259 $revision
260 );
261 }
262
263 public function languageConversion(
264 PageConfig $pageConfig,
265 array $attribs,
266 array $revision
267 ) {
268 return parent::languageConversion(
269 $pageConfig,
270 $attribs,
271 $revision
272 );
273 }
274 };
275
276 $authority = new UltimateAuthority( new UserIdentityValue( 0, '127.0.0.1' ) );
277 $request = new RequestData( [ 'method' => $method ] );
278 $router = $this->createRouter( $authority, $request );
279 $config = [];
280
281 $formatter = $this->getDummyTextFormatter( true );
282
283 /** @var ResponseFactory|MockObject $responseFactory */
284 $responseFactory = new ResponseFactory( [ 'qqx' => $formatter ] );
285
286 if ( !$request->hasBody() && $method === 'POST' ) {
287 // Send an empty body if none was provided.
288 $request->setParsedBody( [] );
289 }
290
291 $handler->initContext( $this->newModule( [ 'router' => $router ] ), 'test', $config );
292 $handler->initServices( $authority, $responseFactory, $this->createHookContainer() );
293 $handler->initSession( $this->getSession( true ) );
294 $handler->initForExecute( $request );
295
296 return $handler;
297 }
298
299 /**
300 * @param PageIdentity $page
301 * @param int|string|RevisionRecord|null $revIdOrText
302 *
303 * @return PageConfig
304 */
305 private function getPageConfig( PageIdentity $page, $revIdOrText = null ): PageConfig {
306 $rev = null;
307 if ( is_string( $revIdOrText ) ) {
308 $rev = new MutableRevisionRecord( $page );
309 $rev->setContent( SlotRecord::MAIN, new WikitextContent( $revIdOrText ) );
310 } else {
311 // may be null or an int or a RevisionRecord
312 $rev = $revIdOrText;
313 }
314
315 return $this->getServiceContainer()->getParsoidPageConfigFactory()->create( $page, null, $rev );
316 }
317
318 private function getPageConfigFactory( PageIdentity $page ): PageConfigFactory {
319 /** @var PageConfigFactory|MockObject $pageConfigFactory */
320 $pageConfigFactory = $this->createNoOpMock( PageConfigFactory::class, [ 'create' ] );
321 $pageConfigFactory->method( 'create' )->willReturn( $this->getPageConfig( $page ) );
322 return $pageConfigFactory;
323 }
324
325 private function getTextFromFile( string $name ): string {
326 return trim( file_get_contents( __DIR__ . "/data/Transform/$name" ) );
327 }
328
329 private function getJsonFromFile( string $name ): array {
330 $text = $this->getTextFromFile( $name );
331 return json_decode( $text, JSON_OBJECT_AS_ARRAY );
332 }
333
334 // Mostly lifted from the contentTypeMatcher in tests/api-testing/REST/Transform.js
335 private function contentTypeMatcher( string $expected, string $actual ): bool {
336 if ( $expected === 'application/json' ) {
337 return $actual === $expected;
338 }
339
340 $pattern = '/^([-\w]+\/[-\w]+); charset=utf-8; profile="https:\/\/www.mediawiki.org\/wiki\/Specs\/([-\w]+)\/(\d+\.\d+\.\d+)"$/';
341
342 preg_match( $pattern, $expected, $expectedParts );
343 if ( !$expectedParts ) {
344 return false;
345 }
346 [ , $expectedMime, $expectedSpec, $expectedVersion ] = $expectedParts;
347
348 preg_match( $pattern, $actual, $actualParts );
349 if ( !$actualParts ) {
350 return false;
351 }
352 [ , $actualMime, $actualSpec, $actualVersion ] = $actualParts;
353
354 // Match version using caret semantics
355 if ( !Semver::satisfies( $actualVersion, "^{$expectedVersion}" ) ) {
356 return false;
357 }
358
359 if ( $actualMime !== $expectedMime || $actualSpec !== $expectedSpec ) {
360 return false;
361 }
362
363 return true;
364 }
365
366 public function provideHtml2wt() {
367 $profileVersion = '2.6.0';
368 $wikitextProfileUri = 'https://www.mediawiki.org/wiki/Specs/wikitext/1.0.0';
369 $htmlProfileUri = 'https://www.mediawiki.org/wiki/Specs/HTML/' . $profileVersion;
370 $dataParsoidProfileUri = 'https://www.mediawiki.org/wiki/Specs/data-parsoid/' . $profileVersion;
371
372 $wikiTextContentType = "text/plain; charset=utf-8; profile=\"$wikitextProfileUri\"";
373 $htmlContentType = "text/html;profile=\"$htmlProfileUri\"";
374 $dataParsoidContentType = "application/json;profile=\"$dataParsoidProfileUri\"";
375
376 $htmlHeaders = [
377 'content-type' => $htmlContentType,
378 ];
379
380 // NOTE: profile version 999 is a placeholder for a future feature, see T78676
381 $htmlContentType999 = 'text/html;profile="https://www.mediawiki.org/wiki/Specs/HTML/999.0.0"';
382 $htmlHeaders999 = [
383 'content-type' => $htmlContentType999,
384 ];
385
386 // should convert html to wikitext ///////////////////////////////////
387 $html = $this->getTextFromFile( 'MainPage-data-parsoid.html' );
388 $expectedText = [
389 'MediaWiki has been successfully installed',
390 '== Getting started ==',
391 ];
392
393 $attribs = [];
394 yield 'should convert html to wikitext' => [
395 $attribs,
396 $html,
397 $expectedText,
398 ];
399
400 // should load original wikitext by revision id ////////////////////
401 $attribs = [
402 'oldid' => 1, // will be replaced by the actual revid
403 ];
404 yield 'should load original wikitext by revision id' => [
405 $attribs,
406 $html,
407 $expectedText,
408 ];
409
410 // should accept original wikitext in body ////////////////////
411 $originalWikitext = $this->getTextFromFile( 'OriginalMainPage.wikitext' );
412 $attribs = [
413 'opts' => [
414 'original' => [
415 'wikitext' => [
416 'headers' => [
417 'content-type' => $wikiTextContentType,
418 ],
419 'body' => $originalWikitext,
420 ]
421 ]
422 ],
423 ];
424 yield 'should accept original wikitext in body' => [
425 $attribs,
426 $html,
427 $expectedText, // TODO: ensure it's actually used!
428 ];
429
430 // should use original html for selser (default) //////////////////////
431 $originalDataParsoid = $this->getJsonFromFile( 'MainPage-original.data-parsoid' );
432 $attribs = [
433 'opts' => [
434 'from' => ParsoidFormatHelper::FORMAT_PAGEBUNDLE,
435 'original' => [
436 'html' => [
437 'headers' => $htmlHeaders,
438 'body' => $this->getTextFromFile( 'MainPage-original.html' ),
439 ],
440 'data-parsoid' => [
441 'headers' => [
442 'content-type' => $dataParsoidContentType,
443 ],
444 'body' => $originalDataParsoid
445 ]
446 ]
447 ],
448 ];
449 yield 'should use original html for selser (default)' => [
450 $attribs,
451 $html,
452 $expectedText,
453 ];
454
455 // should use original html for selser (1.1.1, meta) ///////////////////
456 $attribs = [
457 'opts' => [
458 'from' => ParsoidFormatHelper::FORMAT_PAGEBUNDLE,
459 'original' => [
460 'html' => [
461 'headers' => [
462 // XXX: If this is required anyway, how do we know we are using the
463 // version given in the HTML?
464 'content-type' => 'text/html; profile="mediawiki.org/specs/html/1.1.1"',
465 ],
466 'body' => $this->getTextFromFile( 'MainPage-data-parsoid-1.1.1.html' ),
467 ],
468 'data-parsoid' => [
469 'headers' => [
470 'content-type' => $dataParsoidContentType,
471 ],
472 'body' => $originalDataParsoid
473 ]
474 ]
475 ],
476 ];
477 yield 'should use original html for selser (1.1.1, meta)' => [
478 $attribs,
479 $html,
480 $expectedText,
481 ];
482
483 // should accept original html for selser (1.1.1, headers) ////////////
484 $attribs = [
485 'opts' => [
486 'from' => ParsoidFormatHelper::FORMAT_PAGEBUNDLE,
487 'original' => [
488 'html' => [
489 'headers' => [
490 // Set the schema version to 1.1.1!
491 'content-type' => 'text/html; profile="mediawiki.org/specs/html/1.1.1"',
492 ],
493 // No schema version in HTML
494 'body' => $this->getTextFromFile( 'MainPage-original.html' ),
495 ],
496 'data-parsoid' => [
497 'headers' => [
498 'content-type' => $dataParsoidContentType,
499 ],
500 'body' => $originalDataParsoid
501 ]
502 ]
503 ],
504 ];
505 yield 'should use original html for selser (1.1.1, headers)' => [
506 $attribs,
507 $html,
508 $expectedText,
509 ];
510
511 // Return original wikitext when HTML doesn't change ////////////////////////////
512 // New and old html are identical, which should produce no diffs
513 // and reuse the original wikitext.
514 $html = $this->getTextFromFile( 'Selser.html' );
515
516 // Original wikitext (to be preserved by selser)
517 $originalWikitext = self::IMPERFECT_WIKITEXT;
518
519 // Normalized wikitext (when no selser is applied)
520 $normalizedWikitext = self::NORMALIZED_WIKITEXT;
521
522 $dataParsoid = [ // Per Selser.html
523 'ids' => [
524 'mwAA' => [ 'dsr' => [ 0, 19, 0, 0 ] ],
525 'mwAg' => [ 'stx' => 'html', 'dsr' => [ 0, 19, 7, 6 ] ],
526 'mwAQ' => []
527 ]
528 ];
529
530 $attribs = [
531 'oldid' => 1, // Will be replaced by the revision ID of the default test page
532 'opts' => [
533 'from' => ParsoidFormatHelper::FORMAT_PAGEBUNDLE,
534 'original' => [
535 'html' => [
536 'headers' => $htmlHeaders,
537 // original HTML is the same as the new HTML
538 'body' => $html
539 ],
540 'data-parsoid' => [
541 'body' => $dataParsoid,
542 ]
543 ]
544 ],
545 ];
546
547 yield 'selser should return original wikitext if the HTML didn\'t change (original HTML given)' => [
548 $attribs,
549 $html,
550 [ $originalWikitext ], // Returns original wikitext, because HTML didn't change.
551 ];
552
553 unset( $attribs['opts']['original'] );
554 yield 'selser should return original wikitext if the HTML didn\'t change (original HTML from ParserCache)' => [
555 $attribs,
556 $html,
557 [ $originalWikitext ], // Returns original wikitext, because HTML didn't change.
558 ];
559
560 // Should fall back to non-selective serialization. //////////////////
561 // Without the original wikitext, use non-selective serialization.
562 $attribs = [
563 // No wikitext, no revid/oldid
564 'opts' => [
565 'from' => ParsoidFormatHelper::FORMAT_PAGEBUNDLE,
566 'original' => [
567 'html' => [
568 'headers' => $htmlHeaders,
569 // original HTML is the same as the new HTML
570 'body' => $html
571 ],
572 'data-parsoid' => [
573 'body' => $dataParsoid,
574 ]
575 ]
576 ],
577 ];
578 yield 'Should fall back to non-selective serialization' => [
579 $attribs,
580 $html,
581 [ $normalizedWikitext ],
582 ];
583
584 // should apply data-parsoid to duplicated ids /////////////////////////
585 $dataParsoid = [
586 'ids' => [
587 'mwAA' => [],
588 'mwBB' => [ 'autoInsertedEnd' => true, 'stx' => 'html' ]
589 ]
590 ];
591 $html = '<html><body id="mwAA"><div id="mwBB">data-parsoid test</div>' .
592 '<div id="mwBB">data-parsoid test</div></body></html>';
593 $originalHtml = '<html><body id="mwAA"><div id="mwBB">data-parsoid test</div></body></html>';
594
595 $attribs = [
596 'opts' => [
597 'from' => ParsoidFormatHelper::FORMAT_PAGEBUNDLE,
598 'original' => [
599 'html' => [
600 'headers' => $htmlHeaders,
601 'body' => $originalHtml
602 ],
603 'data-parsoid' => [
604 'body' => $dataParsoid,
605 ]
606 ]
607 ],
608 ];
609 yield 'should apply data-parsoid to duplicated ids' => [
610 $attribs,
611 $html,
612 [ '<div>data-parsoid test<div>data-parsoid test' ],
613 ];
614
615 // should ignore data-parsoid if the input format is not pagebundle ////////////////////////
616 $html = '<html><body id="mwAA"><div id="mwBB">data-parsoid test</div>' .
617 '<div id="mwBB">data-parsoid test</div></body></html>';
618 $originalHtml = '<html><body id="mwAA"><div id="mwBB">data-parsoid test</div></body></html>';
619
620 $attribs = [
621 'opts' => [
622 'from' => ParsoidFormatHelper::FORMAT_HTML,
623 'original' => [
624 'html' => [
625 'headers' => $htmlHeaders,
626 'body' => $originalHtml
627 ],
628 'data-parsoid' => [
629 // This has 'autoInsertedEnd' => true, which would cause
630 // closing </div> tags to be omitted.
631 'body' => $dataParsoid,
632 ]
633 ]
634 ],
635 ];
636 yield 'should ignore data-parsoid if the input format is not pagebundle' => [
637 $attribs,
638 $html,
639 [ '<div>data-parsoid test</div><div>data-parsoid test</div>' ],
640 ];
641
642 // should apply original data-mw ///////////////////////////////////////
643 $html = '<p about="#mwt1" typeof="mw:Transclusion" id="mwAQ">hi</p>';
644 $originalHtml = '<p about="#mwt1" typeof="mw:Transclusion" id="mwAQ">ho</p>';
645 $dataParsoid = [ 'ids' => [ 'mwAQ' => [ 'pi' => [ [ [ 'k' => '1' ] ] ] ] ] ];
646 $dataMediaWiki = [
647 'ids' => [
648 'mwAQ' => [
649 'parts' => [ [
650 'template' => [
651 'target' => [ 'wt' => '1x', 'href' => './Template:1x' ],
652 'params' => [ '1' => [ 'wt' => 'hi' ] ],
653 'i' => 0
654 ]
655 ] ]
656 ]
657 ]
658 ];
659 $attribs = [
660 'opts' => [
661 'from' => ParsoidFormatHelper::FORMAT_PAGEBUNDLE,
662 'original' => [
663 'html' => [
664 'headers' => $htmlHeaders,
665 'body' => $originalHtml
666 ],
667 'data-parsoid' => [
668 'body' => $dataParsoid,
669 ],
670 'data-mw' => [
671 'body' => $dataMediaWiki,
672 ],
673 ]
674 ],
675 ];
676 yield 'should apply original data-mw' => [
677 $attribs,
678 $html,
679 [ '{{1x|hi}}' ],
680 ];
681
682 // should give precedence to inline data-mw over original ////////
683 $html = '<p about="#mwt1" typeof="mw:Transclusion" data-mw=\'{"parts":[{"template":{"target":{"wt":"1x","href":"./Template:1x"},"params":{"1":{"wt":"hi"}},"i":0}}]}\' id="mwAQ">hi</p>';
684 $originalHtml = '<p about="#mwt1" typeof="mw:Transclusion" id="mwAQ">ho</p>';
685 $dataParsoid = [ 'ids' => [ 'mwAQ' => [ 'pi' => [ [ [ 'k' => '1' ] ] ] ] ] ];
686 $dataMediaWiki = [ 'ids' => [ 'mwAQ' => [] ] ]; // Missing data-mw.parts!
687 $attribs = [
688 'opts' => [
689 'from' => ParsoidFormatHelper::FORMAT_PAGEBUNDLE,
690 'original' => [
691 'html' => [
692 'headers' => $htmlHeaders,
693 'body' => $originalHtml
694 ],
695 'data-parsoid' => [
696 'body' => $dataParsoid,
697 ],
698 'data-mw' => [
699 'body' => $dataMediaWiki,
700 ],
701 ]
702 ],
703 ];
704 yield 'should give precedence to inline data-mw over original' => [
705 $attribs,
706 $html,
707 [ '{{1x|hi}}' ],
708 ];
709
710 // should not apply original data-mw if modified is supplied ///////////
711 $html = '<p about="#mwt1" typeof="mw:Transclusion" id="mwAQ">hi</p>';
712 $originalHtml = '<p about="#mwt1" typeof="mw:Transclusion" id="mwAQ">ho</p>';
713 $dataParsoid = [ 'ids' => [ 'mwAQ' => [ 'pi' => [ [ [ 'k' => '1' ] ] ] ] ] ];
714 $dataMediaWiki = [ 'ids' => [ 'mwAQ' => [] ] ]; // Missing data-mw.parts!
715 $dataMediaWikiModified = [
716 'ids' => [
717 'mwAQ' => [
718 'parts' => [ [
719 'template' => [
720 'target' => [ 'wt' => '1x', 'href' => './Template:1x' ],
721 'params' => [ '1' => [ 'wt' => 'hi' ] ],
722 'i' => 0
723 ]
724 ] ]
725 ]
726 ]
727 ];
728 $attribs = [
729 'opts' => [
730 'from' => ParsoidFormatHelper::FORMAT_PAGEBUNDLE,
731 'data-mw' => [ // modified data
732 'body' => $dataMediaWikiModified,
733 ],
734 'original' => [
735 'html' => [
736 'headers' => $htmlHeaders999,
737 'body' => $originalHtml
738 ],
739 'data-parsoid' => [
740 'body' => $dataParsoid,
741 ],
742 'data-mw' => [ // original data
743 'body' => $dataMediaWiki,
744 ],
745 ]
746 ],
747 ];
748 yield 'should not apply original data-mw if modified is supplied' => [
749 $attribs,
750 $html,
751 [ '{{1x|hi}}' ],
752 ];
753
754 // should apply original data-mw when modified is absent (captions 1) ///////////
755 $html = $this->getTextFromFile( 'Image.html' );
756 $dataParsoid = [ 'ids' => [
757 'mwAg' => [ 'optList' => [ [ 'ck' => 'caption', 'ak' => 'Testing 123' ] ] ],
758 'mwAw' => [ 'a' => [ 'href' => './File:Foobar.jpg' ], 'sa' => [] ],
759 'mwBA' => [
760 'a' => [ 'resource' => './File:Foobar.jpg', 'height' => '28', 'width' => '240' ],
761 'sa' => [ 'resource' => 'File:Foobar.jpg' ]
762 ]
763 ] ];
764 $dataMediaWiki = [ 'ids' => [ 'mwAg' => [ 'caption' => 'Testing 123' ] ] ];
765
766 $attribs = [
767 'opts' => [
768 'from' => ParsoidFormatHelper::FORMAT_PAGEBUNDLE,
769 'original' => [
770 'data-parsoid' => [
771 'body' => $dataParsoid,
772 ],
773 'data-mw' => [ // original data
774 'body' => $dataMediaWiki,
775 ],
776 'html' => [
777 'headers' => $htmlHeaders999,
778 'body' => $html
779 ],
780 ]
781 ],
782 ];
783 yield 'should apply original data-mw when modified is absent (captions 1)' => [
784 $attribs,
785 $html, // modified HTML
786 [ '[[File:Foobar.jpg|Testing 123]]' ],
787 ];
788
789 // should give precedence to inline data-mw over modified (captions 2) /////////////
790 $htmlModified = $this->getTextFromFile( 'Image-data-mw.html' );
791 $dataMediaWikiModified = [
792 'ids' => [
793 'mwAg' => [ 'caption' => 'Testing 123' ]
794 ]
795 ];
796
797 $attribs = [
798 'opts' => [
799 'from' => ParsoidFormatHelper::FORMAT_PAGEBUNDLE,
800 'data-mw' => [
801 'body' => $dataMediaWikiModified,
802 ],
803 'original' => [
804 'data-parsoid' => [
805 'body' => $dataParsoid,
806 ],
807 'data-mw' => [ // original data
808 'body' => $dataMediaWiki,
809 ],
810 'html' => [
811 'headers' => $htmlHeaders999,
812 'body' => $html
813 ],
814 ]
815 ],
816 ];
817 yield 'should give precedence to inline data-mw over modified (captions 2)' => [
818 $attribs,
819 $htmlModified, // modified HTML
820 [ '[[File:Foobar.jpg]]' ],
821 ];
822
823 // should give precedence to modified data-mw over original (captions 3) /////////////
824 $dataMediaWikiModified = [
825 'ids' => [
826 'mwAg' => []
827 ]
828 ];
829
830 $attribs = [
831 'opts' => [
832 'from' => ParsoidFormatHelper::FORMAT_PAGEBUNDLE,
833 'data-mw' => [
834 'body' => $dataMediaWikiModified,
835 ],
836 'original' => [
837 'data-parsoid' => [
838 'body' => $dataParsoid,
839 ],
840 'data-mw' => [ // original data
841 'body' => $dataMediaWiki,
842 ],
843 'html' => [
844 'headers' => $htmlHeaders999,
845 'body' => $html
846 ],
847 ]
848 ],
849 ];
850 yield 'should give precedence to modified data-mw over original (captions 3)' => [
851 $attribs,
852 $html, // modified HTML
853 [ '[[File:Foobar.jpg]]' ],
854 ];
855
856 // should apply extra normalizations ///////////////////
857 $htmlModified = 'Foo<h2></h2>Bar';
858 $attribs = [
859 'opts' => [
860 'original' => []
861 ],
862 ];
863 yield 'should apply extra normalizations' => [
864 $attribs,
865 $htmlModified, // modified HTML
866 [ 'FooBar' ], // empty tag was stripped
867 ];
868
869 // should apply version downgrade ///////////
870 $htmlOfMinimal = $this->getTextFromFile( 'Minimal.html' ); // Uses profile version 2.4.0
871 $attribs = [
872 'opts' => [
873 'from' => ParsoidFormatHelper::FORMAT_PAGEBUNDLE,
874 'original' => [
875 'html' => [
876 'headers' => [
877 // Specify newer profile version for original HTML
878 'content-type' => 'text/html;profile="https://www.mediawiki.org/wiki/Specs/HTML/999.0.0"'
879 ],
880 // The profile version given inline in the original HTML doesn't matter, it's ignored
881 'body' => $htmlOfMinimal,
882 ],
883 'data-parsoid' => [ 'body' => [ 'ids' => [] ] ],
884 'data-mw' => [ 'body' => [ 'ids' => [] ] ], // required by version 999.0.0
885 ]
886 ],
887 ];
888 yield 'should apply version downgrade' => [
889 $attribs,
890 $htmlOfMinimal,
891 [ '123' ]
892 ];
893
894 // should not apply version downgrade if versions are the same ///////////
895 $htmlOfMinimal = $this->getTextFromFile( 'Minimal.html' ); // Uses profile version 2.4.0
896 $attribs = [
897 'opts' => [
898 'from' => ParsoidFormatHelper::FORMAT_PAGEBUNDLE,
899 'original' => [
900 'html' => [
901 'headers' => [
902 // Specify the exact same version specified inline in Minimal.html 2.4.0
903 'content-type' => 'text/html;profile="https://www.mediawiki.org/wiki/Specs/HTML/2.4.0"'
904 ],
905 // The profile version given inline in the original HTML doesn't matter, it's ignored
906 'body' => $htmlOfMinimal,
907 ],
908 'data-parsoid' => [ 'body' => [ 'ids' => [] ] ],
909 ]
910 ],
911 ];
912 yield 'should not apply version downgrade if versions are the same' => [
913 $attribs,
914 $htmlOfMinimal,
915 [ '123' ]
916 ];
917
918 // should convert html to json ///////////////////////////////////
919 $html = $this->getTextFromFile( 'JsonConfig.html' );
920 $expectedText = [
921 '{"a":4,"b":3}',
922 ];
923
924 $attribs = [
925 'opts' => [
926 // even if the path says "wikitext", the contentmodel from the body should win.
927 'format' => ParsoidFormatHelper::FORMAT_WIKITEXT,
928 'contentmodel' => CONTENT_MODEL_JSON,
929 ],
930 ];
931 yield 'should convert html to json' => [
932 $attribs,
933 $html,
934 $expectedText,
935 [ 'content-type' => 'application/json' ],
936 ];
937
938 // page bundle input should work with no original data present ///////////
939 $htmlOfMinimal = $this->getTextFromFile( 'Minimal.html' ); // Uses profile version 2.4.0
940 $attribs = [
941 'opts' => [
942 'from' => ParsoidFormatHelper::FORMAT_PAGEBUNDLE,
943 'original' => [],
944 ],
945 ];
946 yield 'page bundle input should work with no original data present' => [
947 $attribs,
948 $htmlOfMinimal,
949 [ '123' ]
950 ];
951 }
952
953 private function makePage( $title, $wikitext ): RevisionRecord {
954 $title = new TitleValue( NS_MAIN, $title );
955 $rev = $this->getServiceContainer()->getRevisionLookup()->getRevisionByTitle( $title );
956
957 if ( $rev ) {
958 return $rev;
959 }
960
961 /** @var RevisionRecord $rev */
962 [ 'revision-record' => $rev ] = $this->editPage( 'Test_html2wt', $wikitext )->getValue();
963
964 return $rev;
965 }
966
967 /**
968 * @dataProvider provideHtml2wt
969 *
970 * @param array $attribs
971 * @param string $html
972 * @param string[] $expectedText
973 * @param string[] $expectedHeaders
974 *
975 * @covers \MediaWiki\Parser\Parsoid\HtmlToContentTransform
976 * @covers \MediaWiki\Rest\Handler\ParsoidHandler::html2wt
977 */
978 public function testHtml2wt(
979 array $attribs,
980 string $html,
981 array $expectedText,
982 array $expectedHeaders = []
983 ) {
984 $wikitextProfileUri = 'https://www.mediawiki.org/wiki/Specs/wikitext/1.0.0';
985 $expectedHeaders += [
986 'content-type' => "text/plain; charset=utf-8; profile=\"$wikitextProfileUri\"",
987 ];
988
989 $wikitext = self::IMPERFECT_WIKITEXT;
990
991 $rev = $this->makePage( 'Test_html2wt', $wikitext );
992 $page = $rev->getPage();
993
994 $pageConfig = $this->getPageConfig( $page );
995
996 $attribs += self::DEFAULT_ATTRIBS;
997 $attribs['opts'] += self::DEFAULT_ATTRIBS['opts'];
998 $attribs['opts']['from'] ??= 'html';
999 $attribs['envOptions'] += self::DEFAULT_ATTRIBS['envOptions'];
1000
1001 if ( $attribs['oldid'] ) {
1002 // Set the actual ID of an existing revision
1003 $attribs['oldid'] = $rev->getId();
1004 }
1005
1006 $handler = $this->newParsoidHandler();
1007
1008 $response = $handler->html2wt( $pageConfig, $attribs, $html );
1009 $body = $response->getBody();
1010 $body->rewind();
1011 $wikitext = $body->getContents();
1012
1013 foreach ( $expectedHeaders as $name => $value ) {
1014 $this->assertSame( $value, $response->getHeaderLine( $name ) );
1015 }
1016
1017 foreach ( (array)$expectedText as $exp ) {
1018 $this->assertStringContainsString( $exp, $wikitext );
1019 }
1020 }
1021
1022 public function provideHtml2wtThrows() {
1023 $html = '<html lang="en"><body>123</body></html>';
1024
1025 $profileVersion = '2.4.0';
1026 $htmlProfileUri = 'https://www.mediawiki.org/wiki/Specs/HTML/' . $profileVersion;
1027 $htmlContentType = "text/html;profile=\"$htmlProfileUri\"";
1028 $htmlHeaders = [
1029 'content-type' => $htmlContentType,
1030 ];
1031
1032 // XXX: what does version 999.0.0 mean?!
1033 $htmlContentType999 = 'text/html;profile="https://www.mediawiki.org/wiki/Specs/HTML/999.0.0"';
1034 $htmlHeaders999 = [
1035 'content-type' => $htmlContentType999,
1036 ];
1037
1038 // Content-type of original html is missing ////////////////////////////
1039 $attribs = [
1040 'opts' => [
1041 'original' => [
1042 'html' => [
1043 // no headers with content type
1044 'body' => $html,
1045 ],
1046 ]
1047 ],
1048 ];
1049 yield 'Content-type of original html is missing' => [
1050 $attribs,
1051 $html,
1052 new LocalizedHttpException(
1053 new MessageValue( 'rest-html-backend-error', [ 'Content-type of original html is missing.' ] ),
1054 400,
1055 [ 'reason' => 'Content-type of original html is missing.' ]
1056 )
1057 ];
1058
1059 // should fail to downgrade the original version for an unknown transition ///////////
1060 $htmlOfMinimal = $this->getTextFromFile( 'Minimal.html' );
1061 $htmlOfMinimal2222 = $this->getTextFromFile( 'Minimal-2222.html' );
1062 $attribs = [
1063 'opts' => [
1064 'from' => ParsoidFormatHelper::FORMAT_PAGEBUNDLE,
1065 'original' => [
1066 'html' => [
1067 'headers' => [
1068 // Specify version 2222.0.0!
1069 'content-type' => 'text/html;profile="https://www.mediawiki.org/wiki/Specs/HTML/2222.0.0"'
1070 ],
1071 'body' => $htmlOfMinimal2222,
1072 ],
1073 'data-parsoid' => [ 'body' => [ 'ids' => [] ] ],
1074 ]
1075 ],
1076 ];
1077 yield 'should fail to downgrade the original version for an unknown transition' => [
1078 $attribs,
1079 $htmlOfMinimal,
1080 new LocalizedHttpException(
1081 new MessageValue( 'rest-html-backend-error', [ 'No downgrade possible from schema version 2222.0.0 to 2.4.0.' ] ),
1082 400,
1083 [ 'reason' => 'No downgrade possible from schema version 2222.0.0 to 2.4.0.' ]
1084 )
1085 ];
1086
1087 // DSR offsetType mismatch: UCS2 vs byte ///////////////////////////////
1088 $attribs = [
1089 'offsetType' => 'byte',
1090 'envOptions' => [],
1091 'opts' => [
1092 'from' => ParsoidFormatHelper::FORMAT_PAGEBUNDLE,
1093 'original' => [
1094 'html' => [
1095 'headers' => $htmlHeaders,
1096 'body' => $html,
1097 ],
1098 'data-parsoid' => [
1099 'body' => [
1100 'offsetType' => 'UCS2',
1101 'ids' => [],
1102 ]
1103 ],
1104 ]
1105 ],
1106 ];
1107 yield 'DSR offsetType mismatch: UCS2 vs byte' => [
1108 $attribs,
1109 $html,
1110 new LocalizedHttpException(
1111 new MessageValue( 'rest-html-backend-error', [ 'DSR offsetType mismatch: UCS2 vs byte' ] ),
1112 400,
1113 [ 'reason' => 'DSR offsetType mismatch: UCS2 vs byte' ]
1114 )
1115 ];
1116
1117 // DSR offsetType mismatch: byte vs UCS2 ///////////////////////////////
1118 $attribs = [
1119 'offsetType' => 'UCS2',
1120 'envOptions' => [],
1121 'opts' => [
1122 // Enable selser
1123 'from' => ParsoidFormatHelper::FORMAT_PAGEBUNDLE,
1124 'original' => [
1125 'html' => [
1126 'headers' => $htmlHeaders,
1127 'body' => $html,
1128 ],
1129 'data-parsoid' => [
1130 'body' => [
1131 'offsetType' => 'byte',
1132 'ids' => [],
1133 ]
1134 ],
1135 ]
1136 ],
1137 ];
1138 yield 'DSR offsetType mismatch: byte vs UCS2' => [
1139 $attribs,
1140 $html,
1141 new LocalizedHttpException(
1142 new MessageValue( 'rest-html-backend-error', [ 'DSR offsetType mismatch: byte vs UCS2' ] ),
1143 400,
1144 [ 'reason' => 'DSR offsetType mismatch: byte vs UCS2' ]
1145 )
1146 ];
1147
1148 // Could not find previous revision ////////////////////////////
1149 $attribs = [
1150 'oldid' => 1155779922,
1151 'opts' => [
1152 // set original HTML to enable selser
1153 'original' => [
1154 'html' => [
1155 'headers' => $htmlHeaders,
1156 'body' => $html,
1157 ]
1158 ]
1159 ]
1160 ];
1161 yield 'Could not find previous revision' => [
1162 $attribs,
1163 $html,
1164 new LocalizedHttpException( new MessageValue( "rest-specified-revision-unavailable" ),
1165 404
1166 )
1167 ];
1168
1169 // should return a 400 for missing inline data-mw (2.x) ///////////////////
1170 $html = '<p about="#mwt1" typeof="mw:Transclusion" id="mwAQ">hi</p>';
1171 $dataParsoid = [ 'ids' => [ 'mwAQ' => [ 'pi' => [ [ [ 'k' => '1' ] ] ] ] ] ];
1172 $htmlOrig = '<p about="#mwt1" typeof="mw:Transclusion" id="mwAQ">ho</p>';
1173 $attribs = [
1174 'opts' => [
1175 'from' => ParsoidFormatHelper::FORMAT_PAGEBUNDLE,
1176 'original' => [
1177 'data-parsoid' => [
1178 'body' => $dataParsoid,
1179 ],
1180 'html' => [
1181 'headers' => $htmlHeaders,
1182 // slightly modified
1183 'body' => $htmlOrig,
1184 ]
1185 ]
1186 ],
1187 ];
1188 yield 'should return a 400 for missing inline data-mw (2.x)' => [
1189 $attribs,
1190 $html,
1191 new LocalizedHttpException( new MessageValue( 'rest-parsoid-error', [ 'Cannot serialize mw:Transclusion without data-mw.parts or data-parsoid.src' ] ),
1192 400
1193 )
1194 ];
1195
1196 // should return a 400 for not supplying data-mw //////////////////////
1197 $attribs = [
1198 'opts' => [
1199 'from' => ParsoidFormatHelper::FORMAT_PAGEBUNDLE,
1200 'original' => [
1201 'data-parsoid' => [
1202 'body' => $dataParsoid,
1203 ],
1204 'html' => [
1205 'headers' => $htmlHeaders999,
1206 'body' => $htmlOrig,
1207 ]
1208 ]
1209 ],
1210 ];
1211 yield 'should return a 400 for not supplying data-mw' => [
1212 $attribs,
1213 $html,
1214 new LocalizedHttpException(
1215 new MessageValue( 'rest-html-backend-error', [ 'Invalid data-mw was provided.' ] ),
1216 400,
1217 [ 'reason' => 'Invalid data-mw was provided.' ]
1218 )
1219 ];
1220
1221 // should return a 400 for missing modified data-mw
1222 $attribs = [
1223 'opts' => [
1224 'from' => ParsoidFormatHelper::FORMAT_PAGEBUNDLE,
1225 'original' => [
1226 'data-parsoid' => [
1227 'body' => $dataParsoid,
1228 ],
1229 'data-mw' => [
1230 'body' => [
1231 // Missing data-mw.parts!
1232 'ids' => [ 'mwAQ' => [] ],
1233 ]
1234 ],
1235 'html' => [
1236 'headers' => $htmlHeaders999,
1237 'body' => $htmlOrig,
1238 ]
1239 ]
1240 ],
1241 ];
1242 yield 'should return a 400 for missing modified data-mw' => [
1243 $attribs,
1244 $html,
1245 new LocalizedHttpException( new MessageValue( 'rest-parsoid-error', [ 'Cannot serialize mw:Transclusion without data-mw.parts or data-parsoid.src' ] ),
1246 400
1247 )
1248 ];
1249
1250 // should return http 400 if supplied data-parsoid is empty ////////////
1251 $html = '<html><head></head><body><p>hi</p></body></html>';
1252 $htmlOrig = '<html><head></head><body><p>ho</p></body></html>';
1253 $attribs = [
1254 'opts' => [
1255 'from' => ParsoidFormatHelper::FORMAT_PAGEBUNDLE,
1256 'original' => [
1257 'data-parsoid' => [
1258 'body' => [],
1259 ],
1260 'html' => [
1261 'headers' => $htmlHeaders,
1262 'body' => $htmlOrig,
1263 ]
1264 ]
1265 ],
1266 ];
1267 yield 'should return http 400 if supplied data-parsoid is empty' => [
1268 $attribs,
1269 $html,
1270 new LocalizedHttpException(
1271 new MessageValue( 'rest-html-backend-error', [ 'Invalid data-parsoid was provided.' ] ),
1272 400,
1273 [ 'reason' => 'Invalid data-parsoid was provided.' ]
1274 )
1275 ];
1276
1277 // TODO: ResourceLimitExceededException from $parsoid->dom2wikitext -> 413
1278 // TODO: ClientError from $parsoid->dom2wikitext -> 413
1279 // TODO: Errors from PageBundle->validate
1280 }
1281
1282 /**
1283 * @dataProvider provideHtml2wtThrows
1284 *
1285 * @param array $attribs
1286 * @param string $html
1287 * @param Exception $expectedException
1288 */
1289 public function testHtml2wtThrows(
1290 array $attribs,
1291 string $html,
1292 Exception $expectedException
1293 ) {
1294 if ( isset( $attribs['oldid'] ) ) {
1295 // If a specific revision ID is requested, it's almost certain to no exist.
1296 // So we are testing with a non-existing page.
1297 $page = $this->getNonexistingTestPage();
1298 } else {
1299 $page = $this->getExistingTestPage();
1300 }
1301
1302 $pageConfig = $this->getPageConfig( $page );
1303
1304 $attribs += self::DEFAULT_ATTRIBS;
1305 $attribs['opts'] += self::DEFAULT_ATTRIBS['opts'];
1306 $attribs['opts']['from'] ??= 'html';
1307 $attribs['envOptions'] += self::DEFAULT_ATTRIBS['envOptions'];
1308
1309 $handler = $this->newParsoidHandler();
1310
1311 try {
1312 $handler->html2wt( $pageConfig, $attribs, $html );
1313 $this->fail( 'Expected exception: ' . $expectedException );
1314 } catch ( Exception $e ) {
1315 $this->assertInstanceOf( get_class( $expectedException ), $e );
1316 $this->assertSame( $expectedException->getCode(), $e->getCode() );
1317
1318 if ( $expectedException instanceof HttpException ) {
1319 /** @var HttpException $e */
1320 $this->assertSame(
1321 $expectedException->getErrorData(),
1322 array_intersect_key(
1323 $expectedException->getErrorData(),
1324 $e->getErrorData()
1325 )
1326 );
1327 }
1328
1329 if ( $expectedException instanceof LocalizedHttpException ) {
1330 /** @var LocalizedHttpException $expectedException */
1331 $this->assertInstanceOf( LocalizedHttpException::class, $e );
1332 $this->assertEquals( $expectedException->getMessageValue(), $e->getMessageValue() );
1333 $this->assertSame( $expectedException->getErrorData(), $e->getErrorData() );
1334 }
1335
1336 $this->assertSame( $expectedException->getMessage(), $e->getMessage() );
1337 }
1338 }
1339
1340 public static function provideDom2wikitextException() {
1341 yield 'ClientError' => [
1342 new ClientError( 'test' ),
1343 new LocalizedHttpException( new MessageValue( 'rest-parsoid-error', [ 'test' ] ), 400 )
1344 ];
1345
1346 yield 'ResourceLimitExceededException' => [
1347 new ResourceLimitExceededException( 'test' ),
1348 new LocalizedHttpException( new MessageValue( 'rest-parsoid-resource-exceeded', [ 'test' ] ), 413 )
1349 ];
1350 }
1351
1352 /**
1353 * @dataProvider provideDom2wikitextException
1354 *
1355 * @param Exception $throw
1356 * @param Exception $expectedException
1357 */
1358 public function testHtml2wtHandlesDom2wikitextException(
1359 Exception $throw,
1360 Exception $expectedException
1361 ) {
1362 $html = '<p>hi</p>';
1363 $page = $this->getExistingTestPage();
1364 $attribs = [
1365 'opts' => [
1366 'from' => ParsoidFormatHelper::FORMAT_HTML
1367 ]
1368 ] + self::DEFAULT_ATTRIBS;
1369
1370 // Make a fake Parsoid that throws
1371 /** @var Parsoid|MockObject $parsoid */
1372 $parsoid = $this->createNoOpMock( Parsoid::class, [ 'dom2wikitext' ] );
1373 $parsoid->method( 'dom2wikitext' )->willThrowException( $throw );
1374
1375 // Make a fake HtmlTransformFactory that returns an HtmlToContentTransform that uses the fake Parsoid.
1376 /** @var HtmlTransformFactory|MockObject $factory */
1377 $factory = $this->createNoOpMock( HtmlTransformFactory::class, [ 'getHtmlToContentTransform' ] );
1378 $factory->method( 'getHtmlToContentTransform' )->willReturn( new HtmlToContentTransform(
1379 $html,
1380 $page,
1381 $parsoid,
1382 [],
1383 $this->getPageConfigFactory( $page ),
1384 $this->getServiceContainer()->getContentHandlerFactory()
1385 ) );
1386
1387 // Use an HtmlInputTransformHelper that uses the fake HtmlTransformFactory, so it ends up
1388 // using the HtmlToContentTransform that has the fake Parsoid which throws an exception.
1389 $handler = $this->newParsoidHandler( [
1390 'getHtmlInputHelper' => function () use ( $factory, $page, $html ) {
1391 $helper = new HtmlInputTransformHelper(
1392 StatsFactory::newNull(),
1393 $factory,
1394 $this->getServiceContainer()->getParsoidOutputStash(),
1395 $this->getServiceContainer()->getParserOutputAccess(),
1396 $this->getServiceContainer()->getPageStore(),
1397 $this->getServiceContainer()->getRevisionLookup(),
1398 [],
1399 $page,
1400 [ 'html' => $html ],
1401 []
1402 );
1403 return $helper;
1404 }
1405 ] );
1406
1407 try {
1408 $handler->html2wt( $page, $attribs, $html );
1409 $this->fail( 'Expected exception ' . get_class( $expectedException ) . ' not thrown' );
1410 } catch ( Exception $e ) {
1411 $this->assertSame( $expectedException->getCode(), $e->getCode() );
1412 $this->assertSame( $expectedException->getMessage(), $e->getMessage() );
1413
1414 if ( $expectedException instanceof LocalizedHttpException ) {
1415 $this->assertEquals( $expectedException->getMessageValue(), $e->getMessageValue() );
1416 $this->assertSame( $expectedException->getErrorData(), $e->getErrorData() );
1417
1418 }
1419 $this->assertSame( $expectedException->getMessage(), $e->getMessage() );
1420
1421 }
1422 }
1423
1424 /** @return Generator */
1425 public function provideTryToCreatePageConfigData() {
1426 $en = $this->createLanguageMock( 'en' );
1427 $ar = $this->createLanguageMock( 'ar' );
1428 $de = $this->createLanguageMock( 'de' );
1429 yield 'Default attribs for tryToCreatePageConfig()' => [
1430 'attribs' => [ 'oldid' => 1, 'pageName' => 'Test', 'pagelanguage' => $en ],
1431 'wikitext' => null,
1432 'html2WtMode' => false,
1433 'expectedPageLanguage' => $en,
1434 ];
1435
1436 yield 'tryToCreatePageConfig with wikitext' => [
1437 'attribs' => [ 'oldid' => 1, 'pageName' => 'Test', 'pagelanguage' => $en ],
1438 'wikitext' => "=test=",
1439 'html2WtMode' => false,
1440 'expected page language' => $en,
1441 ];
1442
1443 yield 'tryToCreatePageConfig with html2WtMode set to true' => [
1444 'attribs' => [ 'oldid' => 1, 'pageName' => 'Test', 'pagelanguage' => null ],
1445 'wikitext' => null,
1446 'html2WtMode' => true,
1447 'expected page language' => $en,
1448 ];
1449
1450 yield 'tryToCreatePageConfig with both wikitext and html2WtMode' => [
1451 'attribs' => [ 'oldid' => 1, 'pageName' => 'Test', 'pagelanguage' => $ar ],
1452 'wikitext' => "=header=",
1453 'html2WtMode' => true,
1454 'expected page language' => $ar,
1455 ];
1456
1457 yield 'Try to create a page config with pageName set to empty string' => [
1458 'attribs' => [ 'oldid' => 1, 'pageName' => '', 'pagelanguage' => $de ],
1459 'wikitext' => null,
1460 'html2WtMode' => false,
1461 'expected page language' => $de,
1462 ];
1463
1464 yield 'Try to create a page config with pageName set to zero string' => [
1465 'attribs' => [ 'oldid' => 1, 'pageName' => '0', 'pagelanguage' => $de ],
1466 'wikitext' => null,
1467 'html2WtMode' => false,
1468 'expected page language' => $de,
1469 ];
1470
1471 yield 'Try to create a page config with no page language' => [
1472 'attribs' => [ 'oldid' => 1, 'pageName' => '', 'pagelanguage' => null ],
1473 'wikitext' => null,
1474 false,
1475 'expected page language' => $en,
1476 ];
1477 }
1478
1479 /**
1480 * @covers \MediaWiki\Rest\Handler\ParsoidHandler::tryToCreatePageConfig
1481 *
1482 * @dataProvider provideTryToCreatePageConfigData
1483 */
1484 public function testTryToCreatePageConfig(
1485 array $attribs,
1486 ?string $wikitext,
1487 $html2WtMode,
1488 Language $expectedLanguage
1489 ) {
1490 // Create a page, if needed, to test with oldid
1491 $origContent = 'Test content for ' . __METHOD__;
1492 $page = $this->getNonexistingTestPage();
1493 $this->editPage( $page, $origContent );
1494 $expectedWikitext = $wikitext ?? $origContent;
1495 $pageConfig = $this->newParsoidHandler()->tryToCreatePageConfig( $attribs, $wikitext, $html2WtMode );
1496
1497 $this->assertSame(
1498 $expectedWikitext,
1499 $pageConfig->getRevisionContent()->getContent( SlotRecord::MAIN )
1500 );
1501
1502 $pageName = ( $attribs['pageName'] === '' ) ? 'Main Page' : $attribs['pageName'];
1503 $this->assertSame( $pageName, $pageConfig->getLinkTarget()->getPrefixedText() );
1504
1505 $this->assertSame( $expectedLanguage->getCode(), $pageConfig->getPageLanguageBcp47()->getCode() );
1506 }
1507
1508 /** @return Generator */
1509 public function provideTryToCreatePageConfigDataThrows() {
1510 $en = $this->createLanguageMock( 'en' );
1511 yield "PageConfig with oldid that doesn't exist" => [
1512 'attribs' => [ 'oldid' => null, 'pageName' => 'Test', 'pagelanguage' => $en ],
1513 'wikitext' => null,
1514 'html2WtMode' => false,
1515 ];
1516
1517 yield 'PageConfig with a bad title' => [
1518 [ 'oldid' => null, 'pageName' => 'Special:Badtitle', 'pagelanguage' => $en ],
1519 'wikitext' => null,
1520 'html2WtMode' => false,
1521 ];
1522
1523 yield "PageConfig with a revision that doesn't exist" => [
1524 // 'oldid' is so large because we want to emulate a revision
1525 // that doesn't exist.
1526 [ 'oldid' => 12345678, 'pageName' => 'Test', 'pagelanguage' => $en ],
1527 'wikitext' => null,
1528 'html2WtMode' => false,
1529 ];
1530 }
1531
1532 /**
1533 * @covers \MediaWiki\Rest\Handler\ParsoidHandler::tryToCreatePageConfig
1534 *
1535 * @dataProvider provideTryToCreatePageConfigDataThrows
1536 */
1537 public function testTryToCreatePageConfigThrows( array $attribs, $wikitext, $html2WtMode ) {
1538 $this->expectException( HttpException::class );
1539 $this->expectExceptionCode( 404 );
1540
1541 $this->newParsoidHandler()->tryToCreatePageConfig( $attribs, $wikitext, $html2WtMode );
1542 }
1543
1544 public static function provideRoundTripNoSelser() {
1545 yield 'space in heading' => [
1546 "==foo==\nsomething\n"
1547 ];
1548 }
1549
1550 public static function provideRoundTripNeedingSelser() {
1551 yield 'uppercase tags' => [
1552 "<DIV>foo</div>"
1553 ];
1554 }
1555
1556 /**
1557 * @dataProvider provideRoundTripNoSelser
1558 */
1559 public function testRoundTripWithHTML( $wikitext ) {
1560 $handler = $this->newParsoidHandler();
1561
1562 $attribs = self::DEFAULT_ATTRIBS;
1563 $attribs['opts']['from'] = ParsoidFormatHelper::FORMAT_WIKITEXT;
1564 $attribs['opts']['format'] = ParsoidFormatHelper::FORMAT_HTML;
1565
1566 $pageConfig = $handler->tryToCreatePageConfig( $attribs, $wikitext );
1567 $response = $handler->wt2html( $pageConfig, $attribs, $wikitext );
1568 $body = $response->getBody();
1569 $body->rewind();
1570 $html = $body->getContents();
1571
1572 // Got HTML, now convert back
1573 $attribs = self::DEFAULT_ATTRIBS;
1574 $attribs['opts']['from'] = ParsoidFormatHelper::FORMAT_HTML;
1575 $attribs['opts']['format'] = ParsoidFormatHelper::FORMAT_WIKITEXT;
1576
1577 $pageConfig = $handler->tryToCreatePageConfig( $attribs, null, true );
1578 $response = $handler->html2wt( $pageConfig, $attribs, $html );
1579 $body = $response->getBody();
1580 $body->rewind();
1581 $actual = $body->getContents();
1582
1583 // apply some normalization before comparing
1584 $actual = trim( $actual );
1585 $wikitext = trim( $wikitext );
1586
1587 $this->assertSame( $wikitext, $actual );
1588 }
1589
1590 /**
1591 * @dataProvider provideRoundTripNoSelser
1592 */
1593 public function testRoundTripWithPageBundleWithoutOriginalHTML( $wikitext ) {
1594 $handler = $this->newParsoidHandler();
1595
1596 $attribs = self::DEFAULT_ATTRIBS;
1597 $attribs['opts']['from'] = ParsoidFormatHelper::FORMAT_WIKITEXT;
1598 $attribs['opts']['format'] = ParsoidFormatHelper::FORMAT_PAGEBUNDLE;
1599
1600 $pageConfig = $handler->tryToCreatePageConfig( $attribs, $wikitext );
1601 $response = $handler->wt2html( $pageConfig, $attribs, $wikitext );
1602 $body = $response->getBody();
1603 $body->rewind();
1604 $pbJson = $body->getContents();
1605
1606 $pbData = json_decode( $pbJson, JSON_OBJECT_AS_ARRAY );
1607 $html = $pbData['html']['body']; // HTML with data-parsoid stripped out
1608
1609 // Got HTML, now convert back
1610 $attribs = self::DEFAULT_ATTRIBS;
1611 $attribs['opts']['from'] = ParsoidFormatHelper::FORMAT_PAGEBUNDLE;
1612 $attribs['opts']['format'] = ParsoidFormatHelper::FORMAT_WIKITEXT;
1613 $attribs['opts']['original'] = [
1614 'data-parsoid' => $pbData['data-parsoid'],
1615 ];
1616
1617 $pageConfig = $handler->tryToCreatePageConfig( $attribs, null, true );
1618 $response = $handler->html2wt( $pageConfig, $attribs, $html );
1619 $body = $response->getBody();
1620 $body->rewind();
1621 $actual = $body->getContents();
1622
1623 // apply some normalization before comparing
1624 $actual = trim( $actual );
1625 $wikitext = trim( $wikitext );
1626
1627 $this->assertSame( $wikitext, $actual );
1628 }
1629
1630 /**
1631 * @dataProvider provideRoundTripNoSelser
1632 * @dataProvider provideRoundTripNeedingSelser
1633 */
1634 public function testRoundTripWithSelser( $wikitext ) {
1635 $handler = $this->newParsoidHandler();
1636
1637 $attribs = self::DEFAULT_ATTRIBS;
1638 $attribs['opts']['from'] = ParsoidFormatHelper::FORMAT_WIKITEXT;
1639 $attribs['opts']['format'] = ParsoidFormatHelper::FORMAT_PAGEBUNDLE;
1640
1641 $page = $this->getExistingTestPage();
1642 $revid = $page->getLatest();
1643
1644 $pageConfig = $handler->tryToCreatePageConfig( $attribs, $wikitext );
1645 $response = $handler->wt2html( $pageConfig, $attribs, $wikitext );
1646
1647 // NOTE: Make sure there is no ETag if no stashing was requested (T331629)
1648 $etag = $response->getHeaderLine( 'etag' );
1649 $this->assertSame( '', $etag, 'ETag' );
1650
1651 $body = $response->getBody();
1652 $body->rewind();
1653 $pbJson = $body->getContents();
1654
1655 $pbData = json_decode( $pbJson, JSON_OBJECT_AS_ARRAY );
1656 $html = $pbData['html']['body']; // HTML with data-parsoid stripped out
1657
1658 // Got HTML, now convert back
1659 $attribs = self::DEFAULT_ATTRIBS;
1660 $attribs['oldid'] = $revid;
1661 $attribs['opts']['revid'] = $revid;
1662 $attribs['opts']['from'] = ParsoidFormatHelper::FORMAT_PAGEBUNDLE;
1663 $attribs['opts']['format'] = ParsoidFormatHelper::FORMAT_WIKITEXT;
1664 $attribs['opts']['original'] = $pbData;
1665 $attribs['opts']['original']['wikitext']['body'] = $wikitext;
1666
1667 $pageConfig = $handler->tryToCreatePageConfig( $attribs, $wikitext, true );
1668 $response = $handler->html2wt( $pageConfig, $attribs, $html );
1669 $body = $response->getBody();
1670 $body->rewind();
1671 $actual = $body->getContents();
1672
1673 // apply some normalization before comparing
1674 $actual = trim( $actual );
1675 $wikitext = trim( $wikitext );
1676
1677 $this->assertSame( $wikitext, $actual );
1678 }
1679
1680 /**
1681 * @dataProvider provideRoundTripNoSelser
1682 * @dataProvider provideRoundTripNeedingSelser
1683 */
1684 public function testRoundTripWithStashing( $wikitext ) {
1685 $handler = $this->newParsoidHandler();
1686
1687 $attribs = self::DEFAULT_ATTRIBS;
1688 $attribs['opts']['from'] = ParsoidFormatHelper::FORMAT_WIKITEXT;
1689 $attribs['opts']['format'] = ParsoidFormatHelper::FORMAT_HTML;
1690 $attribs['opts']['stash'] = true;
1691
1692 $page = $this->getExistingTestPage();
1693 $revid = $page->getLatest();
1694
1695 $pageConfig = $handler->tryToCreatePageConfig( $attribs, $wikitext );
1696 $response = $handler->wt2html( $pageConfig, $attribs, $wikitext );
1697
1698 $etag = $response->getHeaderLine( 'etag' );
1699 $this->assertNotEmpty( $etag, 'ETag' );
1700
1701 $body = $response->getBody();
1702 $body->rewind();
1703 $html = $body->getContents();
1704
1705 // Got HTML, now convert back
1706 $attribs = self::DEFAULT_ATTRIBS;
1707 $attribs['oldid'] = $revid;
1708 $attribs['opts']['revid'] = $revid;
1709 $attribs['opts']['from'] = ParsoidFormatHelper::FORMAT_PAGEBUNDLE;
1710 $attribs['opts']['format'] = ParsoidFormatHelper::FORMAT_WIKITEXT;
1711 $attribs['opts']['original']['etag'] = $etag;
1712 $attribs['opts']['original']['wikitext'] = $wikitext;
1713
1714 $pageConfig = $handler->tryToCreatePageConfig( $attribs, $wikitext, true );
1715 $response = $handler->html2wt( $pageConfig, $attribs, $html );
1716 $body = $response->getBody();
1717 $body->rewind();
1718 $actual = $body->getContents();
1719
1720 // apply some normalization before comparing
1721 $actual = trim( $actual );
1722 $wikitext = trim( $wikitext );
1723
1724 $this->assertSame( $wikitext, $actual );
1725 }
1726
1727 public function provideLanguageConversion() {
1728 $en = $this->createLanguageMock( 'en' );
1729 $enPigLatin = $this->createLanguageMock( 'en-x-piglatin' );
1730 $profileVersion = Parsoid::AVAILABLE_VERSIONS[0];
1731 $htmlProfileUri = 'https://www.mediawiki.org/wiki/Specs/HTML/' . $profileVersion;
1732 $htmlContentType = "text/html; charset=utf-8; profile=\"$htmlProfileUri\"";
1733
1734 $defaultAttribs = [
1735 'oldid' => null,
1736 'pageName' => __METHOD__,
1737 'opts' => [],
1738 'envOptions' => [
1739 'inputContentVersion' => Parsoid::defaultHTMLVersion()
1740 ]
1741 ];
1742
1743 $attribs = [
1744 'pagelanguage' => $en,
1745 'opts' => [
1746 'updates' => [
1747 'variant' => [
1748 'source' => $en,
1749 'target' => $enPigLatin
1750 ]
1751 ],
1752 ],
1753 ] + $defaultAttribs;
1754
1755 $revision = [
1756 'contentmodel' => CONTENT_MODEL_WIKITEXT,
1757 'html' => [
1758 'headers' => [
1759 'content-type' => $htmlContentType,
1760 ],
1761 'body' => '<p>test language conversion</p>',
1762 ],
1763 ];
1764
1765 yield [
1766 $attribs,
1767 $revision,
1768 '>esttay anguagelay onversioncay<',
1769 [
1770 'content-type' => $htmlContentType,
1771 'content-language' => $enPigLatin->toBcp47Code(),
1772 ]
1773 ];
1774 }
1775
1776 /**
1777 * @dataProvider provideLanguageConversion
1778 */
1779 public function testLanguageConversion(
1780 array $attribs,
1781 array $revision,
1782 string $expectedText,
1783 array $expectedHeaders
1784 ) {
1785 $handler = $this->newParsoidHandler();
1786
1787 $pageConfig = $handler->tryToCreatePageConfig( $attribs, null, true );
1788 $response = $handler->languageConversion( $pageConfig, $attribs, $revision );
1789
1790 $body = $response->getBody();
1791 $body->rewind();
1792 $actual = $body->getContents();
1793
1794 $pb = json_decode( $actual, true );
1795 $this->assertNotEmpty( $pb );
1796 $this->assertArrayHasKey( 'html', $pb );
1797 $this->assertArrayHasKey( 'body', $pb['html'] );
1798
1799 $this->assertStringContainsString( $expectedText, $pb['html']['body'] );
1800
1801 foreach ( $expectedHeaders as $key => $value ) {
1802 $this->assertArrayHasKey( $key, $pb['html']['headers'] );
1803 $this->assertSame( $value, $pb['html']['headers'][$key] );
1804 }
1805 }
1806
1807 public static function provideWt2html() {
1808 $profileVersion = '2.6.0';
1809 $htmlProfileUri = 'https://www.mediawiki.org/wiki/Specs/HTML/' . $profileVersion;
1810 $pbProfileUri = 'https://www.mediawiki.org/wiki/Specs/pagebundle/' . $profileVersion;
1811 $dpProfileUri = 'https://www.mediawiki.org/wiki/Specs/data-parsoid/' . $profileVersion;
1812
1813 $htmlContentType = "text/html; charset=utf-8; profile=\"$htmlProfileUri\"";
1814 $pbContentType = "application/json; charset=utf-8; profile=\"$pbProfileUri\"";
1815 $dpContentType = "application/json; charset=utf-8; profile=\"$dpProfileUri\"";
1816 $lintContentType = "application/json";
1817
1818 $htmlHeaders = [
1819 'content-type' => $htmlContentType,
1820 ];
1821
1822 $pbHeaders = [
1823 'content-type' => $pbContentType,
1824 ];
1825
1826 $lintHeaders = [
1827 'content-type' => $lintContentType,
1828 ];
1829
1830 // should get from a title and revision (html) ///////////////////////////////////
1831 $expectedText = [
1832 '>First Revision Content<',
1833 '<html', // full document
1834 'data-parsoid=' // annotated
1835 ];
1836
1837 $unexpectedText = [];
1838
1839 $attribs = [
1840 'oldid' => 1, // will be replaced by a real revision id
1841 ];
1842 yield 'should get from a title and revision (html)' => [
1843 $attribs,
1844 null,
1845 $expectedText,
1846 $unexpectedText,
1847 $htmlHeaders
1848 ];
1849
1850 // should get from a title and revision (pagebundle) ///////////////////////////////////
1851 $expectedText = [ // bits of json
1852 '"body":"<!DOCTYPE html>',
1853 'First Revision Content</p>',
1854 'contentmodel' => 'wikitext',
1855 'data-parsoid' => [
1856 'headers' => [
1857 'content-type' => $dpContentType,
1858 ],
1859 'body' => [
1860 'counter' => 2,
1861 'ids' => [ // NOTE: match "First Revision Content"
1862 'mwAA' => [ 'dsr' => [ 0, 22, 0, 0 ] ],
1863 'mwAQ' => [],
1864 'mwAg' => [ 'dsr' => [ 0, 22, 0, 0 ] ],
1865 ],
1866 'offsetType' => 'ucs2', // as provided in the input
1867 ]
1868 ],
1869 ];
1870
1871 $unexpectedText = [];
1872
1873 $attribs = [
1874 'oldid' => 1, // will be replaced by a real revision id
1875 'opts' => [ 'format' => ParsoidFormatHelper::FORMAT_PAGEBUNDLE ],
1876 // Ensure this is ucs2 so we have a ucs2 offsetType test since
1877 // Parsoid's rt-testing script is node.js based and hence needs
1878 // ucs2 offsets to function correctly!
1879 'offsetType' => 'ucs2', // make sure this is looped through to data-parsoid attribute
1880 ];
1881 yield 'should get from a title and revision (pagebundle)' => [
1882 $attribs,
1883 null,
1884 $expectedText,
1885 $unexpectedText,
1886 $pbHeaders
1887 ];
1888
1889 // should parse the given wikitext ///////////////////////////////////
1890 $wikitext = 'lorem ipsum';
1891 $expectedText = [
1892 '>lorem ipsum<',
1893 '<html', // full document
1894 'data-parsoid=' // annotated
1895 ];
1896
1897 $unexpectedText = [];
1898
1899 $attribs = [];
1900 yield 'should parse the given wikitext' => [
1901 $attribs,
1902 $wikitext,
1903 $expectedText,
1904 $unexpectedText,
1905 $htmlHeaders
1906 ];
1907
1908 // should parse the given wikitext (body_only) ///////////////////////////////////
1909 $wikitext = 'lorem ipsum';
1910 $expectedText = [ '>lorem ipsum<' ];
1911
1912 $unexpectedText = [ '<html' ];
1913
1914 $attribs = [
1915 'body_only' => true
1916 ];
1917 yield 'should parse the given wikitext (body_only)' => [
1918 $attribs,
1919 $wikitext,
1920 $expectedText,
1921 $unexpectedText,
1922 $htmlHeaders
1923 ];
1924
1925 // should lint the given wikitext ///////////////////////////////////
1926 $wikitext = "{|\nhi\n|ho\n|}";
1927 $expectedText = [
1928 '"type":"fostered"',
1929 '"dsr"'
1930 ];
1931
1932 $unexpectedText = [
1933 '<html'
1934 ];
1935
1936 $attribs = [
1937 'opts' => [ 'format' => ParsoidFormatHelper::FORMAT_LINT ]
1938 ];
1939
1940 yield 'should lint the given wikitext' => [
1941 $attribs,
1942 $wikitext,
1943 $expectedText,
1944 $unexpectedText,
1945 $lintHeaders
1946 ];
1947
1948 // should lint the given wikitext 2 ///////////////////////////////////
1949 $wikitext = "{|\n|wide\n|wide\n|wide\n|wide\n|wide\n|wide\n|}";
1950 if ( ExtensionRegistry::getInstance()->isLoaded( 'Linter' ) ) {
1951 $expectedText = [];
1952 } else {
1953 $expectedText = [
1954 '"type":"large-tables"',
1955 '"dsr"'
1956 ];
1957 }
1958
1959 $unexpectedText = [
1960 '<html'
1961 ];
1962
1963 $attribs = [
1964 'opts' => [ 'format' => ParsoidFormatHelper::FORMAT_LINT ]
1965 ];
1966
1967 yield 'should lint the given wikitext 2' => [
1968 $attribs,
1969 $wikitext,
1970 $expectedText,
1971 $unexpectedText,
1972 $lintHeaders
1973 ];
1974
1975 // should lint the given wikitext 3 ///////////////////////////////////
1976
1977 // Multibyte characters before lint error
1978 $wikitext = "ăăă ''test";
1979
1980 $expectedText = [
1981 '"type":"missing-end-tag"',
1982 // '"dsr":[7,13,2,0]', // 'byte' offsets
1983 '"dsr":[4,10,2,0]', // 'ucs2' offsets
1984 ];
1985
1986 $unexpectedText = [
1987 '<html'
1988 ];
1989
1990 $attribs = [
1991 'opts' => [ 'format' => ParsoidFormatHelper::FORMAT_LINT ],
1992 'offsetType' => 'ucs2',
1993 ];
1994
1995 yield 'should lint the given wikitext 3' => [
1996 $attribs,
1997 $wikitext,
1998 $expectedText,
1999 $unexpectedText,
2000 $lintHeaders
2001 ];
2002
2003 // should parse the given JSON ///////////////////////////////////
2004 $wikitext = '{ "color": "green" }';
2005
2006 // should be rendered as table, not interpreted as wikitext
2007 $expectedText = [
2008 '>color</th>',
2009 '>green</td>',
2010 '<html',
2011 ];
2012
2013 $unexpectedText = [ '<p>' ];
2014
2015 $attribs = [
2016 'opts' => [
2017 'contentmodel' => CONTENT_MODEL_JSON,
2018 ]
2019 ];
2020 yield 'should parse the given JSON' => [
2021 $attribs,
2022 $wikitext,
2023 $expectedText,
2024 $unexpectedText,
2025 $htmlHeaders
2026 ];
2027 }
2028
2029 /**
2030 * @dataProvider provideWt2html
2031 *
2032 * @param array $attribs
2033 * @param string|null $text
2034 * @param array $expectedData
2035 * @param string[] $unexpectedHtml
2036 * @param string[] $expectedHeaders
2037 */
2038 public function testWt2html(
2039 array $attribs,
2040 ?string $text,
2041 array $expectedData,
2042 array $unexpectedHtml,
2043 array $expectedHeaders = []
2044 ) {
2045 $htmlProfileUri = 'https://www.mediawiki.org/wiki/Specs/html/2.6.0';
2046 $expectedHeaders += [
2047 'content-type' => "text/x-wiki; charset=utf-8; profile=\"$htmlProfileUri\"",
2048 ];
2049
2050 $page = $this->getNonexistingTestPage( __METHOD__ );
2051 $status = $this->editPage( $page, 'First Revision Content' );
2052 $currentRev = $status->getNewRevision();
2053
2054 $attribs += self::DEFAULT_ATTRIBS;
2055 $attribs['opts'] += self::DEFAULT_ATTRIBS['opts'];
2056 $attribs['opts']['from'] ??= 'wikitext';
2057 $attribs['opts']['format'] ??= 'html';
2058 $attribs['envOptions'] += self::DEFAULT_ATTRIBS['envOptions'];
2059
2060 if ( $attribs['oldid'] ) {
2061 // Set the actual ID of an existing revision
2062 $attribs['oldid'] = $currentRev->getId();
2063
2064 // Make sure we are testing against a non-current revision
2065 $this->editPage( $page, 'this is not the content you are looking for' );
2066 }
2067
2068 $handler = $this->newParsoidHandler();
2069
2070 $revTextOrId = $text ?? $attribs['oldid'] ?? null;
2071 $pageConfig = $this->getPageConfig( $page, $revTextOrId );
2072 $response = $handler->wt2html( $pageConfig, $attribs, $text );
2073 $body = $response->getBody();
2074 $body->rewind();
2075 $data = $body->getContents();
2076
2077 foreach ( $expectedHeaders as $name => $value ) {
2078 $responseHeaderValue = $response->getHeaderLine( $name );
2079 if ( $name === 'content-type' ) {
2080 $this->assertTrue( $this->contentTypeMatcher( $value, $responseHeaderValue ) );
2081 } else {
2082 $this->assertSame( $value, $responseHeaderValue );
2083 }
2084 }
2085
2086 // HACK: try to parse as json, just in case:
2087 $jsonData = json_decode( $data, JSON_OBJECT_AS_ARRAY );
2088
2089 foreach ( $expectedData as $index => $exp ) {
2090 if ( is_int( $index ) ) {
2091 $this->assertStringContainsString( $exp, $data );
2092 } else {
2093 $this->assertArrayHasKey( $index, $jsonData );
2094 if ( $index === 'data-parsoid' ) {
2095 // FIXME: Assert headers as well
2096 $this->assertArrayHasKey( 'body', $jsonData[$index] );
2097 $this->assertSame( $exp['body'], $jsonData[$index]['body'] );
2098 } else {
2099 $this->assertSame( $exp, $jsonData[$index] );
2100 }
2101 }
2102 }
2103
2104 foreach ( $unexpectedHtml as $exp ) {
2105 $this->assertStringNotContainsString( $exp, $data );
2106 }
2107 }
2108
2109 public function testLenientRevisionHandling() {
2110 $page1 = $this->getNonexistingTestPage( "Page1" );
2111 $status = $this->editPage( $page1, 'Page 1 revision content' );
2112 $rev1 = $status->getNewRevision();
2113
2114 $page2 = $this->getNonexistingTestPage( "Page2" );
2115 $status = $this->editPage( $page2, '#REDIRECT [[Page1]]' );
2116 $rev2 = $status->getNewRevision();
2117
2118 $handler = $this->newParsoidHandler();
2119
2120 // Test 1: <page1, rev1>
2121 $attribs = self::DEFAULT_ATTRIBS;
2122 $attribs['opts'] += self::DEFAULT_ATTRIBS['opts'];
2123 $attribs['opts']['from'] ??= 'wikitext';
2124 $attribs['opts']['format'] ??= 'html';
2125 $attribs['envOptions'] += self::DEFAULT_ATTRIBS['envOptions'];
2126 $attribs['oldid'] = $rev1->getId();
2127
2128 $pageConfig = $this->getPageConfig( $page1, $attribs['oldid'] );
2129 $response = $handler->wt2html( $pageConfig, $attribs );
2130 $body = $response->getBody();
2131 $body->rewind();
2132 $data = $body->getContents();
2133 $this->assertStringContainsString( 'Page 1 revision content', $data );
2134
2135 // Test 2: <page2, rev2>
2136 $attribs['oldid'] = $rev2->getId();
2137 $pageConfig = $this->getPageConfig( $page2, $attribs['oldid'] );
2138 $response = $handler->wt2html( $pageConfig, $attribs );
2139 $body = $response->getBody();
2140 $body->rewind();
2141 $data = $body->getContents();
2142 $this->assertStringContainsString( '<link rel="mw:PageProp/redirect" ', $data );
2143
2144 // Test 2: <page2, rev1> <-- should transparently redirect
2145 $attribs['oldid'] = $rev1->getId();
2146 $pageConfig = $this->getPageConfig( $page2, $attribs['oldid'] );
2147 $response = $handler->wt2html( $pageConfig, $attribs );
2148 $body = $response->getBody();
2149 $body->rewind();
2150 $data = $body->getContents();
2151 $this->assertStringContainsString( 'Page 1 revision content', $data );
2152
2153 // Test 3 repeated with ParserCache to ensure nothing is written to cache!
2154 $parserCache = $this->createNoOpMock( ParserCache::class, [ 'save', 'get', 'getDirty', 'makeParserOutputKey' ] );
2155 // This is the critical assertion -- no cache svaes for mismatched rev & page params
2156 $parserCache->expects( $this->never() )->method( 'save' );
2157 // Ensures there is a cache miss
2158 $parserCache->method( 'get' )->willReturn( false );
2159 $parserCache->method( 'getDirty' )->willReturn( false );
2160 // Verify that the cache is queried
2161 $parserCache->expects( $this->atLeastOnce() )->method( 'makeParserOutputKey' );
2162 $parserCacheFactory = $this->createNoOpMock(
2163 ParserCacheFactory::class,
2164 [ 'getParserCache', 'getRevisionOutputCache' ]
2165 );
2166 $parserCacheFactory->method( 'getParserCache' )->willReturn( $parserCache );
2167 $parserCacheFactory->method( 'getRevisionOutputCache' )->willReturn(
2168 $this->createNoOpMock( RevisionOutputCache::class )
2169 );
2170 $this->setService( 'ParserCacheFactory', $parserCacheFactory );
2171 $handler = $this->newParsoidHandler();
2172 $handler->wt2html( $pageConfig, $attribs ); // Reuse pageconfig & attribs from test 3
2173 }
2174
2175 public function testWt2html_ParserCache() {
2176 $page = $this->getExistingTestPage();
2177 $pageConfig = $this->getPageConfig( $page );
2178
2179 $parserCache = $this->createNoOpMock( ParserCache::class, [ 'save', 'get', 'getDirty', 'makeParserOutputKey' ] );
2180
2181 // This is the critical assertion in this test case: the save() method should
2182 // be called exactly once!
2183 $parserCache->expects( $this->once() )->method( 'save' );
2184 $parserCache->method( 'get' )->willReturn( false );
2185 $parserCache->method( 'getDirty' )->willReturn( false );
2186 // These methods will be called by ParserOutputAccess:qa
2187 $parserCache->expects( $this->atLeastOnce() )->method( 'makeParserOutputKey' );
2188
2189 $parserCacheFactory = $this->createNoOpMock(
2190 ParserCacheFactory::class,
2191 [ 'getParserCache', 'getRevisionOutputCache' ]
2192 );
2193 $parserCacheFactory->method( 'getParserCache' )->willReturn( $parserCache );
2194 $parserCacheFactory->method( 'getRevisionOutputCache' )->willReturn(
2195 $this->createNoOpMock( RevisionOutputCache::class )
2196 );
2197
2198 $this->setService( 'ParserCacheFactory', $parserCacheFactory );
2199
2200 $attribs = self::DEFAULT_ATTRIBS;
2201 $attribs['opts']['from'] = 'wikitext';
2202 $attribs['opts']['format'] = 'html';
2203
2204 $handler = $this->newParsoidHandler();
2205
2206 // This should trigger a parser cache write, because we didn't set a write-ratio
2207 $handler->wt2html( $pageConfig, $attribs );
2208 }
2209
2210 public function testWt2html_variant_conversion() {
2211 $page = $this->getExistingTestPage();
2212 $pageConfig = $this->getPageConfig( $page );
2213
2214 $attribs = self::DEFAULT_ATTRIBS;
2215 $attribs['opts']['from'] = 'wikitext';
2216 $attribs['opts']['format'] = 'html';
2217 $attribs['opts']['accept-language'] = 'en-x-piglatin';
2218
2219 $handler = $this->newParsoidHandler();
2220
2221 // This should trigger a parser cache write, because we didn't set a write-ratio
2222 $response = $handler->wt2html( $pageConfig, $attribs );
2223
2224 $body = $response->getBody();
2225 $body->rewind();
2226 $data = $body->getContents();
2227
2228 $this->assertStringContainsString(
2229 '<meta http-equiv="content-language" content="en-x-piglatin"/>',
2230 $data
2231 );
2232 }
2233
2234 public function testWt2html_NonParsoidContentModel() {
2235 $page = $this->getNonexistingTestPage( __METHOD__ );
2236 $this->editPage( $page, new JavaScriptContent( '"not wikitext"' ) );
2237 $pageConfig = $this->getPageConfig( $page );
2238
2239 $attribs = self::DEFAULT_ATTRIBS;
2240 $attribs['opts']['from'] = 'wikitext';
2241 // Asking for a 'pagebundle' here because of T325137.
2242 $attribs['opts']['format'] = 'pagebundle';
2243
2244 $handler = $this->newParsoidHandler();
2245 $response = $handler->wt2html( $pageConfig, $attribs );
2246
2247 $this->assertSame( 200, $response->getStatusCode() );
2248
2249 $body = $response->getBody();
2250 $body->rewind();
2251 $data = $body->getContents();
2252
2253 $jsonData = json_decode( $data, JSON_OBJECT_AS_ARRAY );
2254
2255 $this->assertIsArray( $jsonData );
2256 $this->assertStringContainsString( "not wikitext", $jsonData['html']['body'] );
2257 }
2258
2259 // TODO: test wt2html failure modes
2260 // TODO: test redlinks
2261
2262 public function createLanguageMock( string $code ) {
2263 // Ensure that we always return the same object for a given code.
2264 static $seen = [];
2265 if ( !isset( $seen[$code] ) ) {
2266 $langMock = $this->createMock( Language::class );
2267 $langMock
2268 ->method( 'getCode' )
2269 ->willReturn( $code );
2270 $bcp47 = LanguageCode::bcp47( $code );
2271 $langMock
2272 ->method( 'getHtmlCode' )
2273 ->willReturn( $bcp47 );
2274 $langMock
2275 ->method( 'toBcp47Code' )
2276 ->willReturn( $bcp47 );
2277 $langMock
2278 ->method( 'getDir' )
2279 ->willReturn( 'ltr' );
2280 $seen[$code] = $langMock;
2281 }
2282 return $seen[$code];
2283 }
2284
2285 }