getDefaultWikitextNS(); $title = Title::newFromText( $title, $ns ); } return new WikiPage( $title ); } /** * @param string|Title|WikiPage $page * @param string|Content|Content[] $content * @param int|null $model * @param Authority|null $performer * * @return WikiPage */ protected function createPage( $page, $content, $model = null, ?Authority $performer = null ) { if ( is_string( $page ) || $page instanceof Title ) { $page = $this->newPage( $page, $model ); } $performer ??= $this->getTestUser()->getUser(); if ( is_string( $content ) ) { $content = ContentHandler::makeContent( $content, $page->getTitle(), $model ); } if ( !is_array( $content ) ) { $content = [ SlotRecord::MAIN => $content ]; } $updater = $page->newPageUpdater( $performer ); foreach ( $content as $role => $cnt ) { $updater->setContent( $role, $cnt ); } $updater->saveRevision( CommentStoreComment::newUnsavedComment( "testing" ) ); if ( !$updater->wasSuccessful() ) { $this->fail( $updater->getStatus()->getWikiText() ); } return $page; } public function testSerialization_fails() { $this->expectException( LogicException::class ); $page = $this->createPage( __METHOD__, __METHOD__ ); serialize( $page ); } public static function provideTitlesThatCannotExist() { yield 'Special' => [ NS_SPECIAL, 'Recentchanges' ]; // existing special page yield 'Invalid character' => [ NS_MAIN, '#' ]; // bad character } /** * @dataProvider provideTitlesThatCannotExist */ public function testConstructionWithPageThatCannotExist( $ns, $text ) { $title = Title::makeTitle( $ns, $text ); $this->expectException( InvalidArgumentException::class ); new WikiPage( $title ); } public function testPrepareContentForEdit() { $performer = $this->mockUserAuthorityWithPermissions( $this->getTestUser()->getUserIdentity(), [ 'edit' ] ); $sysop = $this->getTestUser( [ 'sysop' ] )->getUserIdentity(); $page = $this->createPage( __METHOD__, __METHOD__, null, $performer ); $title = $page->getTitle(); $content = ContentHandler::makeContent( "[[Lorem ipsum]] dolor sit amet, consetetur sadipscing elitr, sed diam " . " nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat.", $title, CONTENT_MODEL_WIKITEXT ); $content2 = ContentHandler::makeContent( "At vero eos et accusam et justo duo [[dolores]] et ea rebum. " . "Stet clita kasd [[gubergren]], no sea takimata sanctus est. ~~~~", $title, CONTENT_MODEL_WIKITEXT ); $edit = $page->prepareContentForEdit( $content, null, $performer->getUser(), null, false ); $this->assertInstanceOf( ParserOptions::class, $edit->popts, "pops" ); $this->assertStringContainsString( '', $edit->output->getRawText(), "output" ); $this->assertStringContainsString( 'consetetur sadipscing elitr', $edit->output->getRawText(), "output" ); $this->assertTrue( $content->equals( $edit->newContent ), "newContent field" ); $this->assertTrue( $content->equals( $edit->pstContent ), "pstContent field" ); $this->assertSame( $edit->output, $edit->output, "output field" ); $this->assertSame( $edit->popts, $edit->popts, "popts field" ); $this->assertSame( null, $edit->revid, "revid field" ); // PreparedUpdate matches PreparedEdit $update = $page->getCurrentUpdate(); $this->assertSame( $edit->output, $update->getCanonicalParserOutput() ); // Re-using the prepared info if possible $sameEdit = $page->prepareContentForEdit( $content, null, $performer->getUser(), null, false ); $this->assertPreparedEditEquals( $edit, $sameEdit, 'equivalent PreparedEdit' ); $this->assertSame( $edit->pstContent, $sameEdit->pstContent, 're-use output' ); $this->assertSame( $edit->output, $sameEdit->output, 're-use output' ); // re-using the same PreparedUpdate $this->assertSame( $update, $page->getCurrentUpdate() ); // Not re-using the same PreparedEdit if not possible $edit2 = $page->prepareContentForEdit( $content2, null, $performer->getUser(), null, false ); $this->assertPreparedEditNotEquals( $edit, $edit2 ); $this->assertStringContainsString( 'At vero eos', $edit2->pstContent->serialize(), "content" ); // Not re-using the same PreparedUpdate $this->assertNotSame( $update, $page->getCurrentUpdate() ); // Check pre-safe transform $this->assertStringContainsString( '[[gubergren]]', $edit2->pstContent->serialize() ); $this->assertStringNotContainsString( '~~~~', $edit2->pstContent->serialize() ); $edit3 = $page->prepareContentForEdit( $content2, null, $sysop, null, false ); $this->assertPreparedEditNotEquals( $edit2, $edit3 ); // TODO: test with passing revision, then same without revision. } public function testDoEditUpdates() { $user = $this->getTestUser()->getUserIdentity(); // NOTE: if site stats get out of whack and drop below 0, // that causes a DB error during tear-down. So bump the // numbers high enough to not drop below 0. $siteStatsUpdate = SiteStatsUpdate::factory( [ 'edits' => 1000, 'articles' => 1000, 'pages' => 1000 ] ); $siteStatsUpdate->doUpdate(); $page = $this->createPage( __METHOD__, __METHOD__ ); $comment = CommentStoreComment::newUnsavedComment( __METHOD__ ); // PST turns [[|foo]] into [[foo]] $content = $this->getServiceContainer() ->getContentHandlerFactory() ->getContentHandler( CONTENT_MODEL_WIKITEXT ) ->unserializeContent( __METHOD__ . ' [[|foo]][[bar]]' ); $revRecord = new MutableRevisionRecord( $page->getTitle() ); $revRecord->setContent( SlotRecord::MAIN, $content ); $revRecord->setUser( $user ); $revRecord->setTimestamp( '20170707040404' ); $revRecord->setPageId( $page->getId() ); $revRecord->setId( 9989 ); $revRecord->setMinorEdit( true ); $revRecord->setComment( $comment ); $page->doEditUpdates( $revRecord, $user ); // TODO: test various options; needs temporary hooks $res = $this->getDb()->newSelectQueryBuilder() ->select( '*' ) ->from( 'pagelinks' ) ->where( [ 'pl_from' => $page->getId() ] ) ->fetchResultSet(); $n = $res->numRows(); $res->free(); $this->assertSame( 1, $n, 'pagelinks should contain only one link if PST was not applied' ); } public function testDoUserEditContent() { $this->overrideConfigValue( MainConfigNames::PageCreationLog, true ); $page = $this->newPage( __METHOD__ ); $title = $page->getTitle(); $user1 = $this->getTestUser()->getUser(); // Use the confirmed group for user2 to make sure the user is different $user2 = $this->getTestUser( [ 'confirmed' ] )->getUser(); $content = ContentHandler::makeContent( "[[Lorem ipsum]] dolor sit amet, consetetur sadipscing elitr, sed diam " . " nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat.", $title, CONTENT_MODEL_WIKITEXT ); $preparedEditBefore = $page->prepareContentForEdit( $content, null, $user1 ); $status = $page->doUserEditContent( $content, $user1, "[[testing]] 1", EDIT_NEW ); $this->assertStatusGood( $status ); $this->assertTrue( $status->value['new'], 'new' ); $this->assertNotNull( $status->getNewRevision(), 'revision-record' ); $statusRevRecord = $status->getNewRevision(); $this->assertSame( $statusRevRecord->getId(), $page->getRevisionRecord()->getId() ); $this->assertSame( $statusRevRecord->getSha1(), $page->getRevisionRecord()->getSha1() ); $this->assertTrue( $statusRevRecord->getContent( SlotRecord::MAIN )->equals( $content ), 'equals' ); $revRecord = $page->getRevisionRecord(); $recentChange = $this->getServiceContainer() ->getRevisionStore() ->getRecentChange( $revRecord ); $preparedEditAfter = $page->prepareContentForEdit( $content, $revRecord, $user1 ); $this->assertNotNull( $recentChange ); $this->assertSame( $revRecord->getId(), (int)$recentChange->getAttribute( 'rc_this_oldid' ) ); // make sure that cached ParserOutput gets re-used throughout $this->assertSame( $preparedEditBefore->output, $preparedEditAfter->output ); $id = $page->getId(); // Test page creation logging $this->newSelectQueryBuilder() ->select( [ 'log_type', 'log_action' ] ) ->from( 'logging' ) ->where( [ 'log_page' => $id ] ) ->assertResultSet( [ [ 'create', 'create' ] ] ); $this->assertGreaterThan( 0, $title->getArticleID(), "Title object should have new page id" ); $this->assertGreaterThan( 0, $id, "WikiPage should have new page id" ); $this->assertTrue( $title->exists(), "Title object should indicate that the page now exists" ); $this->assertTrue( $page->exists(), "WikiPage object should indicate that the page now exists" ); # ------------------------ $res = $this->getDb()->newSelectQueryBuilder() ->select( '*' ) ->from( 'pagelinks' ) ->where( [ 'pl_from' => $id ] ) ->fetchResultSet(); $n = $res->numRows(); $res->free(); $this->assertSame( 1, $n, 'pagelinks should contain one link from the page' ); # ------------------------ $page = new WikiPage( $title ); $retrieved = $page->getContent(); $this->assertTrue( $content->equals( $retrieved ), 'retrieved content doesn\'t equal original' ); # ------------------------ $page = new WikiPage( $title ); // try null edit, with a different user $status = $page->doUserEditContent( $content, $user2, 'This changes nothing', EDIT_UPDATE, false ); $this->assertStatusWarning( 'edit-no-change', $status ); $this->assertFalse( $status->value['new'], 'new' ); $this->assertNull( $status->getNewRevision(), 'revision-record' ); $this->assertNotNull( $page->getRevisionRecord() ); $this->assertTrue( $page->getRevisionRecord()->getContent( SlotRecord::MAIN )->equals( $content ), 'equals' ); # ------------------------ $content = ContentHandler::makeContent( "At vero eos et accusam et justo duo [[dolores]] et ea rebum. " . "Stet clita kasd [[gubergren]], no sea takimata sanctus est. ~~~~", $title, CONTENT_MODEL_WIKITEXT ); $status = $page->doUserEditContent( $content, $user1, "testing 2", EDIT_UPDATE ); $this->assertStatusGood( $status ); $this->assertFalse( $status->value['new'], 'new' ); $this->assertNotNull( $status->getNewRevision(), 'revision-record' ); $statusRevRecord = $status->getNewRevision(); $this->assertSame( $statusRevRecord->getId(), $page->getRevisionRecord()->getId() ); $this->assertSame( $statusRevRecord->getSha1(), $page->getRevisionRecord()->getSha1() ); $this->assertFalse( $statusRevRecord->getContent( SlotRecord::MAIN )->equals( $content ), 'not equals (PST must substitute signature)' ); $revRecord = $page->getRevisionRecord(); $recentChange = $this->getServiceContainer() ->getRevisionStore() ->getRecentChange( $revRecord ); $this->assertNotNull( $recentChange ); $this->assertSame( $revRecord->getId(), (int)$recentChange->getAttribute( 'rc_this_oldid' ) ); # ------------------------ $page = new WikiPage( $title ); $retrieved = $page->getContent(); $newText = $retrieved->serialize(); $this->assertStringContainsString( '[[gubergren]]', $newText, 'New text must replace old text.' ); $this->assertStringNotContainsString( '~~~~', $newText, 'PST must substitute signature.' ); # ------------------------ $res = $this->getDb()->newSelectQueryBuilder() ->select( '*' ) ->from( 'pagelinks' ) ->where( [ 'pl_from' => $id ] ) ->fetchResultSet(); $n = $res->numRows(); $res->free(); // two in page text and two in signature $this->assertEquals( 4, $n, 'pagelinks should contain four links from the page' ); } public static function provideNonPageTitle() { yield 'bad case and char' => [ Title::makeTitle( NS_MAIN, 'lower case and bad # char' ) ]; yield 'empty' => [ Title::makeTitle( NS_MAIN, '' ) ]; yield 'special' => [ Title::makeTitle( NS_SPECIAL, 'Dummy' ) ]; yield 'relative' => [ Title::makeTitle( NS_MAIN, '', '#section' ) ]; yield 'interwiki' => [ Title::makeTitle( NS_MAIN, 'Foo', '', 'acme' ) ]; } /** * @dataProvider provideNonPageTitle */ public function testDoUserEditContent_bad_page( $title ) { $user1 = $this->getTestUser()->getUser(); $content = ContentHandler::makeContent( "Yadda yadda", $title, CONTENT_MODEL_WIKITEXT ); $this->filterDeprecated( '/WikiPage constructed on a Title that cannot exist as a page/' ); try { $page = $this->newPage( $title ); $page->doUserEditContent( $content, $user1, "[[testing]] 1", EDIT_NEW ); } catch ( Exception $ex ) { // Throwing is an acceptable way to react to an invalid title, // as long as no garbage is written to the database. } $row = $this->getDb()->newSelectQueryBuilder() ->select( '*' ) ->from( 'page' ) ->where( [ 'page_namespace' => $title->getNamespace(), 'page_title' => $title->getDBkey() ] ) ->fetchRow(); $this->assertFalse( $row ); } public function testDoUserEditContent_twice() { $title = Title::newFromText( __METHOD__ ); $page = $this->getServiceContainer()->getWikiPageFactory()->newFromTitle( $title ); $content = ContentHandler::makeContent( '$1 van $2', $title ); $user = $this->getTestUser()->getUser(); // Make sure we can do the exact same save twice. // This tests checks that internal caches are reset as appropriate. $status1 = $page->doUserEditContent( $content, $user, __METHOD__ ); $status2 = $page->doUserEditContent( $content, $user, __METHOD__ ); $this->assertStatusGood( $status1 ); $this->assertStatusWarning( 'edit-no-change', $status2 ); $this->assertNotNull( $status1->getNewRevision(), 'OK' ); $this->assertNull( $status2->getNewRevision(), 'OK' ); } /** * Undeletion is covered in PageArchiveTest::testUndeleteRevisions() * * TODO: Revision deletion */ public function testDoDeleteArticleReal() { $this->overrideConfigValues( [ MainConfigNames::RCWatchCategoryMembership => false, ] ); $page = $this->createPage( __METHOD__, "[[original text]] foo", CONTENT_MODEL_WIKITEXT ); $id = $page->getId(); $user = $this->getTestSysop()->getUser(); $reason = "testing deletion"; $status = $page->doDeleteArticleReal( $reason, $user ); $this->assertFalse( $page->getTitle()->getArticleID() > 0, "Title object should now have page id 0" ); $this->assertSame( 0, $page->getId(), "WikiPage should now have page id 0" ); $this->assertFalse( $page->exists(), "WikiPage::exists should return false after page was deleted" ); $this->assertNull( $page->getContent(), "WikiPage::getContent should return null after page was deleted" ); $t = Title::newFromText( $page->getTitle()->getPrefixedText() ); $this->assertFalse( $t->exists(), "Title::exists should return false after page was deleted" ); // Run the job queue $this->runJobs(); # ------------------------ $res = $this->getDb()->newSelectQueryBuilder() ->select( '*' ) ->from( 'pagelinks' ) ->where( [ 'pl_from' => $id ] ) ->fetchResultSet(); $n = $res->numRows(); $res->free(); $this->assertSame( 0, $n, 'pagelinks should contain no more links from the page' ); // Test deletion logging $logId = $status->getValue(); $commentQuery = $this->getServiceContainer()->getCommentStore()->getJoin( 'log_comment' ); $this->newSelectQueryBuilder() ->select( [ 'log_type', 'log_action', 'log_comment' => $commentQuery['fields']['log_comment_text'], 'log_actor', 'log_namespace', 'log_title', ] ) ->from( 'logging' ) ->tables( $commentQuery['tables'] ) ->where( [ 'log_id' => $logId ] ) ->joinConds( $commentQuery['joins'] ) ->assertRowValue( [ 'delete', 'delete', $reason, (string)$user->getActorId(), (string)$page->getTitle()->getNamespace(), $page->getTitle()->getDBkey(), ] ); } /** * TODO: Test more stuff about suppression. */ public function testDoDeleteArticleReal_suppress() { $page = $this->createPage( __METHOD__, "[[original text]] foo", CONTENT_MODEL_WIKITEXT ); $user = $this->getTestSysop()->getUser(); $status = $page->doDeleteArticleReal( /* reason */ "testing deletion", $user, /* suppress */ true ); // Test suppression logging $logId = $status->getValue(); $commentQuery = $this->getServiceContainer()->getCommentStore()->getJoin( 'log_comment' ); $this->newSelectQueryBuilder() ->select( [ 'log_type', 'log_action', 'log_comment' => $commentQuery['fields']['log_comment_text'], 'log_actor', 'log_namespace', 'log_title', ] ) ->from( 'logging' ) ->tables( $commentQuery['tables'] ) ->where( [ 'log_id' => $logId ] ) ->joinConds( $commentQuery['joins'] ) ->assertRowValue( [ 'suppress', 'delete', 'testing deletion', (string)$user->getActorId(), (string)$page->getTitle()->getNamespace(), $page->getTitle()->getDBkey(), ] ); $lookup = $this->getServiceContainer()->getArchivedRevisionLookup(); $archivedRevs = $lookup->listRevisions( $page->getTitle() ); if ( !$archivedRevs || $archivedRevs->numRows() !== 1 ) { $this->fail( 'Unexpected number of archived revisions' ); } $archivedRev = $this->getServiceContainer()->getRevisionStore() ->newRevisionFromArchiveRow( $archivedRevs->current() ); $this->assertNull( $archivedRev->getContent( SlotRecord::MAIN, RevisionRecord::FOR_PUBLIC ), "Archived content should be null after the page was suppressed for general users" ); $this->assertNull( $archivedRev->getContent( SlotRecord::MAIN, RevisionRecord::FOR_THIS_USER, $this->getTestUser()->getUser() ), "Archived content should be null after the page was suppressed for individual users" ); $this->hideDeprecated( 'ContentHandler::getSlotDiffRendererInternal' ); $this->assertNull( $archivedRev->getContent( SlotRecord::MAIN, RevisionRecord::FOR_THIS_USER, $user ), "Archived content should be null after the page was suppressed even for a sysop" ); } public function testGetContent() { $page = $this->newPage( __METHOD__ ); $content = $page->getContent(); $this->assertNull( $content ); $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT ); $content = $page->getContent(); $this->assertEquals( "some text", $content->getText() ); } public function testExists() { $page = $this->newPage( __METHOD__ ); $this->assertFalse( $page->exists() ); $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT ); $this->assertTrue( $page->exists() ); $page = new WikiPage( $page->getTitle() ); $this->assertTrue( $page->exists() ); $this->deletePage( $page, "done testing" ); $this->assertFalse( $page->exists() ); $page = new WikiPage( $page->getTitle() ); $this->assertFalse( $page->exists() ); } public static function provideHasViewableContent() { return [ [ 'WikiPageTest_testHasViewableContent', false, true ], [ 'MediaWiki:WikiPageTest_testHasViewableContent', false ], [ 'MediaWiki:help', true ], ]; } /** * @dataProvider provideHasViewableContent */ public function testHasViewableContent( $title, $viewable, $create = false ) { $page = $this->newPage( $title ); $this->assertEquals( $viewable, $page->hasViewableContent() ); if ( $create ) { $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT ); $this->assertTrue( $page->hasViewableContent() ); $page = new WikiPage( $page->getTitle() ); $this->assertTrue( $page->hasViewableContent() ); } } public static function provideGetRedirectTarget() { return [ [ 'WikiPageTest_testGetRedirectTarget_1', CONTENT_MODEL_WIKITEXT, "hello world", null ], [ 'WikiPageTest_testGetRedirectTarget_2', CONTENT_MODEL_WIKITEXT, "#REDIRECT [[hello world]]", "Hello world" ], // The below added to protect against Media namespace // redirects which throw a fatal: (T203942) [ 'WikiPageTest_testGetRedirectTarget_3', CONTENT_MODEL_WIKITEXT, "#REDIRECT [[Media:hello_world]]", "File:Hello world" ], // Test fragments longer than 255 bytes (T207876) [ 'WikiPageTest_testGetRedirectTarget_4', CONTENT_MODEL_WIKITEXT, '#REDIRECT [[Foobar#🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴]]', 'Foobar#🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴🏴' ] ]; } /** * @dataProvider provideGetRedirectTarget * @covers \WikiPage * @covers \MediaWiki\Page\RedirectStore */ public function testGetRedirectTarget( $title, $model, $text, $target ) { $this->overrideConfigValues( [ MainConfigNames::CapitalLinks => true, // The file redirect can trigger http request with UseInstantCommons = true MainConfigNames::ForeignFileRepos => [], ] ); $titleFormatter = $this->getServiceContainer()->getTitleFormatter(); $page = $this->createPage( $title, $text, $model ); # double check, because this test seems to fail for no reason for some people. $c = $page->getContent(); $this->assertEquals( WikitextContent::class, get_class( $c ) ); # now, test the actual redirect $redirectStore = $this->getServiceContainer()->getRedirectStore(); $t = $redirectStore->getRedirectTarget( $page ); $this->assertEquals( $target, $t ? $titleFormatter->getFullText( $t ) : null ); } /** * @dataProvider provideGetRedirectTarget */ public function testIsRedirect( $title, $model, $text, $target ) { // The file redirect can trigger http request with UseInstantCommons = true $this->overrideConfigValue( MainConfigNames::ForeignFileRepos, [] ); $page = $this->createPage( $title, $text, $model ); $this->assertEquals( $target !== null, $page->isRedirect() ); } public static function provideIsCountable() { return [ // any [ 'WikiPageTest_testIsCountable', CONTENT_MODEL_WIKITEXT, '', 'any', true ], [ 'WikiPageTest_testIsCountable', CONTENT_MODEL_WIKITEXT, 'Foo', 'any', true ], // link [ 'WikiPageTest_testIsCountable', CONTENT_MODEL_WIKITEXT, 'Foo', 'link', false ], [ 'WikiPageTest_testIsCountable', CONTENT_MODEL_WIKITEXT, 'Foo [[bar]]', 'link', true ], // redirects [ 'WikiPageTest_testIsCountable', CONTENT_MODEL_WIKITEXT, '#REDIRECT [[bar]]', 'any', false ], [ 'WikiPageTest_testIsCountable', CONTENT_MODEL_WIKITEXT, '#REDIRECT [[bar]]', 'link', false ], // not a content namespace [ 'Talk:WikiPageTest_testIsCountable', CONTENT_MODEL_WIKITEXT, 'Foo', 'any', false ], [ 'Talk:WikiPageTest_testIsCountable', CONTENT_MODEL_WIKITEXT, 'Foo [[bar]]', 'link', false ], // not a content namespace, different model [ 'MediaWiki:WikiPageTest_testIsCountable.js', null, 'Foo', 'any', false ], [ 'MediaWiki:WikiPageTest_testIsCountable.js', null, 'Foo [[bar]]', 'link', false ], ]; } /** * @dataProvider provideIsCountable */ public function testIsCountable( $title, $model, $text, $mode, $expected ) { $this->overrideConfigValue( MainConfigNames::ArticleCountMethod, $mode ); $title = Title::newFromText( $title ); $page = $this->createPage( $title, $text, $model ); $editInfo = $page->prepareContentForEdit( $page->getContent(), null, $this->getTestUser()->getUser() ); $v = $page->isCountable(); $w = $page->isCountable( $editInfo ); $this->assertEquals( $expected, $v, "isCountable( null ) returned unexpected value " . var_export( $v, true ) . " instead of " . var_export( $expected, true ) . " in mode `$mode` for text \"$text\"" ); $this->assertEquals( $expected, $w, "isCountable( \$editInfo ) returned unexpected value " . var_export( $v, true ) . " instead of " . var_export( $expected, true ) . " in mode `$mode` for text \"$text\"" ); } /** * @dataProvider provideMakeParserOptions */ public function testMakeParserOptions( int $ns, string $title, string $model, $context, callable $expectation ) { // Ensure we're working with the default values during this test. $this->overrideConfigValues( [ MainConfigNames::TextModelsToParse => [ CONTENT_MODEL_WIKITEXT, CONTENT_MODEL_JAVASCRIPT, CONTENT_MODEL_CSS, ], MainConfigNames::DisableLangConversion => false, ] ); // Call the context function first, which lets us setup the // overall wiki context before invoking the function-under-test if ( is_callable( $context ) ) { $context = $context( $this ); } $page = $this->createPage( Title::makeTitle( $ns, $title ), __METHOD__, $model ); $parserOptions = $page->makeParserOptions( $context ); $expected = $expectation(); $this->assertTrue( $expected->matches( $parserOptions ) ); } /** * @dataProvider provideMakeParserOptions */ public function testMakeParserOptionsFromTitleAndModel( int $ns, string $title, string $model, $context, callable $expectation ) { // Ensure we're working with the default values during this test. $this->overrideConfigValues( [ MainConfigNames::TextModelsToParse => [ CONTENT_MODEL_WIKITEXT, CONTENT_MODEL_JAVASCRIPT, CONTENT_MODEL_CSS, ], MainConfigNames::DisableLangConversion => false, ] ); // Call the context function first, which lets us setup the // overall wiki context before invoking the function-under-test if ( is_callable( $context ) ) { $context = $context( $this ); } $parserOptions = WikiPage::makeParserOptionsFromTitleAndModel( Title::makeTitle( $ns, $title ), $model, $context ); $expected = $expectation(); $this->assertTrue( $expected->matches( $parserOptions ) ); } public static function provideMakeParserOptions() { // Default canonical parser options for a normal wikitext page yield [ NS_MAIN, 'Main Page', CONTENT_MODEL_WIKITEXT, 'canonical', static function () { return ParserOptions::newFromAnon(); }, ]; // JavaScript should have Table Of Contents suppressed yield [ NS_MAIN, 'JavaScript Test', CONTENT_MODEL_JAVASCRIPT, 'canonical', static function () { return ParserOptions::newFromAnon(); }, ]; // CSS should have Table Of Contents suppressed yield [ NS_MAIN, 'CSS Test', CONTENT_MODEL_CSS, 'canonical', static function () { return ParserOptions::newFromAnon(); }, ]; // Language Conversion tables have content conversion disabled yield [ NS_MEDIAWIKI, 'Conversiontable/Test', CONTENT_MODEL_WIKITEXT, static function ( $test ) { // Switch wiki to a language where LanguageConverter is enabled $test->setContentLang( 'zh' ); $test->setUserLang( 'en' ); return 'canonical'; }, static function () { $po = ParserOptions::newFromAnon(); $po->disableContentConversion(); // "Canonical" PO should use content language not user language Assert::assertSame( 'zh', $po->getUserLang() ); return $po; }, ]; // Test "non-canonical" options: parser option should use user // language here, not content language $user = null; yield [ NS_MAIN, 'Main Page', CONTENT_MODEL_WIKITEXT, static function ( $test ) use ( &$user ) { $test->setContentLang( 'qqx' ); $test->setUserLang( 'fr' ); $user = $test->getTestUser()->getUser(); return $user; }, static function () use ( &$user ) { $po = ParserOptions::newFromUser( $user ); Assert::assertSame( 'fr', $po->getUserLang() ); return $po; }, ]; } public static function provideGetParserOutput() { return [ [ CONTENT_MODEL_WIKITEXT, "hello ''world''\n", '
hello world
\nvar test='<h2>not really a heading</h2>';\n", ], [ CONTENT_MODEL_CSS, "/* Not ''wikitext'' */", "
\n/* Not ''wikitext'' */\n", ], // @todo more...? ]; } /** * @dataProvider provideGetParserOutput */ public function testGetParserOutput( $model, $text, $expectedHtml ) { $page = $this->createPage( __METHOD__, $text, $model ); $opt = $page->makeParserOptions( 'canonical' ); $po = $page->getParserOutput( $opt ); $pipeline = MediaWikiServices::getInstance()->getDefaultOutputPipeline(); $text = $pipeline->run( $po, $opt, [] )->getContentHolderText(); $text = trim( preg_replace( '//sm', '', $text ) ); # strip injected comments $text = preg_replace( '!\s*(|)!m', '\1', $text ); # don't let tidy confuse us $this->assertEquals( $expectedHtml, $text ); } public function testGetParserOutput_nonexisting() { $page = new WikiPage( Title::newFromText( __METHOD__ ) ); $opt = ParserOptions::newFromAnon(); $po = $page->getParserOutput( $opt ); $this->assertFalse( $po, "getParserOutput() shall return false for non-existing pages." ); } public function testGetParserOutput_badrev() { $page = $this->createPage( __METHOD__, 'dummy', CONTENT_MODEL_WIKITEXT ); $opt = ParserOptions::newFromAnon(); $po = $page->getParserOutput( $opt, $page->getLatest() + 1234 ); // @todo would be neat to also test deleted revision $this->assertFalse( $po, "getParserOutput() shall return false for non-existing revisions." ); } public const SECTIONS = "Intro == stuff == hello world == test == just a test == foo == more stuff "; public function dataReplaceSection() { // NOTE: assume the Help namespace to contain wikitext return [ [ 'Help:WikiPageTest_testReplaceSection', CONTENT_MODEL_WIKITEXT, self::SECTIONS, "0", "No more", null, trim( preg_replace( '/^Intro/m', 'No more', self::SECTIONS ) ) ], [ 'Help:WikiPageTest_testReplaceSection', CONTENT_MODEL_WIKITEXT, self::SECTIONS, "", "No more", null, "No more" ], [ 'Help:WikiPageTest_testReplaceSection', CONTENT_MODEL_WIKITEXT, self::SECTIONS, "2", "== TEST ==\nmore fun", null, trim( preg_replace( '/^== test ==.*== foo ==/sm', "== TEST ==\nmore fun\n\n== foo ==", self::SECTIONS ) ) ], [ 'Help:WikiPageTest_testReplaceSection', CONTENT_MODEL_WIKITEXT, self::SECTIONS, "8", "No more", null, trim( self::SECTIONS ) ], [ 'Help:WikiPageTest_testReplaceSection', CONTENT_MODEL_WIKITEXT, self::SECTIONS, "new", "No more", "New", trim( self::SECTIONS ) . "\n\n== New ==\n\nNo more" ], ]; } /** * @dataProvider dataReplaceSection */ public function testReplaceSectionContent( $title, $model, $text, $section, $with, $sectionTitle, $expected ) { $page = $this->createPage( $title, $text, $model ); $content = ContentHandler::makeContent( $with, $page->getTitle(), $page->getContentModel() ); /** @var TextContent $c */ $c = $page->replaceSectionContent( $section, $content, $sectionTitle ); $this->assertEquals( $expected, $c ? trim( $c->getText() ) : null ); } /** * @dataProvider dataReplaceSection */ public function testReplaceSectionAtRev( $title, $model, $text, $section, $with, $sectionTitle, $expected ) { $page = $this->createPage( $title, $text, $model ); $baseRevId = $page->getLatest(); $content = ContentHandler::makeContent( $with, $page->getTitle(), $page->getContentModel() ); /** @var TextContent $c */ $c = $page->replaceSectionAtRev( $section, $content, $sectionTitle, $baseRevId ); $this->assertEquals( $expected, $c ? trim( $c->getText() ) : null ); } public static function provideGetAutoDeleteReason() { return [ [ [], false, false ], [ [ [ "first edit", null ], ], "/first edit.*only contributor/", false ], [ [ [ "first edit", null ], [ "second edit", null ], ], "/second edit.*only contributor/", true ], [ [ [ "first edit", "127.0.2.22" ], [ "second edit", "127.0.3.33" ], ], "/second edit/", true ], [ [ [ "first edit: " . "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam " . " nonumy eirmod tempor invidunt ut labore et dolore magna " . "aliquyam erat, sed diam voluptua. At vero eos et accusam " . "et justo duo dolores et ea rebum. Stet clita kasd gubergren, " . "no sea takimata sanctus est Lorem ipsum dolor sit amet. " . " this here is some more filler content added to try and " . "reach the maximum automatic summary length so that this is" . " truncated ipot sodit colrad ut ad olve amit basul dat" . "Dorbet romt crobit trop bri. DannyS712 put me here lor pe" . " ode quob zot bozro see also T22281 for background pol sup" . "Lorem ipsum dolor sit amet'", null ], ], '/first edit:.*\.\.\."/', false ], [ [ [ "first edit", "127.0.2.22" ], [ "", "127.0.3.33" ], ], "/before blanking.*first edit/", true ], ]; } /** * @dataProvider provideGetAutoDeleteReason */ public function testGetAutoDeleteReason( $edits, $expectedResult, $expectedHistory ) { $this->disableAutoCreateTempUser(); // NOTE: assume Help namespace to contain wikitext $page = $this->newPage( "Help:WikiPageTest_testGetAutoDeleteReason" ); $c = 1; foreach ( $edits as $edit ) { $user = new User(); if ( !empty( $edit[1] ) ) { $user->setName( $edit[1] ); } else { $user = new User; } $content = ContentHandler::makeContent( $edit[0], $page->getTitle(), $page->getContentModel() ); $page->doUserEditContent( $content, $user, "test edit $c", $c < 2 ? EDIT_NEW : 0 ); $c += 1; } $this->hideDeprecated( 'WikiPage::getAutoDeleteReason:' ); $this->hideDeprecated( 'MediaWiki\\Content\\ContentHandler::getAutoDeleteReason:' ); $reason = $page->getAutoDeleteReason( $hasHistory ); if ( is_bool( $expectedResult ) || $expectedResult === null ) { $this->assertEquals( $expectedResult, $reason ); } else { $this->assertTrue( (bool)preg_match( $expectedResult, $reason ), "Autosummary didn't match expected pattern $expectedResult: $reason" ); } $this->assertEquals( $expectedHistory, $hasHistory, "expected \$hasHistory to be " . var_export( $expectedHistory, true ) ); } public static function providePreSaveTransform() { return [ [ 'hello this is ~~~', "hello this is [[Special:Contributions/127.0.0.1|127.0.0.1]]", ], [ 'hello \'\'this\'\' is