Debian Codegraph @

tests/phpunit/includes/page/WikiPageDbTest.php

raw symbols SCIP
1 <?php
2
3 use MediaWiki\Category\Category;
4 use MediaWiki\CommentStore\CommentStoreComment;
5 use MediaWiki\Content\Content;
6 use MediaWiki\Content\ContentHandler;
7 use MediaWiki\Content\Renderer\ContentRenderer;
8 use MediaWiki\Content\TextContent;
9 use MediaWiki\Content\WikitextContent;
10 use MediaWiki\Deferred\SiteStatsUpdate;
11 use MediaWiki\Edit\PreparedEdit;
12 use MediaWiki\MainConfigNames;
13 use MediaWiki\MediaWikiServices;
14 use MediaWiki\Parser\ParserOptions;
15 use MediaWiki\Parser\ParserOutput;
16 use MediaWiki\Permissions\Authority;
17 use MediaWiki\Revision\MutableRevisionRecord;
18 use MediaWiki\Revision\RevisionRecord;
19 use MediaWiki\Revision\SlotRecord;
20 use MediaWiki\Storage\RevisionSlotsUpdate;
21 use MediaWiki\Tests\Unit\DummyServicesTrait;
22 use MediaWiki\Tests\Unit\Permissions\MockAuthorityTrait;
23 use MediaWiki\Tests\User\TempUser\TempUserTestTrait;
24 use MediaWiki\Title\Title;
25 use MediaWiki\User\User;
26 use MediaWiki\Utils\MWTimestamp;
27 use PHPUnit\Framework\Assert;
28 use Wikimedia\Rdbms\IDBAccessObject;
29 use Wikimedia\TestingAccessWrapper;
30
31 /**
32 * @covers \WikiPage
33 * @group Database
34 */
35 class WikiPageDbTest extends MediaWikiLangTestCase {
36 use DummyServicesTrait;
37 use MockAuthorityTrait;
38 use TempUserTestTrait;
39
40 protected function tearDown(): void {
41 ParserOptions::clearStaticCache();
42 parent::tearDown();
43 }
44
45 /**
46 * @param Title|string $title
47 * @param string|null $model
48 * @return WikiPage
49 */
50 private function newPage( $title, $model = null ) {
51 if ( is_string( $title ) ) {
52 $ns = $this->getDefaultWikitextNS();
53 $title = Title::newFromText( $title, $ns );
54 }
55
56 return new WikiPage( $title );
57 }
58
59 /**
60 * @param string|Title|WikiPage $page
61 * @param string|Content|Content[] $content
62 * @param int|null $model
63 * @param Authority|null $performer
64 *
65 * @return WikiPage
66 */
67 protected function createPage( $page, $content, $model = null, ?Authority $performer = null ) {
68 if ( is_string( $page ) || $page instanceof Title ) {
69 $page = $this->newPage( $page, $model );
70 }
71
72 $performer ??= $this->getTestUser()->getUser();
73
74 if ( is_string( $content ) ) {
75 $content = ContentHandler::makeContent( $content, $page->getTitle(), $model );
76 }
77
78 if ( !is_array( $content ) ) {
79 $content = [ SlotRecord::MAIN => $content ];
80 }
81
82 $updater = $page->newPageUpdater( $performer );
83
84 foreach ( $content as $role => $cnt ) {
85 $updater->setContent( $role, $cnt );
86 }
87
88 $updater->saveRevision( CommentStoreComment::newUnsavedComment( "testing" ) );
89 if ( !$updater->wasSuccessful() ) {
90 $this->fail( $updater->getStatus()->getWikiText() );
91 }
92
93 return $page;
94 }
95
96 public function testSerialization_fails() {
97 $this->expectException( LogicException::class );
98 $page = $this->createPage( __METHOD__, __METHOD__ );
99 serialize( $page );
100 }
101
102 public static function provideTitlesThatCannotExist() {
103 yield 'Special' => [ NS_SPECIAL, 'Recentchanges' ]; // existing special page
104 yield 'Invalid character' => [ NS_MAIN, '#' ]; // bad character
105 }
106
107 /**
108 * @dataProvider provideTitlesThatCannotExist
109 */
110 public function testConstructionWithPageThatCannotExist( $ns, $text ) {
111 $title = Title::makeTitle( $ns, $text );
112 $this->expectException( InvalidArgumentException::class );
113 new WikiPage( $title );
114 }
115
116 public function testPrepareContentForEdit() {
117 $performer = $this->mockUserAuthorityWithPermissions(
118 $this->getTestUser()->getUserIdentity(),
119 [ 'edit' ]
120 );
121 $sysop = $this->getTestUser( [ 'sysop' ] )->getUserIdentity();
122
123 $page = $this->createPage( __METHOD__, __METHOD__, null, $performer );
124 $title = $page->getTitle();
125
126 $content = ContentHandler::makeContent(
127 "[[Lorem ipsum]] dolor sit amet, consetetur sadipscing elitr, sed diam "
128 . " nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat.",
129 $title,
130 CONTENT_MODEL_WIKITEXT
131 );
132 $content2 = ContentHandler::makeContent(
133 "At vero eos et accusam et justo duo [[dolores]] et ea rebum. "
134 . "Stet clita kasd [[gubergren]], no sea takimata sanctus est. ~~~~",
135 $title,
136 CONTENT_MODEL_WIKITEXT
137 );
138
139 $edit = $page->prepareContentForEdit( $content, null, $performer->getUser(), null, false );
140
141 $this->assertInstanceOf(
142 ParserOptions::class,
143 $edit->popts,
144 "pops"
145 );
146 $this->assertStringContainsString( '</a>', $edit->output->getRawText(), "output" );
147 $this->assertStringContainsString(
148 'consetetur sadipscing elitr',
149 $edit->output->getRawText(), "output"
150 );
151
152 $this->assertTrue( $content->equals( $edit->newContent ), "newContent field" );
153 $this->assertTrue( $content->equals( $edit->pstContent ), "pstContent field" );
154 $this->assertSame( $edit->output, $edit->output, "output field" );
155 $this->assertSame( $edit->popts, $edit->popts, "popts field" );
156 $this->assertSame( null, $edit->revid, "revid field" );
157
158 // PreparedUpdate matches PreparedEdit
159 $update = $page->getCurrentUpdate();
160 $this->assertSame( $edit->output, $update->getCanonicalParserOutput() );
161
162 // Re-using the prepared info if possible
163 $sameEdit = $page->prepareContentForEdit( $content, null, $performer->getUser(), null, false );
164 $this->assertPreparedEditEquals( $edit, $sameEdit, 'equivalent PreparedEdit' );
165 $this->assertSame( $edit->pstContent, $sameEdit->pstContent, 're-use output' );
166 $this->assertSame( $edit->output, $sameEdit->output, 're-use output' );
167
168 // re-using the same PreparedUpdate
169 $this->assertSame( $update, $page->getCurrentUpdate() );
170
171 // Not re-using the same PreparedEdit if not possible
172 $edit2 = $page->prepareContentForEdit( $content2, null, $performer->getUser(), null, false );
173 $this->assertPreparedEditNotEquals( $edit, $edit2 );
174 $this->assertStringContainsString( 'At vero eos', $edit2->pstContent->serialize(), "content" );
175
176 // Not re-using the same PreparedUpdate
177 $this->assertNotSame( $update, $page->getCurrentUpdate() );
178
179 // Check pre-safe transform
180 $this->assertStringContainsString( '[[gubergren]]', $edit2->pstContent->serialize() );
181 $this->assertStringNotContainsString( '~~~~', $edit2->pstContent->serialize() );
182
183 $edit3 = $page->prepareContentForEdit( $content2, null, $sysop, null, false );
184 $this->assertPreparedEditNotEquals( $edit2, $edit3 );
185
186 // TODO: test with passing revision, then same without revision.
187 }
188
189 public function testDoEditUpdates() {
190 $user = $this->getTestUser()->getUserIdentity();
191
192 // NOTE: if site stats get out of whack and drop below 0,
193 // that causes a DB error during tear-down. So bump the
194 // numbers high enough to not drop below 0.
195 $siteStatsUpdate = SiteStatsUpdate::factory(
196 [ 'edits' => 1000, 'articles' => 1000, 'pages' => 1000 ]
197 );
198 $siteStatsUpdate->doUpdate();
199
200 $page = $this->createPage( __METHOD__, __METHOD__ );
201
202 $comment = CommentStoreComment::newUnsavedComment( __METHOD__ );
203
204 // PST turns [[|foo]] into [[foo]]
205 $content = $this->getServiceContainer()
206 ->getContentHandlerFactory()
207 ->getContentHandler( CONTENT_MODEL_WIKITEXT )
208 ->unserializeContent( __METHOD__ . ' [[|foo]][[bar]]' );
209
210 $revRecord = new MutableRevisionRecord( $page->getTitle() );
211 $revRecord->setContent( SlotRecord::MAIN, $content );
212 $revRecord->setUser( $user );
213 $revRecord->setTimestamp( '20170707040404' );
214 $revRecord->setPageId( $page->getId() );
215 $revRecord->setId( 9989 );
216 $revRecord->setMinorEdit( true );
217 $revRecord->setComment( $comment );
218
219 $page->doEditUpdates( $revRecord, $user );
220
221 // TODO: test various options; needs temporary hooks
222
223 $res = $this->getDb()->newSelectQueryBuilder()
224 ->select( '*' )
225 ->from( 'pagelinks' )
226 ->where( [ 'pl_from' => $page->getId() ] )
227 ->fetchResultSet();
228 $n = $res->numRows();
229 $res->free();
230
231 $this->assertSame( 1, $n, 'pagelinks should contain only one link if PST was not applied' );
232 }
233
234 public function testDoUserEditContent() {
235 $this->overrideConfigValue( MainConfigNames::PageCreationLog, true );
236
237 $page = $this->newPage( __METHOD__ );
238 $title = $page->getTitle();
239
240 $user1 = $this->getTestUser()->getUser();
241 // Use the confirmed group for user2 to make sure the user is different
242 $user2 = $this->getTestUser( [ 'confirmed' ] )->getUser();
243
244 $content = ContentHandler::makeContent(
245 "[[Lorem ipsum]] dolor sit amet, consetetur sadipscing elitr, sed diam "
246 . " nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat.",
247 $title,
248 CONTENT_MODEL_WIKITEXT
249 );
250
251 $preparedEditBefore = $page->prepareContentForEdit( $content, null, $user1 );
252
253 $status = $page->doUserEditContent( $content, $user1, "[[testing]] 1", EDIT_NEW );
254
255 $this->assertStatusGood( $status );
256 $this->assertTrue( $status->value['new'], 'new' );
257 $this->assertNotNull( $status->getNewRevision(), 'revision-record' );
258
259 $statusRevRecord = $status->getNewRevision();
260 $this->assertSame( $statusRevRecord->getId(), $page->getRevisionRecord()->getId() );
261 $this->assertSame( $statusRevRecord->getSha1(), $page->getRevisionRecord()->getSha1() );
262 $this->assertTrue(
263 $statusRevRecord->getContent( SlotRecord::MAIN )->equals( $content ),
264 'equals'
265 );
266
267 $revRecord = $page->getRevisionRecord();
268 $recentChange = $this->getServiceContainer()
269 ->getRevisionStore()
270 ->getRecentChange( $revRecord );
271 $preparedEditAfter = $page->prepareContentForEdit( $content, $revRecord, $user1 );
272
273 $this->assertNotNull( $recentChange );
274 $this->assertSame( $revRecord->getId(), (int)$recentChange->getAttribute( 'rc_this_oldid' ) );
275
276 // make sure that cached ParserOutput gets re-used throughout
277 $this->assertSame( $preparedEditBefore->output, $preparedEditAfter->output );
278
279 $id = $page->getId();
280
281 // Test page creation logging
282 $this->newSelectQueryBuilder()
283 ->select( [ 'log_type', 'log_action' ] )
284 ->from( 'logging' )
285 ->where( [ 'log_page' => $id ] )
286 ->assertResultSet( [ [ 'create', 'create' ] ] );
287
288 $this->assertGreaterThan( 0, $title->getArticleID(), "Title object should have new page id" );
289 $this->assertGreaterThan( 0, $id, "WikiPage should have new page id" );
290 $this->assertTrue( $title->exists(), "Title object should indicate that the page now exists" );
291 $this->assertTrue( $page->exists(), "WikiPage object should indicate that the page now exists" );
292
293 # ------------------------
294 $res = $this->getDb()->newSelectQueryBuilder()
295 ->select( '*' )
296 ->from( 'pagelinks' )
297 ->where( [ 'pl_from' => $id ] )
298 ->fetchResultSet();
299 $n = $res->numRows();
300 $res->free();
301
302 $this->assertSame( 1, $n, 'pagelinks should contain one link from the page' );
303
304 # ------------------------
305 $page = new WikiPage( $title );
306
307 $retrieved = $page->getContent();
308 $this->assertTrue( $content->equals( $retrieved ), 'retrieved content doesn\'t equal original' );
309
310 # ------------------------
311 $page = new WikiPage( $title );
312
313 // try null edit, with a different user
314 $status = $page->doUserEditContent( $content, $user2, 'This changes nothing', EDIT_UPDATE, false );
315 $this->assertStatusWarning( 'edit-no-change', $status );
316 $this->assertFalse( $status->value['new'], 'new' );
317 $this->assertNull( $status->getNewRevision(), 'revision-record' );
318 $this->assertNotNull( $page->getRevisionRecord() );
319 $this->assertTrue(
320 $page->getRevisionRecord()->getContent( SlotRecord::MAIN )->equals( $content ),
321 'equals'
322 );
323
324 # ------------------------
325 $content = ContentHandler::makeContent(
326 "At vero eos et accusam et justo duo [[dolores]] et ea rebum. "
327 . "Stet clita kasd [[gubergren]], no sea takimata sanctus est. ~~~~",
328 $title,
329 CONTENT_MODEL_WIKITEXT
330 );
331
332 $status = $page->doUserEditContent( $content, $user1, "testing 2", EDIT_UPDATE );
333 $this->assertStatusGood( $status );
334 $this->assertFalse( $status->value['new'], 'new' );
335 $this->assertNotNull( $status->getNewRevision(), 'revision-record' );
336 $statusRevRecord = $status->getNewRevision();
337 $this->assertSame( $statusRevRecord->getId(), $page->getRevisionRecord()->getId() );
338 $this->assertSame( $statusRevRecord->getSha1(), $page->getRevisionRecord()->getSha1() );
339 $this->assertFalse(
340 $statusRevRecord->getContent( SlotRecord::MAIN )->equals( $content ),
341 'not equals (PST must substitute signature)'
342 );
343
344 $revRecord = $page->getRevisionRecord();
345 $recentChange = $this->getServiceContainer()
346 ->getRevisionStore()
347 ->getRecentChange( $revRecord );
348 $this->assertNotNull( $recentChange );
349 $this->assertSame( $revRecord->getId(), (int)$recentChange->getAttribute( 'rc_this_oldid' ) );
350
351 # ------------------------
352 $page = new WikiPage( $title );
353
354 $retrieved = $page->getContent();
355 $newText = $retrieved->serialize();
356 $this->assertStringContainsString( '[[gubergren]]', $newText, 'New text must replace old text.' );
357 $this->assertStringNotContainsString( '~~~~', $newText, 'PST must substitute signature.' );
358
359 # ------------------------
360 $res = $this->getDb()->newSelectQueryBuilder()
361 ->select( '*' )
362 ->from( 'pagelinks' )
363 ->where( [ 'pl_from' => $id ] )
364 ->fetchResultSet();
365 $n = $res->numRows();
366 $res->free();
367
368 // two in page text and two in signature
369 $this->assertEquals( 4, $n, 'pagelinks should contain four links from the page' );
370 }
371
372 public static function provideNonPageTitle() {
373 yield 'bad case and char' => [ Title::makeTitle( NS_MAIN, 'lower case and bad # char' ) ];
374 yield 'empty' => [ Title::makeTitle( NS_MAIN, '' ) ];
375 yield 'special' => [ Title::makeTitle( NS_SPECIAL, 'Dummy' ) ];
376 yield 'relative' => [ Title::makeTitle( NS_MAIN, '', '#section' ) ];
377 yield 'interwiki' => [ Title::makeTitle( NS_MAIN, 'Foo', '', 'acme' ) ];
378 }
379
380 /**
381 * @dataProvider provideNonPageTitle
382 */
383 public function testDoUserEditContent_bad_page( $title ) {
384 $user1 = $this->getTestUser()->getUser();
385
386 $content = ContentHandler::makeContent(
387 "Yadda yadda",
388 $title,
389 CONTENT_MODEL_WIKITEXT
390 );
391
392 $this->filterDeprecated( '/WikiPage constructed on a Title that cannot exist as a page/' );
393 try {
394 $page = $this->newPage( $title );
395 $page->doUserEditContent( $content, $user1, "[[testing]] 1", EDIT_NEW );
396 } catch ( Exception $ex ) {
397 // Throwing is an acceptable way to react to an invalid title,
398 // as long as no garbage is written to the database.
399 }
400
401 $row = $this->getDb()->newSelectQueryBuilder()
402 ->select( '*' )
403 ->from( 'page' )
404 ->where( [ 'page_namespace' => $title->getNamespace(), 'page_title' => $title->getDBkey() ] )
405 ->fetchRow();
406
407 $this->assertFalse( $row );
408 }
409
410 public function testDoUserEditContent_twice() {
411 $title = Title::newFromText( __METHOD__ );
412 $page = $this->getServiceContainer()->getWikiPageFactory()->newFromTitle( $title );
413 $content = ContentHandler::makeContent( '$1 van $2', $title );
414
415 $user = $this->getTestUser()->getUser();
416
417 // Make sure we can do the exact same save twice.
418 // This tests checks that internal caches are reset as appropriate.
419 $status1 = $page->doUserEditContent( $content, $user, __METHOD__ );
420 $status2 = $page->doUserEditContent( $content, $user, __METHOD__ );
421
422 $this->assertStatusGood( $status1 );
423 $this->assertStatusWarning( 'edit-no-change', $status2 );
424
425 $this->assertNotNull( $status1->getNewRevision(), 'OK' );
426 $this->assertNull( $status2->getNewRevision(), 'OK' );
427 }
428
429 /**
430 * Undeletion is covered in PageArchiveTest::testUndeleteRevisions()
431 *
432 * TODO: Revision deletion
433 */
434 public function testDoDeleteArticleReal() {
435 $this->overrideConfigValues( [
436 MainConfigNames::RCWatchCategoryMembership => false,
437 ] );
438
439 $page = $this->createPage(
440 __METHOD__,
441 "[[original text]] foo",
442 CONTENT_MODEL_WIKITEXT
443 );
444 $id = $page->getId();
445 $user = $this->getTestSysop()->getUser();
446
447 $reason = "testing deletion";
448 $status = $page->doDeleteArticleReal( $reason, $user );
449
450 $this->assertFalse(
451 $page->getTitle()->getArticleID() > 0,
452 "Title object should now have page id 0"
453 );
454 $this->assertSame( 0, $page->getId(), "WikiPage should now have page id 0" );
455 $this->assertFalse(
456 $page->exists(),
457 "WikiPage::exists should return false after page was deleted"
458 );
459 $this->assertNull(
460 $page->getContent(),
461 "WikiPage::getContent should return null after page was deleted"
462 );
463
464 $t = Title::newFromText( $page->getTitle()->getPrefixedText() );
465 $this->assertFalse(
466 $t->exists(),
467 "Title::exists should return false after page was deleted"
468 );
469
470 // Run the job queue
471 $this->runJobs();
472
473 # ------------------------
474 $res = $this->getDb()->newSelectQueryBuilder()
475 ->select( '*' )
476 ->from( 'pagelinks' )
477 ->where( [ 'pl_from' => $id ] )
478 ->fetchResultSet();
479 $n = $res->numRows();
480 $res->free();
481
482 $this->assertSame( 0, $n, 'pagelinks should contain no more links from the page' );
483
484 // Test deletion logging
485 $logId = $status->getValue();
486 $commentQuery = $this->getServiceContainer()->getCommentStore()->getJoin( 'log_comment' );
487 $this->newSelectQueryBuilder()
488 ->select( [
489 'log_type',
490 'log_action',
491 'log_comment' => $commentQuery['fields']['log_comment_text'],
492 'log_actor',
493 'log_namespace',
494 'log_title',
495 ] )
496 ->from( 'logging' )
497 ->tables( $commentQuery['tables'] )
498 ->where( [ 'log_id' => $logId ] )
499 ->joinConds( $commentQuery['joins'] )
500 ->assertRowValue( [
501 'delete',
502 'delete',
503 $reason,
504 (string)$user->getActorId(),
505 (string)$page->getTitle()->getNamespace(),
506 $page->getTitle()->getDBkey(),
507 ] );
508 }
509
510 /**
511 * TODO: Test more stuff about suppression.
512 */
513 public function testDoDeleteArticleReal_suppress() {
514 $page = $this->createPage(
515 __METHOD__,
516 "[[original text]] foo",
517 CONTENT_MODEL_WIKITEXT
518 );
519
520 $user = $this->getTestSysop()->getUser();
521 $status = $page->doDeleteArticleReal(
522 /* reason */ "testing deletion",
523 $user,
524 /* suppress */ true
525 );
526
527 // Test suppression logging
528 $logId = $status->getValue();
529 $commentQuery = $this->getServiceContainer()->getCommentStore()->getJoin( 'log_comment' );
530 $this->newSelectQueryBuilder()
531 ->select( [
532 'log_type',
533 'log_action',
534 'log_comment' => $commentQuery['fields']['log_comment_text'],
535 'log_actor',
536 'log_namespace',
537 'log_title',
538 ] )
539 ->from( 'logging' )
540 ->tables( $commentQuery['tables'] )
541 ->where( [ 'log_id' => $logId ] )
542 ->joinConds( $commentQuery['joins'] )
543 ->assertRowValue( [
544 'suppress',
545 'delete',
546 'testing deletion',
547 (string)$user->getActorId(),
548 (string)$page->getTitle()->getNamespace(),
549 $page->getTitle()->getDBkey(),
550 ] );
551
552 $lookup = $this->getServiceContainer()->getArchivedRevisionLookup();
553 $archivedRevs = $lookup->listRevisions( $page->getTitle() );
554 if ( !$archivedRevs || $archivedRevs->numRows() !== 1 ) {
555 $this->fail( 'Unexpected number of archived revisions' );
556 }
557 $archivedRev = $this->getServiceContainer()->getRevisionStore()
558 ->newRevisionFromArchiveRow( $archivedRevs->current() );
559
560 $this->assertNull(
561 $archivedRev->getContent( SlotRecord::MAIN, RevisionRecord::FOR_PUBLIC ),
562 "Archived content should be null after the page was suppressed for general users"
563 );
564
565 $this->assertNull(
566 $archivedRev->getContent(
567 SlotRecord::MAIN,
568 RevisionRecord::FOR_THIS_USER,
569 $this->getTestUser()->getUser()
570 ),
571 "Archived content should be null after the page was suppressed for individual users"
572 );
573
574 $this->hideDeprecated( 'ContentHandler::getSlotDiffRendererInternal' );
575 $this->assertNull(
576 $archivedRev->getContent( SlotRecord::MAIN, RevisionRecord::FOR_THIS_USER, $user ),
577 "Archived content should be null after the page was suppressed even for a sysop"
578 );
579 }
580
581 public function testGetContent() {
582 $page = $this->newPage( __METHOD__ );
583
584 $content = $page->getContent();
585 $this->assertNull( $content );
586
587 $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT );
588
589 $content = $page->getContent();
590 $this->assertEquals( "some text", $content->getText() );
591 }
592
593 public function testExists() {
594 $page = $this->newPage( __METHOD__ );
595 $this->assertFalse( $page->exists() );
596
597 $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT );
598 $this->assertTrue( $page->exists() );
599
600 $page = new WikiPage( $page->getTitle() );
601 $this->assertTrue( $page->exists() );
602
603 $this->deletePage( $page, "done testing" );
604 $this->assertFalse( $page->exists() );
605
606 $page = new WikiPage( $page->getTitle() );
607 $this->assertFalse( $page->exists() );
608 }
609
610 public static function provideHasViewableContent() {
611 return [
612 [ 'WikiPageTest_testHasViewableContent', false, true ],
613 [ 'MediaWiki:WikiPageTest_testHasViewableContent', false ],
614 [ 'MediaWiki:help', true ],
615 ];
616 }
617
618 /**
619 * @dataProvider provideHasViewableContent
620 */
621 public function testHasViewableContent( $title, $viewable, $create = false ) {
622 $page = $this->newPage( $title );
623 $this->assertEquals( $viewable, $page->hasViewableContent() );
624
625 if ( $create ) {
626 $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT );
627 $this->assertTrue( $page->hasViewableContent() );
628
629 $page = new WikiPage( $page->getTitle() );
630 $this->assertTrue( $page->hasViewableContent() );
631 }
632 }
633
634 public static function provideGetRedirectTarget() {
635 return [
636 [ 'WikiPageTest_testGetRedirectTarget_1', CONTENT_MODEL_WIKITEXT, "hello world", null ],
637 [
638 'WikiPageTest_testGetRedirectTarget_2',
639 CONTENT_MODEL_WIKITEXT,
640 "#REDIRECT [[hello world]]",
641 "Hello world"
642 ],
643 // The below added to protect against Media namespace
644 // redirects which throw a fatal: (T203942)
645 [
646 'WikiPageTest_testGetRedirectTarget_3',
647 CONTENT_MODEL_WIKITEXT,
648 "#REDIRECT [[Media:hello_world]]",
649 "File:Hello world"
650 ],
651 // Test fragments longer than 255 bytes (T207876)
652 [
653 'WikiPageTest_testGetRedirectTarget_4',
654 CONTENT_MODEL_WIKITEXT,
655 '#REDIRECT [[Foobar#🏴󠁮󠁬󠁦󠁲󠁿🏴󠁮󠁬󠁦󠁲󠁿🏴󠁮󠁬󠁦󠁲󠁿🏴󠁮󠁬󠁦󠁲󠁿🏴󠁮󠁬󠁦󠁲󠁿🏴󠁮󠁬󠁦󠁲󠁿🏴󠁮󠁬󠁦󠁲󠁿🏴󠁮󠁬󠁦󠁲󠁿🏴󠁮󠁬󠁦󠁲󠁿🏴󠁮󠁬󠁦󠁲󠁿🏴󠁮󠁬󠁦󠁲󠁿🏴󠁮󠁬󠁦󠁲󠁿🏴󠁮󠁬󠁦󠁲󠁿🏴󠁮󠁬󠁦󠁲󠁿🏴󠁮󠁬󠁦󠁲󠁿🏴󠁮󠁬󠁦󠁲󠁿🏴󠁮󠁬󠁦󠁲󠁿🏴󠁮󠁬󠁦󠁲󠁿🏴󠁮󠁬󠁦󠁲󠁿🏴󠁮󠁬󠁦󠁲󠁿🏴󠁮󠁬󠁦󠁲󠁿🏴󠁮󠁬󠁦󠁲󠁿]]',
656 'Foobar#🏴󠁮󠁬󠁦󠁲󠁿🏴󠁮󠁬󠁦󠁲󠁿🏴󠁮󠁬󠁦󠁲󠁿🏴󠁮󠁬󠁦󠁲󠁿🏴󠁮󠁬󠁦󠁲󠁿🏴󠁮󠁬󠁦󠁲󠁿🏴󠁮󠁬󠁦󠁲󠁿🏴󠁮󠁬󠁦󠁲󠁿🏴󠁮󠁬󠁦󠁲󠁿🏴󠁮󠁬󠁦󠁲󠁿🏴󠁮󠁬'
657 ]
658 ];
659 }
660
661 /**
662 * @dataProvider provideGetRedirectTarget
663 * @covers \WikiPage
664 * @covers \MediaWiki\Page\RedirectStore
665 */
666 public function testGetRedirectTarget( $title, $model, $text, $target ) {
667 $this->overrideConfigValues( [
668 MainConfigNames::CapitalLinks => true,
669 // The file redirect can trigger http request with UseInstantCommons = true
670 MainConfigNames::ForeignFileRepos => [],
671 ] );
672
673 $titleFormatter = $this->getServiceContainer()->getTitleFormatter();
674
675 $page = $this->createPage( $title, $text, $model );
676
677 # double check, because this test seems to fail for no reason for some people.
678 $c = $page->getContent();
679 $this->assertEquals( WikitextContent::class, get_class( $c ) );
680
681 # now, test the actual redirect
682 $redirectStore = $this->getServiceContainer()->getRedirectStore();
683 $t = $redirectStore->getRedirectTarget( $page );
684
685 $this->assertEquals( $target, $t ? $titleFormatter->getFullText( $t ) : null );
686 }
687
688 /**
689 * @dataProvider provideGetRedirectTarget
690 */
691 public function testIsRedirect( $title, $model, $text, $target ) {
692 // The file redirect can trigger http request with UseInstantCommons = true
693 $this->overrideConfigValue( MainConfigNames::ForeignFileRepos, [] );
694
695 $page = $this->createPage( $title, $text, $model );
696 $this->assertEquals( $target !== null, $page->isRedirect() );
697 }
698
699 public static function provideIsCountable() {
700 return [
701
702 // any
703 [ 'WikiPageTest_testIsCountable',
704 CONTENT_MODEL_WIKITEXT,
705 '',
706 'any',
707 true
708 ],
709 [ 'WikiPageTest_testIsCountable',
710 CONTENT_MODEL_WIKITEXT,
711 'Foo',
712 'any',
713 true
714 ],
715
716 // link
717 [ 'WikiPageTest_testIsCountable',
718 CONTENT_MODEL_WIKITEXT,
719 'Foo',
720 'link',
721 false
722 ],
723 [ 'WikiPageTest_testIsCountable',
724 CONTENT_MODEL_WIKITEXT,
725 'Foo [[bar]]',
726 'link',
727 true
728 ],
729
730 // redirects
731 [ 'WikiPageTest_testIsCountable',
732 CONTENT_MODEL_WIKITEXT,
733 '#REDIRECT [[bar]]',
734 'any',
735 false
736 ],
737 [ 'WikiPageTest_testIsCountable',
738 CONTENT_MODEL_WIKITEXT,
739 '#REDIRECT [[bar]]',
740 'link',
741 false
742 ],
743
744 // not a content namespace
745 [ 'Talk:WikiPageTest_testIsCountable',
746 CONTENT_MODEL_WIKITEXT,
747 'Foo',
748 'any',
749 false
750 ],
751 [ 'Talk:WikiPageTest_testIsCountable',
752 CONTENT_MODEL_WIKITEXT,
753 'Foo [[bar]]',
754 'link',
755 false
756 ],
757
758 // not a content namespace, different model
759 [ 'MediaWiki:WikiPageTest_testIsCountable.js',
760 null,
761 'Foo',
762 'any',
763 false
764 ],
765 [ 'MediaWiki:WikiPageTest_testIsCountable.js',
766 null,
767 'Foo [[bar]]',
768 'link',
769 false
770 ],
771 ];
772 }
773
774 /**
775 * @dataProvider provideIsCountable
776 */
777 public function testIsCountable( $title, $model, $text, $mode, $expected ) {
778 $this->overrideConfigValue( MainConfigNames::ArticleCountMethod, $mode );
779
780 $title = Title::newFromText( $title );
781
782 $page = $this->createPage( $title, $text, $model );
783
784 $editInfo = $page->prepareContentForEdit(
785 $page->getContent(),
786 null,
787 $this->getTestUser()->getUser()
788 );
789
790 $v = $page->isCountable();
791 $w = $page->isCountable( $editInfo );
792
793 $this->assertEquals(
794 $expected,
795 $v,
796 "isCountable( null ) returned unexpected value " . var_export( $v, true )
797 . " instead of " . var_export( $expected, true )
798 . " in mode `$mode` for text \"$text\""
799 );
800
801 $this->assertEquals(
802 $expected,
803 $w,
804 "isCountable( \$editInfo ) returned unexpected value " . var_export( $v, true )
805 . " instead of " . var_export( $expected, true )
806 . " in mode `$mode` for text \"$text\""
807 );
808 }
809
810 /**
811 * @dataProvider provideMakeParserOptions
812 */
813 public function testMakeParserOptions( int $ns, string $title, string $model, $context, callable $expectation ) {
814 // Ensure we're working with the default values during this test.
815 $this->overrideConfigValues( [
816 MainConfigNames::TextModelsToParse => [
817 CONTENT_MODEL_WIKITEXT,
818 CONTENT_MODEL_JAVASCRIPT,
819 CONTENT_MODEL_CSS,
820 ],
821 MainConfigNames::DisableLangConversion => false,
822 ] );
823 // Call the context function first, which lets us setup the
824 // overall wiki context before invoking the function-under-test
825 if ( is_callable( $context ) ) {
826 $context = $context( $this );
827 }
828 $page = $this->createPage(
829 Title::makeTitle( $ns, $title ), __METHOD__, $model
830 );
831 $parserOptions = $page->makeParserOptions( $context );
832 $expected = $expectation();
833 $this->assertTrue( $expected->matches( $parserOptions ) );
834 }
835
836 /**
837 * @dataProvider provideMakeParserOptions
838 */
839 public function testMakeParserOptionsFromTitleAndModel( int $ns, string $title, string $model, $context, callable $expectation ) {
840 // Ensure we're working with the default values during this test.
841 $this->overrideConfigValues( [
842 MainConfigNames::TextModelsToParse => [
843 CONTENT_MODEL_WIKITEXT,
844 CONTENT_MODEL_JAVASCRIPT,
845 CONTENT_MODEL_CSS,
846 ],
847 MainConfigNames::DisableLangConversion => false,
848 ] );
849 // Call the context function first, which lets us setup the
850 // overall wiki context before invoking the function-under-test
851 if ( is_callable( $context ) ) {
852 $context = $context( $this );
853 }
854 $parserOptions = WikiPage::makeParserOptionsFromTitleAndModel(
855 Title::makeTitle( $ns, $title ), $model, $context
856 );
857 $expected = $expectation();
858 $this->assertTrue( $expected->matches( $parserOptions ) );
859 }
860
861 public static function provideMakeParserOptions() {
862 // Default canonical parser options for a normal wikitext page
863 yield [
864 NS_MAIN, 'Main Page', CONTENT_MODEL_WIKITEXT, 'canonical',
865 static function () {
866 return ParserOptions::newFromAnon();
867 },
868 ];
869 // JavaScript should have Table Of Contents suppressed
870 yield [
871 NS_MAIN, 'JavaScript Test', CONTENT_MODEL_JAVASCRIPT, 'canonical',
872 static function () {
873 return ParserOptions::newFromAnon();
874 },
875 ];
876 // CSS should have Table Of Contents suppressed
877 yield [
878 NS_MAIN, 'CSS Test', CONTENT_MODEL_CSS, 'canonical',
879 static function () {
880 return ParserOptions::newFromAnon();
881 },
882 ];
883 // Language Conversion tables have content conversion disabled
884 yield [
885 NS_MEDIAWIKI, 'Conversiontable/Test', CONTENT_MODEL_WIKITEXT,
886 static function ( $test ) {
887 // Switch wiki to a language where LanguageConverter is enabled
888 $test->setContentLang( 'zh' );
889 $test->setUserLang( 'en' );
890 return 'canonical';
891 },
892 static function () {
893 $po = ParserOptions::newFromAnon();
894 $po->disableContentConversion();
895 // "Canonical" PO should use content language not user language
896 Assert::assertSame( 'zh', $po->getUserLang() );
897 return $po;
898 },
899 ];
900 // Test "non-canonical" options: parser option should use user
901 // language here, not content language
902 $user = null;
903 yield [
904 NS_MAIN, 'Main Page', CONTENT_MODEL_WIKITEXT,
905 static function ( $test ) use ( &$user ) {
906 $test->setContentLang( 'qqx' );
907 $test->setUserLang( 'fr' );
908 $user = $test->getTestUser()->getUser();
909 return $user;
910 },
911 static function () use ( &$user ) {
912 $po = ParserOptions::newFromUser( $user );
913 Assert::assertSame( 'fr', $po->getUserLang() );
914 return $po;
915 },
916 ];
917 }
918
919 public static function provideGetParserOutput() {
920 return [
921 [
922 CONTENT_MODEL_WIKITEXT,
923 "hello ''world''\n",
924 '<div class="mw-content-ltr mw-parser-output" lang="en" dir="ltr"><p>hello <i>world</i></p></div>'
925 ],
926 [
927 CONTENT_MODEL_JAVASCRIPT,
928 "var test='<h2>not really a heading</h2>';",
929 "<pre class=\"mw-code mw-js\" dir=\"ltr\">var test='&lt;h2&gt;not really a heading&lt;/h2&gt;';\n</pre>",
930 ],
931 [
932 CONTENT_MODEL_CSS,
933 "/* Not ''wikitext'' */",
934 "<pre class=\"mw-code mw-css\" dir=\"ltr\">/* Not ''wikitext'' */\n</pre>",
935 ],
936 // @todo more...?
937 ];
938 }
939
940 /**
941 * @dataProvider provideGetParserOutput
942 */
943 public function testGetParserOutput( $model, $text, $expectedHtml ) {
944 $page = $this->createPage( __METHOD__, $text, $model );
945
946 $opt = $page->makeParserOptions( 'canonical' );
947 $po = $page->getParserOutput( $opt );
948 $pipeline = MediaWikiServices::getInstance()->getDefaultOutputPipeline();
949 $text = $pipeline->run( $po, $opt, [] )->getContentHolderText();
950
951 $text = trim( preg_replace( '/<!--.*?-->/sm', '', $text ) ); # strip injected comments
952 $text = preg_replace( '!\s*(</p>|</div>)!m', '\1', $text ); # don't let tidy confuse us
953
954 $this->assertEquals( $expectedHtml, $text );
955 }
956
957 public function testGetParserOutput_nonexisting() {
958 $page = new WikiPage( Title::newFromText( __METHOD__ ) );
959
960 $opt = ParserOptions::newFromAnon();
961 $po = $page->getParserOutput( $opt );
962
963 $this->assertFalse( $po, "getParserOutput() shall return false for non-existing pages." );
964 }
965
966 public function testGetParserOutput_badrev() {
967 $page = $this->createPage( __METHOD__, 'dummy', CONTENT_MODEL_WIKITEXT );
968
969 $opt = ParserOptions::newFromAnon();
970 $po = $page->getParserOutput( $opt, $page->getLatest() + 1234 );
971
972 // @todo would be neat to also test deleted revision
973
974 $this->assertFalse( $po, "getParserOutput() shall return false for non-existing revisions." );
975 }
976
977 public const SECTIONS =
978
979 "Intro
980
981 == stuff ==
982 hello world
983
984 == test ==
985 just a test
986
987 == foo ==
988 more stuff
989 ";
990
991 public function dataReplaceSection() {
992 // NOTE: assume the Help namespace to contain wikitext
993 return [
994 [ 'Help:WikiPageTest_testReplaceSection',
995 CONTENT_MODEL_WIKITEXT,
996 self::SECTIONS,
997 "0",
998 "No more",
999 null,
1000 trim( preg_replace( '/^Intro/m', 'No more', self::SECTIONS ) )
1001 ],
1002 [ 'Help:WikiPageTest_testReplaceSection',
1003 CONTENT_MODEL_WIKITEXT,
1004 self::SECTIONS,
1005 "",
1006 "No more",
1007 null,
1008 "No more"
1009 ],
1010 [ 'Help:WikiPageTest_testReplaceSection',
1011 CONTENT_MODEL_WIKITEXT,
1012 self::SECTIONS,
1013 "2",
1014 "== TEST ==\nmore fun",
1015 null,
1016 trim( preg_replace( '/^== test ==.*== foo ==/sm',
1017 "== TEST ==\nmore fun\n\n== foo ==",
1018 self::SECTIONS ) )
1019 ],
1020 [ 'Help:WikiPageTest_testReplaceSection',
1021 CONTENT_MODEL_WIKITEXT,
1022 self::SECTIONS,
1023 "8",
1024 "No more",
1025 null,
1026 trim( self::SECTIONS )
1027 ],
1028 [ 'Help:WikiPageTest_testReplaceSection',
1029 CONTENT_MODEL_WIKITEXT,
1030 self::SECTIONS,
1031 "new",
1032 "No more",
1033 "New",
1034 trim( self::SECTIONS ) . "\n\n== New ==\n\nNo more"
1035 ],
1036 ];
1037 }
1038
1039 /**
1040 * @dataProvider dataReplaceSection
1041 */
1042 public function testReplaceSectionContent( $title, $model, $text, $section,
1043 $with, $sectionTitle, $expected
1044 ) {
1045 $page = $this->createPage( $title, $text, $model );
1046
1047 $content = ContentHandler::makeContent( $with, $page->getTitle(), $page->getContentModel() );
1048 /** @var TextContent $c */
1049 $c = $page->replaceSectionContent( $section, $content, $sectionTitle );
1050
1051 $this->assertEquals( $expected, $c ? trim( $c->getText() ) : null );
1052 }
1053
1054 /**
1055 * @dataProvider dataReplaceSection
1056 */
1057 public function testReplaceSectionAtRev( $title, $model, $text, $section,
1058 $with, $sectionTitle, $expected
1059 ) {
1060 $page = $this->createPage( $title, $text, $model );
1061 $baseRevId = $page->getLatest();
1062
1063 $content = ContentHandler::makeContent( $with, $page->getTitle(), $page->getContentModel() );
1064 /** @var TextContent $c */
1065 $c = $page->replaceSectionAtRev( $section, $content, $sectionTitle, $baseRevId );
1066
1067 $this->assertEquals( $expected, $c ? trim( $c->getText() ) : null );
1068 }
1069
1070 public static function provideGetAutoDeleteReason() {
1071 return [
1072 [
1073 [],
1074 false,
1075 false
1076 ],
1077
1078 [
1079 [
1080 [ "first edit", null ],
1081 ],
1082 "/first edit.*only contributor/",
1083 false
1084 ],
1085
1086 [
1087 [
1088 [ "first edit", null ],
1089 [ "second edit", null ],
1090 ],
1091 "/second edit.*only contributor/",
1092 true
1093 ],
1094
1095 [
1096 [
1097 [ "first edit", "127.0.2.22" ],
1098 [ "second edit", "127.0.3.33" ],
1099 ],
1100 "/second edit/",
1101 true
1102 ],
1103
1104 [
1105 [
1106 [
1107 "first edit: "
1108 . "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam "
1109 . " nonumy eirmod tempor invidunt ut labore et dolore magna "
1110 . "aliquyam erat, sed diam voluptua. At vero eos et accusam "
1111 . "et justo duo dolores et ea rebum. Stet clita kasd gubergren, "
1112 . "no sea takimata sanctus est Lorem ipsum dolor sit amet. "
1113 . " this here is some more filler content added to try and "
1114 . "reach the maximum automatic summary length so that this is"
1115 . " truncated ipot sodit colrad ut ad olve amit basul dat"
1116 . "Dorbet romt crobit trop bri. DannyS712 put me here lor pe"
1117 . " ode quob zot bozro see also T22281 for background pol sup"
1118 . "Lorem ipsum dolor sit amet'",
1119 null
1120 ],
1121 ],
1122 '/first edit:.*\.\.\."/',
1123 false
1124 ],
1125
1126 [
1127 [
1128 [ "first edit", "127.0.2.22" ],
1129 [ "", "127.0.3.33" ],
1130 ],
1131 "/before blanking.*first edit/",
1132 true
1133 ],
1134
1135 ];
1136 }
1137
1138 /**
1139 * @dataProvider provideGetAutoDeleteReason
1140 */
1141 public function testGetAutoDeleteReason( $edits, $expectedResult, $expectedHistory ) {
1142 $this->disableAutoCreateTempUser();
1143
1144 // NOTE: assume Help namespace to contain wikitext
1145 $page = $this->newPage( "Help:WikiPageTest_testGetAutoDeleteReason" );
1146
1147 $c = 1;
1148
1149 foreach ( $edits as $edit ) {
1150 $user = new User();
1151
1152 if ( !empty( $edit[1] ) ) {
1153 $user->setName( $edit[1] );
1154 } else {
1155 $user = new User;
1156 }
1157
1158 $content = ContentHandler::makeContent( $edit[0], $page->getTitle(), $page->getContentModel() );
1159
1160 $page->doUserEditContent( $content, $user, "test edit $c", $c < 2 ? EDIT_NEW : 0 );
1161
1162 $c += 1;
1163 }
1164
1165 $this->hideDeprecated( 'WikiPage::getAutoDeleteReason:' );
1166 $this->hideDeprecated( 'MediaWiki\\Content\\ContentHandler::getAutoDeleteReason:' );
1167 $reason = $page->getAutoDeleteReason( $hasHistory );
1168
1169 if ( is_bool( $expectedResult ) || $expectedResult === null ) {
1170 $this->assertEquals( $expectedResult, $reason );
1171 } else {
1172 $this->assertTrue( (bool)preg_match( $expectedResult, $reason ),
1173 "Autosummary didn't match expected pattern $expectedResult: $reason" );
1174 }
1175
1176 $this->assertEquals( $expectedHistory, $hasHistory,
1177 "expected \$hasHistory to be " . var_export( $expectedHistory, true ) );
1178 }
1179
1180 public static function providePreSaveTransform() {
1181 return [
1182 [ 'hello this is ~~~',
1183 "hello this is [[Special:Contributions/127.0.0.1|127.0.0.1]]",
1184 ],
1185 [ 'hello \'\'this\'\' is <nowiki>~~~</nowiki>',
1186 'hello \'\'this\'\' is <nowiki>~~~</nowiki>',
1187 ],
1188 ];
1189 }
1190
1191 public function testLoadPageData() {
1192 $title = Title::makeTitle( NS_MAIN, 'SomePage' );
1193 $page = $this->getServiceContainer()->getWikiPageFactory()->newFromTitle( $title );
1194
1195 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject::READ_NORMAL ) );
1196 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject::READ_LATEST ) );
1197 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject::READ_LOCKING ) );
1198 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject::READ_EXCLUSIVE ) );
1199
1200 $page->loadPageData( IDBAccessObject::READ_NORMAL );
1201 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject::READ_NORMAL ) );
1202 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject::READ_LATEST ) );
1203 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject::READ_LOCKING ) );
1204 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject::READ_EXCLUSIVE ) );
1205
1206 $page->loadPageData( IDBAccessObject::READ_LATEST );
1207 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject::READ_NORMAL ) );
1208 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject::READ_LATEST ) );
1209 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject::READ_LOCKING ) );
1210 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject::READ_EXCLUSIVE ) );
1211
1212 $page->loadPageData( IDBAccessObject::READ_LOCKING );
1213 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject::READ_NORMAL ) );
1214 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject::READ_LATEST ) );
1215 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject::READ_LOCKING ) );
1216 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject::READ_EXCLUSIVE ) );
1217
1218 $page->loadPageData( IDBAccessObject::READ_EXCLUSIVE );
1219 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject::READ_NORMAL ) );
1220 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject::READ_LATEST ) );
1221 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject::READ_LOCKING ) );
1222 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject::READ_EXCLUSIVE ) );
1223 }
1224
1225 public function testUpdateCategoryCounts() {
1226 $page = new WikiPage( Title::newFromText( __METHOD__ ) );
1227
1228 // Add an initial category
1229 $page->updateCategoryCounts( [ 'A' ], [], 0 );
1230
1231 $this->assertSame( 1, Category::newFromName( 'A' )->getMemberCount() );
1232 $this->assertSame( 0, Category::newFromName( 'B' )->getMemberCount() );
1233 $this->assertSame( 0, Category::newFromName( 'C' )->getMemberCount() );
1234
1235 // Add a new category
1236 $page->updateCategoryCounts( [ 'B' ], [], 0 );
1237
1238 $this->assertSame( 1, Category::newFromName( 'A' )->getMemberCount() );
1239 $this->assertSame( 1, Category::newFromName( 'B' )->getMemberCount() );
1240 $this->assertSame( 0, Category::newFromName( 'C' )->getMemberCount() );
1241
1242 // Add and remove a category
1243 $page->updateCategoryCounts( [ 'C' ], [ 'A' ], 0 );
1244
1245 $this->assertSame( 0, Category::newFromName( 'A' )->getMemberCount() );
1246 $this->assertSame( 1, Category::newFromName( 'B' )->getMemberCount() );
1247 $this->assertSame( 1, Category::newFromName( 'C' )->getMemberCount() );
1248 }
1249
1250 public static function provideUpdateRedirectOn() {
1251 yield [ '#REDIRECT [[Foo]]', true, null, true, true, [] ];
1252 yield [ '#REDIRECT [[Foo]]', true, 'Foo', true, true, [ [ NS_MAIN, 'Foo' ] ] ];
1253 yield [ 'SomeText', false, null, false, true, [] ];
1254 yield [ 'SomeText', false, 'Foo', false, true, [ [ NS_MAIN, 'Foo' ] ] ];
1255 }
1256
1257 /**
1258 * @dataProvider provideUpdateRedirectOn
1259 *
1260 * @param string $initialText
1261 * @param bool $initialRedirectState
1262 * @param string|null $redirectTitle
1263 * @param bool|null $lastRevIsRedirect
1264 * @param bool $expectedSuccess
1265 * @param array $expectedRows
1266 */
1267 public function testUpdateRedirectOn(
1268 $initialText,
1269 $initialRedirectState,
1270 $redirectTitle,
1271 $lastRevIsRedirect,
1272 $expectedSuccess,
1273 $expectedRows
1274 ) {
1275 static $pageCounter = 0;
1276 $pageCounter++;
1277
1278 $page = $this->createPage( Title::newFromText( __METHOD__ . $pageCounter ), $initialText );
1279 $this->assertSame( $initialRedirectState, $page->isRedirect() );
1280
1281 $redirectTitle = is_string( $redirectTitle )
1282 ? Title::newFromText( $redirectTitle )
1283 : $redirectTitle;
1284
1285 $success = $this->getServiceContainer()->getRedirectStore()
1286 ->updateRedirectTarget( $page, $redirectTitle, $lastRevIsRedirect );
1287 $this->assertSame( $expectedSuccess, $success, 'Success assertion' );
1288 /**
1289 * updateRedirectTarget explicitly updates the redirect table (and not the page table).
1290 * Most of core checks the page table for redirect status, so we have to be ugly and
1291 * assert a select from the table here.
1292 */
1293 $this->assertRedirectTableCountForPageId( $page->getId(), $expectedRows );
1294 }
1295
1296 private function assertRedirectTableCountForPageId( $pageId, $expectedRows ) {
1297 $this->newSelectQueryBuilder()
1298 ->select( [ 'rd_namespace', 'rd_title' ] )
1299 ->from( 'redirect' )
1300 ->where( [ 'rd_from' => $pageId ] )
1301 ->assertResultSet( $expectedRows );
1302 }
1303
1304 public function testInsertRedirectEntry_insertsRedirectEntry() {
1305 $page = $this->createPage( Title::newFromText( __METHOD__ ), 'A' );
1306 $this->assertRedirectTableCountForPageId( $page->getId(), [] );
1307
1308 $targetTitle = Title::newFromText( 'SomeTarget#Frag' );
1309 $reflectedTitle = TestingAccessWrapper::newFromObject( $targetTitle );
1310 $reflectedTitle->mInterwiki = 'eninter';
1311 $this->getServiceContainer()->getRedirectStore()
1312 ->updateRedirectTarget( $page, $targetTitle );
1313
1314 $this->newSelectQueryBuilder()
1315 ->select( [ 'rd_from', 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ] )
1316 ->from( 'redirect' )
1317 ->where( [ 'rd_from' => $page->getId() ] )
1318 ->assertResultSet( [ [
1319 strval( $page->getId() ),
1320 strval( $targetTitle->getNamespace() ),
1321 strval( $targetTitle->getDBkey() ),
1322 strval( $targetTitle->getFragment() ),
1323 strval( $targetTitle->getInterwiki() ),
1324 ] ] );
1325 }
1326
1327 public function testInsertRedirectEntry_T278367() {
1328 $page = $this->createPage( Title::newFromText( __METHOD__ ), 'A' );
1329 $this->assertRedirectTableCountForPageId( $page->getId(), [] );
1330
1331 $targetTitle = Title::newFromText( '#Frag' );
1332 $ok = $this->getServiceContainer()->getRedirectStore()
1333 ->updateRedirectTarget( $page, $targetTitle );
1334
1335 $this->assertFalse( $ok );
1336 $this->assertRedirectTableCountForPageId( $page->getId(), [] );
1337 }
1338
1339 public function testUpdateRevisionOn_existingPage() {
1340 $user = $this->getTestSysop()->getUser();
1341 $page = $this->createPage( __METHOD__, 'StartText' );
1342
1343 $revisionRecord = new MutableRevisionRecord( $page );
1344 $revisionRecord->setContent(
1345 SlotRecord::MAIN,
1346 new WikitextContent( __METHOD__ . '-text' )
1347 );
1348 $revisionRecord->setUser( $user );
1349 $revisionRecord->setTimestamp( '20170707040404' );
1350 $revisionRecord->setPageId( $page->getId() );
1351 $revisionRecord->setId( 9989 );
1352 $revisionRecord->setSize( strlen( __METHOD__ . '-text' ) );
1353 $revisionRecord->setMinorEdit( true );
1354 $revisionRecord->setComment( CommentStoreComment::newUnsavedComment( __METHOD__ ) );
1355
1356 $result = $page->updateRevisionOn( $this->getDb(), $revisionRecord );
1357 $this->assertTrue( $result );
1358 $this->assertSame( 9989, $page->getLatest() );
1359 $this->assertEquals( $revisionRecord, $page->getRevisionRecord() );
1360 }
1361
1362 public function testUpdateRevisionOn_NonExistingPage() {
1363 $user = $this->getTestSysop()->getUser();
1364 $page = $this->createPage( __METHOD__, 'StartText' );
1365 $this->deletePage( $page, '', $user );
1366
1367 $revisionRecord = new MutableRevisionRecord( $page );
1368 $revisionRecord->setContent(
1369 SlotRecord::MAIN,
1370 new WikitextContent( __METHOD__ . '-text' )
1371 );
1372 $revisionRecord->setUser( $user );
1373 $revisionRecord->setTimestamp( '20170707040404' );
1374 $revisionRecord->setPageId( $page->getId() );
1375 $revisionRecord->setId( 9989 );
1376 $revisionRecord->setSize( strlen( __METHOD__ . '-text' ) );
1377 $revisionRecord->setMinorEdit( true );
1378 $revisionRecord->setComment( CommentStoreComment::newUnsavedComment( __METHOD__ ) );
1379
1380 $result = $page->updateRevisionOn( $this->getDb(), $revisionRecord );
1381 $this->assertFalse( $result );
1382 }
1383
1384 public function testInsertOn() {
1385 $title = Title::newFromText( __METHOD__ );
1386 $page = new WikiPage( $title );
1387
1388 $startTimeStamp = wfTimestampNow();
1389 $result = $page->insertOn( $this->getDb() );
1390 $endTimeStamp = wfTimestampNow();
1391
1392 $this->assertIsInt( $result );
1393 $this->assertGreaterThan( 0, $result );
1394
1395 $condition = [ 'page_id' => $result ];
1396
1397 // Check the default fields have been filled
1398 $this->newSelectQueryBuilder()
1399 ->select( [
1400 'page_namespace',
1401 'page_title',
1402 'page_is_redirect',
1403 'page_is_new',
1404 'page_latest',
1405 'page_len',
1406 ] )
1407 ->from( 'page' )
1408 ->where( $condition )
1409 ->assertResultSet( [ [
1410 '0',
1411 __METHOD__,
1412 '0',
1413 '1',
1414 '0',
1415 '0',
1416 ] ] );
1417
1418 // Check the page_random field has been filled
1419 $pageRandom = $this->getDb()->newSelectQueryBuilder()
1420 ->select( 'page_random' )
1421 ->from( 'page' )
1422 ->where( $condition )
1423 ->fetchField();
1424 $this->assertTrue( (float)$pageRandom < 1 && (float)$pageRandom > 0 );
1425
1426 // Assert the touched timestamp in the DB is roughly when we inserted the page
1427 $pageTouched = $this->getDb()->newSelectQueryBuilder()
1428 ->select( 'page_touched' )
1429 ->from( 'page' )
1430 ->where( $condition )
1431 ->fetchField();
1432 $this->assertTrue(
1433 wfTimestamp( TS_UNIX, $startTimeStamp )
1434 <= wfTimestamp( TS_UNIX, $pageTouched )
1435 );
1436 $this->assertTrue(
1437 wfTimestamp( TS_UNIX, $endTimeStamp )
1438 >= wfTimestamp( TS_UNIX, $pageTouched )
1439 );
1440
1441 // Try inserting the same page again and checking the result is false (no change)
1442 $result = $page->insertOn( $this->getDb() );
1443 $this->assertFalse( $result );
1444 }
1445
1446 public function testInsertOn_idSpecified() {
1447 $title = Title::newFromText( __METHOD__ );
1448 $page = new WikiPage( $title );
1449 $id = 1478952189;
1450
1451 $result = $page->insertOn( $this->getDb(), $id );
1452
1453 $this->assertSame( $id, $result );
1454
1455 $condition = [ 'page_id' => $result ];
1456
1457 // Check there is actually a row in the db
1458 $this->newSelectQueryBuilder()
1459 ->select( 'page_title' )
1460 ->from( 'page' )
1461 ->where( $condition )
1462 ->assertResultSet( [ [ __METHOD__ ] ] );
1463 }
1464
1465 public static function provideTestDoUpdateRestrictions_setBasicRestrictions() {
1466 // Note: Once the current dates passes the date in these tests they will fail.
1467 yield 'move something' => [
1468 true,
1469 [ 'move' => 'something' ],
1470 [],
1471 [ 'edit' => [], 'move' => [ 'something' ] ],
1472 [],
1473 ];
1474 yield 'move something, edit blank' => [
1475 true,
1476 [ 'move' => 'something', 'edit' => '' ],
1477 [],
1478 [ 'edit' => [], 'move' => [ 'something' ] ],
1479 [],
1480 ];
1481 yield 'edit sysop, with expiry' => [
1482 true,
1483 [ 'edit' => 'sysop' ],
1484 [ 'edit' => '21330101020202' ],
1485 [ 'edit' => [ 'sysop' ], 'move' => [] ],
1486 [ 'edit' => '21330101020202' ],
1487 ];
1488 yield 'move and edit, move with expiry' => [
1489 true,
1490 [ 'move' => 'something', 'edit' => 'another' ],
1491 [ 'move' => '22220202010101' ],
1492 [ 'edit' => [ 'another' ], 'move' => [ 'something' ] ],
1493 [ 'move' => '22220202010101' ],
1494 ];
1495 yield 'move and edit, edit with infinity expiry' => [
1496 true,
1497 [ 'move' => 'something', 'edit' => 'another' ],
1498 [ 'edit' => 'infinity' ],
1499 [ 'edit' => [ 'another' ], 'move' => [ 'something' ] ],
1500 [ 'edit' => 'infinity' ],
1501 ];
1502 yield 'non existing, create something' => [
1503 false,
1504 [ 'create' => 'something' ],
1505 [],
1506 [ 'create' => [ 'something' ] ],
1507 [],
1508 ];
1509 yield 'non existing, create something with expiry' => [
1510 false,
1511 [ 'create' => 'something' ],
1512 [ 'create' => '23451212112233' ],
1513 [ 'create' => [ 'something' ] ],
1514 [ 'create' => '23451212112233' ],
1515 ];
1516 }
1517
1518 /**
1519 * @dataProvider provideTestDoUpdateRestrictions_setBasicRestrictions
1520 */
1521 public function testDoUpdateRestrictions_setBasicRestrictions(
1522 $pageExists,
1523 array $limit,
1524 array $expiry,
1525 array $expectedRestrictions,
1526 array $expectedRestrictionExpiries
1527 ) {
1528 if ( $pageExists ) {
1529 $page = $this->createPage( __METHOD__, 'ABC' );
1530 } else {
1531 $page = $this->getNonexistingTestPage( Title::newFromText( __METHOD__ . '-nonexist' ) );
1532 }
1533 $user = $this->getTestSysop()->getUser();
1534 $userIdentity = $this->getTestSysop()->getUserIdentity();
1535
1536 $cascade = false;
1537
1538 $status = $page->doUpdateRestrictions( $limit, $expiry, $cascade, 'aReason', $userIdentity, [] );
1539
1540 $logId = $status->getValue();
1541 $restrictionStore = $this->getServiceContainer()->getRestrictionStore();
1542 $allRestrictions = $restrictionStore->getAllRestrictions( $page->getTitle() );
1543
1544 $this->assertStatusGood( $status );
1545 $this->assertIsInt( $logId );
1546 $this->assertSame( $expectedRestrictions, $allRestrictions );
1547 foreach ( $expectedRestrictionExpiries as $key => $value ) {
1548 $this->assertSame( $value, $restrictionStore->getRestrictionExpiry( $page->getTitle(), $key ) );
1549 }
1550
1551 // Make sure the log entry looks good
1552 // log_params is not checked here
1553 $commentQuery = $this->getServiceContainer()->getCommentStore()->getJoin( 'log_comment' );
1554 $this->newSelectQueryBuilder()
1555 ->select( [
1556 'log_comment' => $commentQuery['fields']['log_comment_text'],
1557 'log_actor',
1558 'log_namespace',
1559 'log_title',
1560 ] )
1561 ->from( 'logging' )
1562 ->tables( $commentQuery['tables'] )
1563 ->where( [ 'log_id' => $logId ] )
1564 ->joinConds( $commentQuery['joins'] )
1565 ->assertRowValue( [
1566 'aReason',
1567 (string)$user->getActorId(),
1568 (string)$page->getTitle()->getNamespace(),
1569 $page->getTitle()->getDBkey(),
1570 ] );
1571 }
1572
1573 public function testDoUpdateRestrictions_failsOnReadOnly() {
1574 $page = $this->createPage( __METHOD__, 'ABC' );
1575 $user = $this->getTestSysop()->getUser();
1576 $cascade = false;
1577
1578 // Set read only
1579 $readOnly = $this->getDummyReadOnlyMode( true );
1580 $this->setService( 'ReadOnlyMode', $readOnly );
1581
1582 $status = $page->doUpdateRestrictions( [], [], $cascade, 'aReason', $user, [] );
1583 $this->assertStatusError( 'readonlytext', $status );
1584 }
1585
1586 public function testDoUpdateRestrictions_returnsGoodIfNothingChanged() {
1587 $page = $this->createPage( __METHOD__, 'ABC' );
1588 $user = $this->getTestSysop()->getUser();
1589 $cascade = false;
1590 $limit = [ 'edit' => 'sysop' ];
1591
1592 $status = $page->doUpdateRestrictions(
1593 $limit,
1594 [],
1595 $cascade,
1596 'aReason',
1597 $user,
1598 []
1599 );
1600
1601 // The first entry should have a logId as it did something
1602 $this->assertStatusGood( $status );
1603 $this->assertIsInt( $status->getValue() );
1604
1605 $status = $page->doUpdateRestrictions(
1606 $limit,
1607 [],
1608 $cascade,
1609 'aReason',
1610 $user,
1611 []
1612 );
1613
1614 // The second entry should not have a logId as nothing changed
1615 $this->assertStatusGood( $status );
1616 $this->assertNull( $status->getValue() );
1617 }
1618
1619 public function testDoUpdateRestrictions_logEntryTypeAndAction() {
1620 $page = $this->createPage( __METHOD__, 'ABC' );
1621 $user = $this->getTestSysop()->getUser();
1622 $cascade = false;
1623
1624 // Protect the page
1625 $status = $page->doUpdateRestrictions(
1626 [ 'edit' => 'sysop' ],
1627 [],
1628 $cascade,
1629 'aReason',
1630 $user,
1631 []
1632 );
1633 $this->assertStatusGood( $status );
1634 $this->assertIsInt( $status->getValue() );
1635 $this->newSelectQueryBuilder()
1636 ->select( [ 'log_type', 'log_action' ] )
1637 ->from( 'logging' )
1638 ->where( [ 'log_id' => $status->getValue() ] )
1639 ->assertResultSet( [ [ 'protect', 'protect' ] ] );
1640
1641 // Modify the protection
1642 $status = $page->doUpdateRestrictions(
1643 [ 'edit' => 'somethingElse' ],
1644 [],
1645 $cascade,
1646 'aReason',
1647 $user,
1648 []
1649 );
1650 $this->assertStatusGood( $status );
1651 $this->assertIsInt( $status->getValue() );
1652 $this->newSelectQueryBuilder()
1653 ->select( [ 'log_type', 'log_action' ] )
1654 ->from( 'logging' )
1655 ->where( [ 'log_id' => $status->getValue() ] )
1656 ->assertResultSet( [ [ 'protect', 'modify' ] ] );
1657
1658 // Remove the protection
1659 $status = $page->doUpdateRestrictions(
1660 [],
1661 [],
1662 $cascade,
1663 'aReason',
1664 $user,
1665 []
1666 );
1667 $this->assertStatusGood( $status );
1668 $this->assertIsInt( $status->getValue() );
1669 $this->newSelectQueryBuilder()
1670 ->select( [ 'log_type', 'log_action' ] )
1671 ->from( 'logging' )
1672 ->where( [ 'log_id' => $status->getValue() ] )
1673 ->assertResultSet( [ [ 'protect', 'unprotect' ] ] );
1674 }
1675
1676 public function testNewPageUpdater() {
1677 $user = $this->getTestUser()->getUser();
1678 $page = $this->newPage( __METHOD__, __METHOD__ );
1679 $content = new WikitextContent( 'Hello World' );
1680
1681 /** @var ContentRenderer $contentRenderer */
1682 $contentRenderer = $this->getMockBuilder( ContentRenderer::class )
1683 ->onlyMethods( [ 'getParserOutput' ] )
1684 ->disableOriginalConstructor()
1685 ->getMock();
1686 $contentRenderer->expects( $this->once() )
1687 ->method( 'getParserOutput' )
1688 ->willReturn( new ParserOutput( 'HTML' ) );
1689
1690 $this->setService( 'ContentRenderer', $contentRenderer );
1691
1692 $preparedEditBefore = $page->prepareContentForEdit( $content, null, $user );
1693 $preparedUpdateBefore = $page->getCurrentUpdate();
1694
1695 // provide context, so the cache can be kept in place
1696 $slotsUpdate = new revisionSlotsUpdate();
1697 $slotsUpdate->modifyContent( SlotRecord::MAIN, $content );
1698
1699 $revision = $page->newPageUpdater( $user, $slotsUpdate )
1700 ->setContent( SlotRecord::MAIN, $content )
1701 ->saveRevision( CommentStoreComment::newUnsavedComment( 'test' ), EDIT_NEW );
1702
1703 $preparedEditAfter = $page->prepareContentForEdit( $content, $revision, $user );
1704 $preparedUpdateAfter = $page->getCurrentUpdate();
1705
1706 $this->assertSame( $revision->getId(), $page->getLatest() );
1707
1708 // Parsed output must remain cached throughout.
1709 $this->assertSame(
1710 $preparedEditBefore->output,
1711 $preparedEditAfter->output
1712 );
1713 $this->assertSame(
1714 $preparedEditBefore->output,
1715 $preparedUpdateBefore->getCanonicalParserOutput()
1716 );
1717 $this->assertSame(
1718 $preparedEditBefore->output,
1719 $preparedUpdateAfter->getCanonicalParserOutput()
1720 );
1721 }
1722
1723 public function testGetDerivedDataUpdater() {
1724 $admin = $this->getTestSysop()->getUser();
1725
1726 /** @var object $page */
1727 $page = $this->createPage( __METHOD__, __METHOD__ );
1728 $page = TestingAccessWrapper::newFromObject( $page );
1729
1730 $revision = $page->getRevisionRecord();
1731 $user = $revision->getUser();
1732
1733 $slotsUpdate = new RevisionSlotsUpdate();
1734 $slotsUpdate->modifyContent( SlotRecord::MAIN, new WikitextContent( 'Hello World' ) );
1735
1736 // get a virgin updater
1737 $updater1 = $page->getDerivedDataUpdater( $user );
1738 $this->assertFalse( $updater1->isUpdatePrepared() );
1739
1740 $updater1->prepareUpdate( $revision );
1741
1742 // Re-use updater with same revision or content, even if base changed
1743 $this->assertSame( $updater1, $page->getDerivedDataUpdater( $user, $revision ) );
1744
1745 $slotsUpdate = RevisionSlotsUpdate::newFromContent(
1746 [ SlotRecord::MAIN => $revision->getContent( SlotRecord::MAIN ) ]
1747 );
1748 $this->assertSame( $updater1, $page->getDerivedDataUpdater( $user, null, $slotsUpdate ) );
1749
1750 // Don't re-use for edit if base revision ID changed
1751 $this->assertNotSame(
1752 $updater1,
1753 $page->getDerivedDataUpdater( $user, null, $slotsUpdate, true )
1754 );
1755
1756 // Don't re-use with different user
1757 $updater2a = $page->getDerivedDataUpdater( $admin, null, $slotsUpdate );
1758 $updater2a->prepareContent( $admin, $slotsUpdate, false );
1759
1760 $updater2b = $page->getDerivedDataUpdater( $user, null, $slotsUpdate );
1761 $updater2b->prepareContent( $user, $slotsUpdate, false );
1762 $this->assertNotSame( $updater2a, $updater2b );
1763
1764 // Don't re-use with different content
1765 $updater3 = $page->getDerivedDataUpdater( $admin, null, $slotsUpdate );
1766 $updater3->prepareUpdate( $revision );
1767 $this->assertNotSame( $updater2b, $updater3 );
1768
1769 // Don't re-use if no context given
1770 $updater4 = $page->getDerivedDataUpdater( $admin );
1771 $updater4->prepareUpdate( $revision );
1772 $this->assertNotSame( $updater3, $updater4 );
1773
1774 // Don't re-use if AGAIN no context given
1775 $updater5 = $page->getDerivedDataUpdater( $admin );
1776 $this->assertNotSame( $updater4, $updater5 );
1777
1778 // Don't re-use cached "virgin" unprepared updater
1779 $updater6 = $page->getDerivedDataUpdater( $admin, $revision );
1780 $this->assertNotSame( $updater5, $updater6 );
1781 }
1782
1783 protected function assertPreparedEditEquals(
1784 PreparedEdit $edit, PreparedEdit $edit2, $message = ''
1785 ) {
1786 // suppress differences caused by a clock tick between generating the two PreparedEdits
1787 $timestamp1 = $edit->getOutput()->getCacheTime();
1788 $timestamp2 = $edit2->getOutput()->getCacheTime();
1789 $this->assertEquals( $edit, $edit2, $message );
1790 $this->assertLessThan( 3, abs( $timestamp1 - $timestamp2 ), $message );
1791 }
1792
1793 protected function assertPreparedEditNotEquals(
1794 PreparedEdit $edit, PreparedEdit $edit2, $message = ''
1795 ) {
1796 $this->assertNotEquals( $edit, $edit2, $message );
1797 }
1798
1799 /**
1800 * This is just to confirm that WikiPage::updateRevisionOn() updates the
1801 * Title and LinkCache with the correct redirect value. Failing to do so
1802 * causes subtle test failures in extensions, such as Cognate (T283654)
1803 * and Echo (no task, but see code review of I12542fc899).
1804 */
1805 public function testUpdateSetsTitleRedirectCache() {
1806 // Get a title object without using the title cache
1807 $title = Title::makeTitleSafe( NS_MAIN, 'A new redirect' );
1808 $this->assertFalse( $title->isRedirect() );
1809
1810 $dbw = $this->getDb();
1811 $store = $this->getServiceContainer()->getRevisionStore();
1812 $page = $this->newPage( $title );
1813 $page->insertOn( $dbw );
1814
1815 $revision = new MutableRevisionRecord( $page );
1816 $revision->setContent(
1817 SlotRecord::MAIN,
1818 new WikitextContent( '#REDIRECT [[Target]]' )
1819 );
1820 $revision->setTimestamp( wfTimestampNow() );
1821 $revision->setComment( CommentStoreComment::newUnsavedComment( '' ) );
1822 $revision->setUser( $this->getTestUser()->getUser() );
1823
1824 $revision = $store->insertRevisionOn( $revision, $dbw );
1825
1826 $page->updateRevisionOn( $dbw, $revision );
1827 // check the title cache
1828 $this->assertTrue( $title->isRedirect() );
1829 // check the link cache with a fresh title
1830 $title = Title::makeTitleSafe( NS_MAIN, 'A new redirect' );
1831 $this->assertTrue( $title->isRedirect() );
1832 }
1833
1834 public function testGetTitle() {
1835 $page = $this->createPage( __METHOD__, 'whatever' );
1836
1837 $title = $page->getTitle();
1838 $this->assertSame( __METHOD__, $title->getText() );
1839
1840 $this->assertSame( $page->getId(), $title->getId() );
1841 $this->assertSame( $page->getNamespace(), $title->getNamespace() );
1842 $this->assertSame( $page->getDBkey(), $title->getDBkey() );
1843 $this->assertSame( $page->getWikiId(), $title->getWikiId() );
1844 $this->assertSame( $page->canExist(), $title->canExist() );
1845 }
1846
1847 public function testToPageRecord() {
1848 $page = $this->createPage( __METHOD__, 'whatever' );
1849 $record = $page->toPageRecord();
1850
1851 $this->assertSame( $page->getId(), $record->getId() );
1852 $this->assertSame( $page->getNamespace(), $record->getNamespace() );
1853 $this->assertSame( $page->getDBkey(), $record->getDBkey() );
1854 $this->assertSame( $page->getWikiId(), $record->getWikiId() );
1855 $this->assertSame( $page->canExist(), $record->canExist() );
1856
1857 $this->assertSame( $page->getLatest(), $record->getLatest() );
1858 $this->assertSame( $page->getTouched(), $record->getTouched() );
1859 $this->assertSame( $page->isNew(), $record->isNew() );
1860 $this->assertSame( $page->isRedirect(), $record->isRedirect() );
1861 }
1862
1863 public function testGetTouched() {
1864 $page = $this->createPage( __METHOD__, 'whatever' );
1865
1866 $touched = $this->getDb()->newSelectQueryBuilder()
1867 ->select( 'page_touched' )
1868 ->from( 'page' )
1869 ->where( [ 'page_id' => $page->getId() ] )
1870 ->fetchField();
1871 $touched = MWTimestamp::convert( TS_MW, $touched );
1872
1873 // Internal cache of the touched time was set after the page was created
1874 $this->assertSame( $touched, $page->getTouched() );
1875
1876 $touched = MWTimestamp::convert( TS_MW, MWTimestamp::convert( TS_UNIX, $touched ) + 100 );
1877 $page->getTitle()->invalidateCache( $touched );
1878
1879 // Re-load touched time
1880 $page = $this->newPage( $page->getTitle() );
1881 $this->assertSame( $touched, $page->getTouched() );
1882
1883 // Cause the latest revision to be loaded
1884 $page->getRevisionRecord();
1885
1886 // Make sure the internal cache of the touched time was not overwritten
1887 $this->assertSame( $touched, $page->getTouched() );
1888 }
1889
1890 }