Merge "selenium: invoke jobs to enforce eventual consistency"
[lhc/web/wiklou.git] / tests / phpunit / includes / page / WikiPageDbTestBase.php
1 <?php
2
3 use MediaWiki\Edit\PreparedEdit;
4 use MediaWiki\MediaWikiServices;
5 use MediaWiki\Storage\RevisionSlotsUpdate;
6 use PHPUnit\Framework\MockObject\MockObject;
7 use Wikimedia\TestingAccessWrapper;
8
9 /**
10 * @covers WikiPage
11 */
12 abstract class WikiPageDbTestBase extends MediaWikiLangTestCase {
13
14 private $pagesToDelete;
15
16 public function __construct( $name = null, array $data = [], $dataName = '' ) {
17 parent::__construct( $name, $data, $dataName );
18
19 $this->tablesUsed = array_merge(
20 $this->tablesUsed,
21 [ 'page',
22 'revision',
23 'redirect',
24 'archive',
25 'category',
26 'ip_changes',
27 'text',
28
29 'recentchanges',
30 'logging',
31
32 'page_props',
33 'pagelinks',
34 'categorylinks',
35 'langlinks',
36 'externallinks',
37 'imagelinks',
38 'templatelinks',
39 'iwlinks' ] );
40 }
41
42 protected function addCoreDBData() {
43 // Blank out. This would fail with a modified schema, and we don't need it.
44 }
45
46 /**
47 * @return int
48 */
49 abstract protected function getMcrMigrationStage();
50
51 /**
52 * @return string[]
53 */
54 abstract protected function getMcrTablesToReset();
55
56 protected function setUp() {
57 parent::setUp();
58
59 $this->tablesUsed += $this->getMcrTablesToReset();
60
61 $this->setMwGlobals( 'wgContentHandlerUseDB', $this->getContentHandlerUseDB() );
62 $this->setMwGlobals(
63 'wgMultiContentRevisionSchemaMigrationStage',
64 $this->getMcrMigrationStage()
65 );
66 $this->pagesToDelete = [];
67
68 $this->overrideMwServices();
69 }
70
71 protected function tearDown() {
72 foreach ( $this->pagesToDelete as $p ) {
73 /* @var $p WikiPage */
74
75 try {
76 if ( $p->exists() ) {
77 $p->doDeleteArticle( "testing done." );
78 }
79 } catch ( MWException $ex ) {
80 // fail silently
81 }
82 }
83 parent::tearDown();
84 }
85
86 abstract protected function getContentHandlerUseDB();
87
88 /**
89 * @param Title|string $title
90 * @param string|null $model
91 * @return WikiPage
92 */
93 private function newPage( $title, $model = null ) {
94 if ( is_string( $title ) ) {
95 $ns = $this->getDefaultWikitextNS();
96 $title = Title::newFromText( $title, $ns );
97 }
98
99 $p = new WikiPage( $title );
100
101 $this->pagesToDelete[] = $p;
102
103 return $p;
104 }
105
106 /**
107 * @param string|Title|WikiPage $page
108 * @param string|Content|Content[] $content
109 * @param int|null $model
110 *
111 * @return WikiPage
112 */
113 protected function createPage( $page, $content, $model = null, $user = null ) {
114 if ( is_string( $page ) || $page instanceof Title ) {
115 $page = $this->newPage( $page, $model );
116 }
117
118 if ( !$user ) {
119 $user = $this->getTestUser()->getUser();
120 }
121
122 if ( is_string( $content ) ) {
123 $content = ContentHandler::makeContent( $content, $page->getTitle(), $model );
124 }
125
126 if ( !is_array( $content ) ) {
127 $content = [ 'main' => $content ];
128 }
129
130 $updater = $page->newPageUpdater( $user );
131
132 foreach ( $content as $role => $cnt ) {
133 $updater->setContent( $role, $cnt );
134 }
135
136 $updater->saveRevision( CommentStoreComment::newUnsavedComment( "testing" ) );
137
138 return $page;
139 }
140
141 /**
142 * @covers WikiPage::prepareContentForEdit
143 */
144 public function testPrepareContentForEdit() {
145 $user = $this->getTestUser()->getUser();
146 $sysop = $this->getTestUser( [ 'sysop' ] )->getUser();
147
148 $page = $this->createPage( __METHOD__, __METHOD__, null, $user );
149 $title = $page->getTitle();
150
151 $content = ContentHandler::makeContent(
152 "[[Lorem ipsum]] dolor sit amet, consetetur sadipscing elitr, sed diam "
153 . " nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat.",
154 $title,
155 CONTENT_MODEL_WIKITEXT
156 );
157 $content2 = ContentHandler::makeContent(
158 "At vero eos et accusam et justo duo [[dolores]] et ea rebum. "
159 . "Stet clita kasd [[gubergren]], no sea takimata sanctus est. ~~~~",
160 $title,
161 CONTENT_MODEL_WIKITEXT
162 );
163
164 $edit = $page->prepareContentForEdit( $content, null, $user, null, false );
165
166 $this->assertInstanceOf(
167 ParserOptions::class,
168 $edit->popts,
169 "pops"
170 );
171 $this->assertContains( '</a>', $edit->output->getText(), "output" );
172 $this->assertContains(
173 'consetetur sadipscing elitr',
174 $edit->output->getText(),
175 "output"
176 );
177
178 $this->assertTrue( $content->equals( $edit->newContent ), "newContent field" );
179 $this->assertTrue( $content->equals( $edit->pstContent ), "pstContent field" );
180 $this->assertSame( $edit->output, $edit->output, "output field" );
181 $this->assertSame( $edit->popts, $edit->popts, "popts field" );
182 $this->assertSame( null, $edit->revid, "revid field" );
183
184 // Re-using the prepared info if possible
185 $sameEdit = $page->prepareContentForEdit( $content, null, $user, null, false );
186 $this->assertPreparedEditEquals( $edit, $sameEdit, 'equivalent PreparedEdit' );
187 $this->assertSame( $edit->pstContent, $sameEdit->pstContent, 're-use output' );
188 $this->assertSame( $edit->output, $sameEdit->output, 're-use output' );
189
190 // Not re-using the same PreparedEdit if not possible
191 $rev = $page->getRevision();
192 $edit2 = $page->prepareContentForEdit( $content2, null, $user, null, false );
193 $this->assertPreparedEditNotEquals( $edit, $edit2 );
194 $this->assertContains( 'At vero eos', $edit2->pstContent->serialize(), "content" );
195
196 // Check pre-safe transform
197 $this->assertContains( '[[gubergren]]', $edit2->pstContent->serialize() );
198 $this->assertNotContains( '~~~~', $edit2->pstContent->serialize() );
199
200 $edit3 = $page->prepareContentForEdit( $content2, null, $sysop, null, false );
201 $this->assertPreparedEditNotEquals( $edit2, $edit3 );
202
203 // TODO: test with passing revision, then same without revision.
204 }
205
206 /**
207 * @covers WikiPage::doEditUpdates
208 */
209 public function testDoEditUpdates() {
210 $user = $this->getTestUser()->getUser();
211
212 // NOTE: if site stats get out of whack and drop below 0,
213 // that causes a DB error during tear-down. So bump the
214 // numbers high enough to not drop below 0.
215 $siteStatsUpdate = SiteStatsUpdate::factory(
216 [ 'edits' => 1000, 'articles' => 1000, 'pages' => 1000 ]
217 );
218 $siteStatsUpdate->doUpdate();
219
220 $page = $this->createPage( __METHOD__, __METHOD__ );
221
222 $revision = new Revision(
223 [
224 'id' => 9989,
225 'page' => $page->getId(),
226 'title' => $page->getTitle(),
227 'comment' => __METHOD__,
228 'minor_edit' => true,
229 'text' => __METHOD__ . ' [[|foo]][[bar]]', // PST turns [[|foo]] into [[foo]]
230 'user' => $user->getId(),
231 'user_text' => $user->getName(),
232 'timestamp' => '20170707040404',
233 'content_model' => CONTENT_MODEL_WIKITEXT,
234 'content_format' => CONTENT_FORMAT_WIKITEXT,
235 ]
236 );
237
238 $page->doEditUpdates( $revision, $user );
239
240 // TODO: test various options; needs temporary hooks
241
242 $dbr = wfGetDB( DB_REPLICA );
243 $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $page->getId() ] );
244 $n = $res->numRows();
245 $res->free();
246
247 $this->assertEquals( 1, $n, 'pagelinks should contain only one link if PST was not applied' );
248 }
249
250 /**
251 * @covers WikiPage::doEditContent
252 * @covers WikiPage::prepareContentForEdit
253 */
254 public function testDoEditContent() {
255 $this->setMwGlobals( 'wgPageCreationLog', true );
256
257 $page = $this->newPage( __METHOD__ );
258 $title = $page->getTitle();
259
260 $user1 = $this->getTestUser()->getUser();
261 // Use the confirmed group for user2 to make sure the user is different
262 $user2 = $this->getTestUser( [ 'confirmed' ] )->getUser();
263
264 $content = ContentHandler::makeContent(
265 "[[Lorem ipsum]] dolor sit amet, consetetur sadipscing elitr, sed diam "
266 . " nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat.",
267 $title,
268 CONTENT_MODEL_WIKITEXT
269 );
270
271 $preparedEditBefore = $page->prepareContentForEdit( $content, null, $user1 );
272
273 $status = $page->doEditContent( $content, "[[testing]] 1", EDIT_NEW, false, $user1 );
274
275 $this->assertTrue( $status->isOK(), 'OK' );
276 $this->assertTrue( $status->value['new'], 'new' );
277 $this->assertNotNull( $status->value['revision'], 'revision' );
278 $this->assertSame( $status->value['revision']->getId(), $page->getRevision()->getId() );
279 $this->assertSame( $status->value['revision']->getSha1(), $page->getRevision()->getSha1() );
280 $this->assertTrue( $status->value['revision']->getContent()->equals( $content ), 'equals' );
281
282 $rev = $page->getRevision();
283 $preparedEditAfter = $page->prepareContentForEdit( $content, $rev, $user1 );
284
285 $this->assertNotNull( $rev->getRecentChange() );
286 $this->assertSame( $rev->getId(), (int)$rev->getRecentChange()->getAttribute( 'rc_this_oldid' ) );
287
288 // make sure that cached ParserOutput gets re-used throughout
289 $this->assertSame( $preparedEditBefore->output, $preparedEditAfter->output );
290
291 $id = $page->getId();
292
293 // Test page creation logging
294 $this->assertSelect(
295 'logging',
296 [ 'log_type', 'log_action' ],
297 [ 'log_page' => $id ],
298 [ [ 'create', 'create' ] ]
299 );
300
301 $this->assertTrue( $title->getArticleID() > 0, "Title object should have new page id" );
302 $this->assertTrue( $id > 0, "WikiPage should have new page id" );
303 $this->assertTrue( $title->exists(), "Title object should indicate that the page now exists" );
304 $this->assertTrue( $page->exists(), "WikiPage object should indicate that the page now exists" );
305
306 # ------------------------
307 $dbr = wfGetDB( DB_REPLICA );
308 $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $id ] );
309 $n = $res->numRows();
310 $res->free();
311
312 $this->assertEquals( 1, $n, 'pagelinks should contain one link from the page' );
313
314 # ------------------------
315 $page = new WikiPage( $title );
316
317 $retrieved = $page->getContent();
318 $this->assertTrue( $content->equals( $retrieved ), 'retrieved content doesn\'t equal original' );
319
320 # ------------------------
321 $page = new WikiPage( $title );
322
323 // try null edit, with a different user
324 $status = $page->doEditContent( $content, 'This changes nothing', EDIT_UPDATE, false, $user2 );
325 $this->assertTrue( $status->isOK(), 'OK' );
326 $this->assertFalse( $status->value['new'], 'new' );
327 $this->assertNull( $status->value['revision'], 'revision' );
328 $this->assertNotNull( $page->getRevision() );
329 $this->assertTrue( $page->getRevision()->getContent()->equals( $content ), 'equals' );
330
331 # ------------------------
332 $content = ContentHandler::makeContent(
333 "At vero eos et accusam et justo duo [[dolores]] et ea rebum. "
334 . "Stet clita kasd [[gubergren]], no sea takimata sanctus est. ~~~~",
335 $title,
336 CONTENT_MODEL_WIKITEXT
337 );
338
339 $status = $page->doEditContent( $content, "testing 2", EDIT_UPDATE );
340 $this->assertTrue( $status->isOK(), 'OK' );
341 $this->assertFalse( $status->value['new'], 'new' );
342 $this->assertNotNull( $status->value['revision'], 'revision' );
343 $this->assertSame( $status->value['revision']->getId(), $page->getRevision()->getId() );
344 $this->assertSame( $status->value['revision']->getSha1(), $page->getRevision()->getSha1() );
345 $this->assertFalse(
346 $status->value['revision']->getContent()->equals( $content ),
347 'not equals (PST must substitute signature)'
348 );
349
350 $rev = $page->getRevision();
351 $this->assertNotNull( $rev->getRecentChange() );
352 $this->assertSame( $rev->getId(), (int)$rev->getRecentChange()->getAttribute( 'rc_this_oldid' ) );
353
354 # ------------------------
355 $page = new WikiPage( $title );
356
357 $retrieved = $page->getContent();
358 $newText = $retrieved->serialize();
359 $this->assertContains( '[[gubergren]]', $newText, 'New text must replace old text.' );
360 $this->assertNotContains( '~~~~', $newText, 'PST must substitute signature.' );
361
362 # ------------------------
363 $dbr = wfGetDB( DB_REPLICA );
364 $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $id ] );
365 $n = $res->numRows();
366 $res->free();
367
368 $this->assertEquals( 2, $n, 'pagelinks should contain two links from the page' );
369 }
370
371 /**
372 * @covers WikiPage::doEditContent
373 */
374 public function testDoEditContent_twice() {
375 $title = Title::newFromText( __METHOD__ );
376 $page = WikiPage::factory( $title );
377 $content = ContentHandler::makeContent( '$1 van $2', $title );
378
379 // Make sure we can do the exact same save twice.
380 // This tests checks that internal caches are reset as appropriate.
381 $status1 = $page->doEditContent( $content, __METHOD__ );
382 $status2 = $page->doEditContent( $content, __METHOD__ );
383
384 $this->assertTrue( $status1->isOK(), 'OK' );
385 $this->assertTrue( $status2->isOK(), 'OK' );
386
387 $this->assertTrue( isset( $status1->value['revision'] ), 'OK' );
388 $this->assertFalse( isset( $status2->value['revision'] ), 'OK' );
389 }
390
391 /**
392 * Undeletion is covered in PageArchiveTest::testUndeleteRevisions()
393 * TODO: Revision deletion
394 *
395 * @covers WikiPage::doDeleteArticle
396 * @covers WikiPage::doDeleteArticleReal
397 */
398 public function testDoDeleteArticle() {
399 $page = $this->createPage(
400 __METHOD__,
401 "[[original text]] foo",
402 CONTENT_MODEL_WIKITEXT
403 );
404 $id = $page->getId();
405
406 $page->doDeleteArticle( "testing deletion" );
407
408 $this->assertFalse(
409 $page->getTitle()->getArticleID() > 0,
410 "Title object should now have page id 0"
411 );
412 $this->assertFalse( $page->getId() > 0, "WikiPage should now have page id 0" );
413 $this->assertFalse(
414 $page->exists(),
415 "WikiPage::exists should return false after page was deleted"
416 );
417 $this->assertNull(
418 $page->getContent(),
419 "WikiPage::getContent should return null after page was deleted"
420 );
421
422 $t = Title::newFromText( $page->getTitle()->getPrefixedText() );
423 $this->assertFalse(
424 $t->exists(),
425 "Title::exists should return false after page was deleted"
426 );
427
428 // Run the job queue
429 JobQueueGroup::destroySingletons();
430 $jobs = new RunJobs;
431 $jobs->loadParamsAndArgs( null, [ 'quiet' => true ], null );
432 $jobs->execute();
433
434 # ------------------------
435 $dbr = wfGetDB( DB_REPLICA );
436 $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $id ] );
437 $n = $res->numRows();
438 $res->free();
439
440 $this->assertEquals( 0, $n, 'pagelinks should contain no more links from the page' );
441 }
442
443 /**
444 * @covers WikiPage::doDeleteArticleReal
445 */
446 public function testDoDeleteArticleReal_user0() {
447 $page = $this->createPage(
448 __METHOD__,
449 "[[original text]] foo",
450 CONTENT_MODEL_WIKITEXT
451 );
452 $id = $page->getId();
453
454 $errorStack = '';
455 $status = $page->doDeleteArticleReal(
456 /* reason */ "testing user 0 deletion",
457 /* suppress */ false,
458 /* unused 1 */ null,
459 /* unused 2 */ null,
460 /* errorStack */ $errorStack,
461 null
462 );
463 $logId = $status->getValue();
464 $actorQuery = ActorMigration::newMigration()->getJoin( 'log_user' );
465 $this->assertSelect(
466 [ 'logging' ] + $actorQuery['tables'], /* table */
467 [
468 'log_type',
469 'log_action',
470 'log_comment',
471 'log_user' => $actorQuery['fields']['log_user'],
472 'log_user_text' => $actorQuery['fields']['log_user_text'],
473 'log_namespace',
474 'log_title',
475 ],
476 [ 'log_id' => $logId ],
477 [ [
478 'delete',
479 'delete',
480 'testing user 0 deletion',
481 '0',
482 '127.0.0.1',
483 (string)$page->getTitle()->getNamespace(),
484 $page->getTitle()->getDBkey(),
485 ] ],
486 [],
487 $actorQuery['joins']
488 );
489 }
490
491 /**
492 * @covers WikiPage::doDeleteArticleReal
493 */
494 public function testDoDeleteArticleReal_userSysop() {
495 $page = $this->createPage(
496 __METHOD__,
497 "[[original text]] foo",
498 CONTENT_MODEL_WIKITEXT
499 );
500 $id = $page->getId();
501
502 $user = $this->getTestSysop()->getUser();
503 $errorStack = '';
504 $status = $page->doDeleteArticleReal(
505 /* reason */ "testing sysop deletion",
506 /* suppress */ false,
507 /* unused 1 */ null,
508 /* unused 2 */ null,
509 /* errorStack */ $errorStack,
510 $user
511 );
512 $logId = $status->getValue();
513 $actorQuery = ActorMigration::newMigration()->getJoin( 'log_user' );
514 $this->assertSelect(
515 [ 'logging' ] + $actorQuery['tables'], /* table */
516 [
517 'log_type',
518 'log_action',
519 'log_comment',
520 'log_user' => $actorQuery['fields']['log_user'],
521 'log_user_text' => $actorQuery['fields']['log_user_text'],
522 'log_namespace',
523 'log_title',
524 ],
525 [ 'log_id' => $logId ],
526 [ [
527 'delete',
528 'delete',
529 'testing sysop deletion',
530 (string)$user->getId(),
531 $user->getName(),
532 (string)$page->getTitle()->getNamespace(),
533 $page->getTitle()->getDBkey(),
534 ] ],
535 [],
536 $actorQuery['joins']
537 );
538 }
539
540 /**
541 * TODO: Test more stuff about suppression.
542 *
543 * @covers WikiPage::doDeleteArticleReal
544 */
545 public function testDoDeleteArticleReal_suppress() {
546 $page = $this->createPage(
547 __METHOD__,
548 "[[original text]] foo",
549 CONTENT_MODEL_WIKITEXT
550 );
551 $id = $page->getId();
552
553 $user = $this->getTestSysop()->getUser();
554 $errorStack = '';
555 $status = $page->doDeleteArticleReal(
556 /* reason */ "testing deletion",
557 /* suppress */ true,
558 /* unused 1 */ null,
559 /* unused 2 */ null,
560 /* errorStack */ $errorStack,
561 $user
562 );
563 $logId = $status->getValue();
564 $actorQuery = ActorMigration::newMigration()->getJoin( 'log_user' );
565 $this->assertSelect(
566 [ 'logging' ] + $actorQuery['tables'], /* table */
567 [
568 'log_type',
569 'log_action',
570 'log_comment',
571 'log_user' => $actorQuery['fields']['log_user'],
572 'log_user_text' => $actorQuery['fields']['log_user_text'],
573 'log_namespace',
574 'log_title',
575 ],
576 [ 'log_id' => $logId ],
577 [ [
578 'suppress',
579 'delete',
580 'testing deletion',
581 (string)$user->getId(),
582 $user->getName(),
583 (string)$page->getTitle()->getNamespace(),
584 $page->getTitle()->getDBkey(),
585 ] ],
586 [],
587 $actorQuery['joins']
588 );
589
590 $this->assertNull(
591 $page->getContent( Revision::FOR_PUBLIC ),
592 "WikiPage::getContent should return null after the page was suppressed for general users"
593 );
594
595 $this->assertNull(
596 $page->getContent( Revision::FOR_THIS_USER, null ),
597 "WikiPage::getContent should return null after the page was suppressed for user zero"
598 );
599
600 $this->assertNull(
601 $page->getContent( Revision::FOR_THIS_USER, $user ),
602 "WikiPage::getContent should return null after the page was suppressed even for a sysop"
603 );
604 }
605
606 /**
607 * @covers WikiPage::doDeleteUpdates
608 */
609 public function testDoDeleteUpdates() {
610 $user = $this->getTestUser()->getUser();
611 $page = $this->createPage(
612 __METHOD__,
613 "[[original text]] foo",
614 CONTENT_MODEL_WIKITEXT
615 );
616 $id = $page->getId();
617 $page->loadPageData(); // make sure the current revision is cached.
618
619 // Similar to MovePage logic
620 wfGetDB( DB_MASTER )->delete( 'page', [ 'page_id' => $id ], __METHOD__ );
621 $page->doDeleteUpdates( $page->getId(), $page->getContent(), $page->getRevision(), $user );
622
623 // Run the job queue
624 JobQueueGroup::destroySingletons();
625 $jobs = new RunJobs;
626 $jobs->loadParamsAndArgs( null, [ 'quiet' => true ], null );
627 $jobs->execute();
628
629 # ------------------------
630 $dbr = wfGetDB( DB_REPLICA );
631 $res = $dbr->select( 'pagelinks', '*', [ 'pl_from' => $id ] );
632 $n = $res->numRows();
633 $res->free();
634
635 $this->assertEquals( 0, $n, 'pagelinks should contain no more links from the page' );
636 }
637
638 /**
639 * @param string $name
640 *
641 * @return ContentHandler
642 */
643 protected function defineMockContentModelForUpdateTesting( $name ) {
644 /** @var ContentHandler|MockObject $handler */
645 $handler = $this->getMockBuilder( TextContentHandler::class )
646 ->setConstructorArgs( [ $name ] )
647 ->setMethods(
648 [ 'getSecondaryDataUpdates', 'getDeletionUpdates', 'unserializeContent' ]
649 )
650 ->getMock();
651
652 $dataUpdate = new MWCallableUpdate( 'time' );
653 $dataUpdate->_name = "$name data update";
654
655 $deletionUpdate = new MWCallableUpdate( 'time' );
656 $deletionUpdate->_name = "$name deletion update";
657
658 $handler->method( 'getSecondaryDataUpdates' )->willReturn( [ $dataUpdate ] );
659 $handler->method( 'getDeletionUpdates' )->willReturn( [ $deletionUpdate ] );
660 $handler->method( 'unserializeContent' )->willReturnCallback(
661 function ( $text ) use ( $handler ) {
662 return $this->createMockContent( $handler, $text );
663 }
664 );
665
666 $this->mergeMwGlobalArrayValue(
667 'wgContentHandlers', [
668 $name => function () use ( $handler ){
669 return $handler;
670 }
671 ]
672 );
673
674 return $handler;
675 }
676
677 /**
678 * @param ContentHandler $handler
679 * @param string $text
680 *
681 * @return Content
682 */
683 protected function createMockContent( ContentHandler $handler, $text ) {
684 /** @var Content|MockObject $content */
685 $content = $this->getMockBuilder( TextContent::class )
686 ->setConstructorArgs( [ $text ] )
687 ->setMethods( [ 'getModel', 'getContentHandler' ] )
688 ->getMock();
689
690 $content->method( 'getModel' )->willReturn( $handler->getModelID() );
691 $content->method( 'getContentHandler' )->willReturn( $handler );
692
693 return $content;
694 }
695
696 public function testGetDeletionUpdates() {
697 $m1 = $this->defineMockContentModelForUpdateTesting( 'M1' );
698
699 $mainContent1 = $this->createMockContent( $m1, 'main 1' );
700
701 $page = new WikiPage( Title::newFromText( __METHOD__ ) );
702 $page = $this->createPage(
703 $page,
704 [ 'main' => $mainContent1 ]
705 );
706
707 $dataUpdates = $page->getDeletionUpdates( $page->getRevisionRecord() );
708 $this->assertNotEmpty( $dataUpdates );
709
710 $updateNames = array_map( function ( $du ) {
711 return isset( $du->_name ) ? $du->_name : get_class( $du );
712 }, $dataUpdates );
713
714 $this->assertContains( LinksDeletionUpdate::class, $updateNames );
715 $this->assertContains( 'M1 deletion update', $updateNames );
716 }
717
718 /**
719 * @covers WikiPage::getRevision
720 */
721 public function testGetRevision() {
722 $page = $this->newPage( __METHOD__ );
723
724 $rev = $page->getRevision();
725 $this->assertNull( $rev );
726
727 # -----------------
728 $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT );
729
730 $rev = $page->getRevision();
731
732 $this->assertEquals( $page->getLatest(), $rev->getId() );
733 $this->assertEquals( "some text", $rev->getContent()->getNativeData() );
734 }
735
736 /**
737 * @covers WikiPage::getContent
738 */
739 public function testGetContent() {
740 $page = $this->newPage( __METHOD__ );
741
742 $content = $page->getContent();
743 $this->assertNull( $content );
744
745 # -----------------
746 $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT );
747
748 $content = $page->getContent();
749 $this->assertEquals( "some text", $content->getNativeData() );
750 }
751
752 /**
753 * @covers WikiPage::exists
754 */
755 public function testExists() {
756 $page = $this->newPage( __METHOD__ );
757 $this->assertFalse( $page->exists() );
758
759 # -----------------
760 $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT );
761 $this->assertTrue( $page->exists() );
762
763 $page = new WikiPage( $page->getTitle() );
764 $this->assertTrue( $page->exists() );
765
766 # -----------------
767 $page->doDeleteArticle( "done testing" );
768 $this->assertFalse( $page->exists() );
769
770 $page = new WikiPage( $page->getTitle() );
771 $this->assertFalse( $page->exists() );
772 }
773
774 public function provideHasViewableContent() {
775 return [
776 [ 'WikiPageTest_testHasViewableContent', false, true ],
777 [ 'Special:WikiPageTest_testHasViewableContent', false ],
778 [ 'MediaWiki:WikiPageTest_testHasViewableContent', false ],
779 [ 'Special:Userlogin', true ],
780 [ 'MediaWiki:help', true ],
781 ];
782 }
783
784 /**
785 * @dataProvider provideHasViewableContent
786 * @covers WikiPage::hasViewableContent
787 */
788 public function testHasViewableContent( $title, $viewable, $create = false ) {
789 $page = $this->newPage( $title );
790 $this->assertEquals( $viewable, $page->hasViewableContent() );
791
792 if ( $create ) {
793 $this->createPage( $page, "some text", CONTENT_MODEL_WIKITEXT );
794 $this->assertTrue( $page->hasViewableContent() );
795
796 $page = new WikiPage( $page->getTitle() );
797 $this->assertTrue( $page->hasViewableContent() );
798 }
799 }
800
801 public function provideGetRedirectTarget() {
802 return [
803 [ 'WikiPageTest_testGetRedirectTarget_1', CONTENT_MODEL_WIKITEXT, "hello world", null ],
804 [
805 'WikiPageTest_testGetRedirectTarget_2',
806 CONTENT_MODEL_WIKITEXT,
807 "#REDIRECT [[hello world]]",
808 "Hello world"
809 ],
810 ];
811 }
812
813 /**
814 * @dataProvider provideGetRedirectTarget
815 * @covers WikiPage::getRedirectTarget
816 */
817 public function testGetRedirectTarget( $title, $model, $text, $target ) {
818 $this->setMwGlobals( [
819 'wgCapitalLinks' => true,
820 ] );
821
822 $page = $this->createPage( $title, $text, $model );
823
824 # sanity check, because this test seems to fail for no reason for some people.
825 $c = $page->getContent();
826 $this->assertEquals( WikitextContent::class, get_class( $c ) );
827
828 # now, test the actual redirect
829 $t = $page->getRedirectTarget();
830 $this->assertEquals( $target, is_null( $t ) ? null : $t->getPrefixedText() );
831 }
832
833 /**
834 * @dataProvider provideGetRedirectTarget
835 * @covers WikiPage::isRedirect
836 */
837 public function testIsRedirect( $title, $model, $text, $target ) {
838 $page = $this->createPage( $title, $text, $model );
839 $this->assertEquals( !is_null( $target ), $page->isRedirect() );
840 }
841
842 public function provideIsCountable() {
843 return [
844
845 // any
846 [ 'WikiPageTest_testIsCountable',
847 CONTENT_MODEL_WIKITEXT,
848 '',
849 'any',
850 true
851 ],
852 [ 'WikiPageTest_testIsCountable',
853 CONTENT_MODEL_WIKITEXT,
854 'Foo',
855 'any',
856 true
857 ],
858
859 // link
860 [ 'WikiPageTest_testIsCountable',
861 CONTENT_MODEL_WIKITEXT,
862 'Foo',
863 'link',
864 false
865 ],
866 [ 'WikiPageTest_testIsCountable',
867 CONTENT_MODEL_WIKITEXT,
868 'Foo [[bar]]',
869 'link',
870 true
871 ],
872
873 // redirects
874 [ 'WikiPageTest_testIsCountable',
875 CONTENT_MODEL_WIKITEXT,
876 '#REDIRECT [[bar]]',
877 'any',
878 false
879 ],
880 [ 'WikiPageTest_testIsCountable',
881 CONTENT_MODEL_WIKITEXT,
882 '#REDIRECT [[bar]]',
883 'link',
884 false
885 ],
886
887 // not a content namespace
888 [ 'Talk:WikiPageTest_testIsCountable',
889 CONTENT_MODEL_WIKITEXT,
890 'Foo',
891 'any',
892 false
893 ],
894 [ 'Talk:WikiPageTest_testIsCountable',
895 CONTENT_MODEL_WIKITEXT,
896 'Foo [[bar]]',
897 'link',
898 false
899 ],
900
901 // not a content namespace, different model
902 [ 'MediaWiki:WikiPageTest_testIsCountable.js',
903 null,
904 'Foo',
905 'any',
906 false
907 ],
908 [ 'MediaWiki:WikiPageTest_testIsCountable.js',
909 null,
910 'Foo [[bar]]',
911 'link',
912 false
913 ],
914 ];
915 }
916
917 /**
918 * @dataProvider provideIsCountable
919 * @covers WikiPage::isCountable
920 */
921 public function testIsCountable( $title, $model, $text, $mode, $expected ) {
922 global $wgContentHandlerUseDB;
923
924 $this->setMwGlobals( 'wgArticleCountMethod', $mode );
925
926 $title = Title::newFromText( $title );
927
928 if ( !$wgContentHandlerUseDB
929 && $model
930 && ContentHandler::getDefaultModelFor( $title ) != $model
931 ) {
932 $this->markTestSkipped( "Can not use non-default content model $model for "
933 . $title->getPrefixedDBkey() . " with \$wgContentHandlerUseDB disabled." );
934 }
935
936 $page = $this->createPage( $title, $text, $model );
937
938 $editInfo = $page->prepareContentForEdit( $page->getContent() );
939
940 $v = $page->isCountable();
941 $w = $page->isCountable( $editInfo );
942
943 $this->assertEquals(
944 $expected,
945 $v,
946 "isCountable( null ) returned unexpected value " . var_export( $v, true )
947 . " instead of " . var_export( $expected, true )
948 . " in mode `$mode` for text \"$text\""
949 );
950
951 $this->assertEquals(
952 $expected,
953 $w,
954 "isCountable( \$editInfo ) returned unexpected value " . var_export( $v, true )
955 . " instead of " . var_export( $expected, true )
956 . " in mode `$mode` for text \"$text\""
957 );
958 }
959
960 public function provideGetParserOutput() {
961 return [
962 [
963 CONTENT_MODEL_WIKITEXT,
964 "hello ''world''\n",
965 "<div class=\"mw-parser-output\"><p>hello <i>world</i></p></div>"
966 ],
967 // @todo more...?
968 ];
969 }
970
971 /**
972 * @dataProvider provideGetParserOutput
973 * @covers WikiPage::getParserOutput
974 */
975 public function testGetParserOutput( $model, $text, $expectedHtml ) {
976 $page = $this->createPage( __METHOD__, $text, $model );
977
978 $opt = $page->makeParserOptions( 'canonical' );
979 $po = $page->getParserOutput( $opt );
980 $text = $po->getText();
981
982 $text = trim( preg_replace( '/<!--.*?-->/sm', '', $text ) ); # strip injected comments
983 $text = preg_replace( '!\s*(</p>|</div>)!sm', '\1', $text ); # don't let tidy confuse us
984
985 $this->assertEquals( $expectedHtml, $text );
986
987 return $po;
988 }
989
990 /**
991 * @covers WikiPage::getParserOutput
992 */
993 public function testGetParserOutput_nonexisting() {
994 $page = new WikiPage( Title::newFromText( __METHOD__ ) );
995
996 $opt = new ParserOptions();
997 $po = $page->getParserOutput( $opt );
998
999 $this->assertFalse( $po, "getParserOutput() shall return false for non-existing pages." );
1000 }
1001
1002 /**
1003 * @covers WikiPage::getParserOutput
1004 */
1005 public function testGetParserOutput_badrev() {
1006 $page = $this->createPage( __METHOD__, 'dummy', CONTENT_MODEL_WIKITEXT );
1007
1008 $opt = new ParserOptions();
1009 $po = $page->getParserOutput( $opt, $page->getLatest() + 1234 );
1010
1011 // @todo would be neat to also test deleted revision
1012
1013 $this->assertFalse( $po, "getParserOutput() shall return false for non-existing revisions." );
1014 }
1015
1016 public static $sections =
1017
1018 "Intro
1019
1020 == stuff ==
1021 hello world
1022
1023 == test ==
1024 just a test
1025
1026 == foo ==
1027 more stuff
1028 ";
1029
1030 public function dataReplaceSection() {
1031 // NOTE: assume the Help namespace to contain wikitext
1032 return [
1033 [ 'Help:WikiPageTest_testReplaceSection',
1034 CONTENT_MODEL_WIKITEXT,
1035 self::$sections,
1036 "0",
1037 "No more",
1038 null,
1039 trim( preg_replace( '/^Intro/sm', 'No more', self::$sections ) )
1040 ],
1041 [ 'Help:WikiPageTest_testReplaceSection',
1042 CONTENT_MODEL_WIKITEXT,
1043 self::$sections,
1044 "",
1045 "No more",
1046 null,
1047 "No more"
1048 ],
1049 [ 'Help:WikiPageTest_testReplaceSection',
1050 CONTENT_MODEL_WIKITEXT,
1051 self::$sections,
1052 "2",
1053 "== TEST ==\nmore fun",
1054 null,
1055 trim( preg_replace( '/^== test ==.*== foo ==/sm',
1056 "== TEST ==\nmore fun\n\n== foo ==",
1057 self::$sections ) )
1058 ],
1059 [ 'Help:WikiPageTest_testReplaceSection',
1060 CONTENT_MODEL_WIKITEXT,
1061 self::$sections,
1062 "8",
1063 "No more",
1064 null,
1065 trim( self::$sections )
1066 ],
1067 [ 'Help:WikiPageTest_testReplaceSection',
1068 CONTENT_MODEL_WIKITEXT,
1069 self::$sections,
1070 "new",
1071 "No more",
1072 "New",
1073 trim( self::$sections ) . "\n\n== New ==\n\nNo more"
1074 ],
1075 ];
1076 }
1077
1078 /**
1079 * @dataProvider dataReplaceSection
1080 * @covers WikiPage::replaceSectionContent
1081 */
1082 public function testReplaceSectionContent( $title, $model, $text, $section,
1083 $with, $sectionTitle, $expected
1084 ) {
1085 $page = $this->createPage( $title, $text, $model );
1086
1087 $content = ContentHandler::makeContent( $with, $page->getTitle(), $page->getContentModel() );
1088 $c = $page->replaceSectionContent( $section, $content, $sectionTitle );
1089
1090 $this->assertEquals( $expected, is_null( $c ) ? null : trim( $c->getNativeData() ) );
1091 }
1092
1093 /**
1094 * @dataProvider dataReplaceSection
1095 * @covers WikiPage::replaceSectionAtRev
1096 */
1097 public function testReplaceSectionAtRev( $title, $model, $text, $section,
1098 $with, $sectionTitle, $expected
1099 ) {
1100 $page = $this->createPage( $title, $text, $model );
1101 $baseRevId = $page->getLatest();
1102
1103 $content = ContentHandler::makeContent( $with, $page->getTitle(), $page->getContentModel() );
1104 $c = $page->replaceSectionAtRev( $section, $content, $sectionTitle, $baseRevId );
1105
1106 $this->assertEquals( $expected, is_null( $c ) ? null : trim( $c->getNativeData() ) );
1107 }
1108
1109 /**
1110 * @covers WikiPage::getOldestRevision
1111 */
1112 public function testGetOldestRevision() {
1113 $page = $this->newPage( __METHOD__ );
1114 $page->doEditContent(
1115 new WikitextContent( 'one' ),
1116 "first edit",
1117 EDIT_NEW
1118 );
1119 $rev1 = $page->getRevision();
1120
1121 $page = new WikiPage( $page->getTitle() );
1122 $page->doEditContent(
1123 new WikitextContent( 'two' ),
1124 "second edit",
1125 EDIT_UPDATE
1126 );
1127
1128 $page = new WikiPage( $page->getTitle() );
1129 $page->doEditContent(
1130 new WikitextContent( 'three' ),
1131 "third edit",
1132 EDIT_UPDATE
1133 );
1134
1135 // sanity check
1136 $this->assertNotEquals(
1137 $rev1->getId(),
1138 $page->getRevision()->getId(),
1139 '$page->getRevision()->getId()'
1140 );
1141
1142 // actual test
1143 $this->assertEquals(
1144 $rev1->getId(),
1145 $page->getOldestRevision()->getId(),
1146 '$page->getOldestRevision()->getId()'
1147 );
1148 }
1149
1150 /**
1151 * @covers WikiPage::doRollback
1152 * @covers WikiPage::commitRollback
1153 */
1154 public function testDoRollback() {
1155 // FIXME: fails under postgres
1156 $this->markTestSkippedIfDbType( 'postgres' );
1157
1158 $admin = $this->getTestSysop()->getUser();
1159 $user1 = $this->getTestUser()->getUser();
1160 // Use the confirmed group for user2 to make sure the user is different
1161 $user2 = $this->getTestUser( [ 'confirmed' ] )->getUser();
1162
1163 // make sure we can test autopatrolling
1164 $this->setMwGlobals( 'wgUseRCPatrol', true );
1165
1166 // TODO: MCR: test rollback of multiple slots!
1167 $page = $this->newPage( __METHOD__ );
1168
1169 // Make some edits
1170 $text = "one";
1171 $status1 = $page->doEditContent( ContentHandler::makeContent( $text, $page->getTitle() ),
1172 "section one", EDIT_NEW, false, $admin );
1173
1174 $text .= "\n\ntwo";
1175 $status2 = $page->doEditContent( ContentHandler::makeContent( $text, $page->getTitle() ),
1176 "adding section two", 0, false, $user1 );
1177
1178 $text .= "\n\nthree";
1179 $status3 = $page->doEditContent( ContentHandler::makeContent( $text, $page->getTitle() ),
1180 "adding section three", 0, false, $user2 );
1181
1182 /** @var Revision $rev1 */
1183 /** @var Revision $rev2 */
1184 /** @var Revision $rev3 */
1185 $rev1 = $status1->getValue()['revision'];
1186 $rev2 = $status2->getValue()['revision'];
1187 $rev3 = $status3->getValue()['revision'];
1188
1189 /**
1190 * We are having issues with doRollback spuriously failing. Apparently
1191 * the last revision somehow goes missing or not committed under some
1192 * circumstances. So, make sure the revisions have the correct usernames.
1193 */
1194 $this->assertEquals( 3, Revision::countByPageId( wfGetDB( DB_REPLICA ), $page->getId() ) );
1195 $this->assertEquals( $admin->getName(), $rev1->getUserText() );
1196 $this->assertEquals( $user1->getName(), $rev2->getUserText() );
1197 $this->assertEquals( $user2->getName(), $rev3->getUserText() );
1198
1199 // Now, try the actual rollback
1200 $token = $admin->getEditToken( 'rollback' );
1201 $rollbackErrors = $page->doRollback(
1202 $user2->getName(),
1203 "testing rollback",
1204 $token,
1205 false,
1206 $resultDetails,
1207 $admin
1208 );
1209
1210 if ( $rollbackErrors ) {
1211 $this->fail(
1212 "Rollback failed:\n" .
1213 print_r( $rollbackErrors, true ) . ";\n" .
1214 print_r( $resultDetails, true )
1215 );
1216 }
1217
1218 $page = new WikiPage( $page->getTitle() );
1219 $this->assertEquals( $rev2->getSha1(), $page->getRevision()->getSha1(),
1220 "rollback did not revert to the correct revision" );
1221 $this->assertEquals( "one\n\ntwo", $page->getContent()->getNativeData() );
1222
1223 $rc = MediaWikiServices::getInstance()->getRevisionStore()->getRecentChange(
1224 $page->getRevision()->getRevisionRecord()
1225 );
1226
1227 $this->assertNotNull( $rc, 'RecentChanges entry' );
1228 $this->assertEquals(
1229 RecentChange::PRC_AUTOPATROLLED,
1230 $rc->getAttribute( 'rc_patrolled' ),
1231 'rc_patrolled'
1232 );
1233
1234 // TODO: MCR: assert origin once we write slot data
1235 // $mainSlot = $page->getRevision()->getRevisionRecord()->getSlot( 'main' );
1236 // $this->assertTrue( $mainSlot->isInherited(), 'isInherited' );
1237 // $this->assertSame( $rev2->getId(), $mainSlot->getOrigin(), 'getOrigin' );
1238 }
1239
1240 /**
1241 * @covers WikiPage::doRollback
1242 * @covers WikiPage::commitRollback
1243 */
1244 public function testDoRollbackFailureSameContent() {
1245 $admin = $this->getTestSysop()->getUser();
1246
1247 $text = "one";
1248 $page = $this->newPage( __METHOD__ );
1249 $page->doEditContent(
1250 ContentHandler::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT ),
1251 "section one",
1252 EDIT_NEW,
1253 false,
1254 $admin
1255 );
1256 $rev1 = $page->getRevision();
1257
1258 $user1 = $this->getTestUser( [ 'sysop' ] )->getUser();
1259 $text .= "\n\ntwo";
1260 $page = new WikiPage( $page->getTitle() );
1261 $page->doEditContent(
1262 ContentHandler::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT ),
1263 "adding section two",
1264 0,
1265 false,
1266 $user1
1267 );
1268
1269 # now, do a the rollback from the same user was doing the edit before
1270 $resultDetails = [];
1271 $token = $user1->getEditToken( 'rollback' );
1272 $errors = $page->doRollback(
1273 $user1->getName(),
1274 "testing revert same user",
1275 $token,
1276 false,
1277 $resultDetails,
1278 $admin
1279 );
1280
1281 $this->assertEquals( [], $errors, "Rollback failed same user" );
1282
1283 # now, try the rollback
1284 $resultDetails = [];
1285 $token = $admin->getEditToken( 'rollback' );
1286 $errors = $page->doRollback(
1287 $user1->getName(),
1288 "testing revert",
1289 $token,
1290 false,
1291 $resultDetails,
1292 $admin
1293 );
1294
1295 $this->assertEquals(
1296 [
1297 [
1298 'alreadyrolled',
1299 __METHOD__,
1300 $user1->getName(),
1301 $admin->getName(),
1302 ],
1303 ],
1304 $errors,
1305 "Rollback not failed"
1306 );
1307
1308 $page = new WikiPage( $page->getTitle() );
1309 $this->assertEquals( $rev1->getSha1(), $page->getRevision()->getSha1(),
1310 "rollback did not revert to the correct revision" );
1311 $this->assertEquals( "one", $page->getContent()->getNativeData() );
1312 }
1313
1314 /**
1315 * Tests tagging for edits that do rollback action
1316 * @covers WikiPage::doRollback
1317 */
1318 public function testDoRollbackTagging() {
1319 if ( !in_array( 'mw-rollback', ChangeTags::getSoftwareTags() ) ) {
1320 $this->markTestSkipped( 'Rollback tag deactivated, skipped the test.' );
1321 }
1322
1323 $admin = new User();
1324 $admin->setName( 'Administrator' );
1325 $admin->addToDatabase();
1326
1327 $text = 'First line';
1328 $page = $this->newPage( 'WikiPageTest_testDoRollbackTagging' );
1329 $page->doEditContent(
1330 ContentHandler::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT ),
1331 'Added first line',
1332 EDIT_NEW,
1333 false,
1334 $admin
1335 );
1336
1337 $secondUser = new User();
1338 $secondUser->setName( '92.65.217.32' );
1339 $text .= '\n\nSecond line';
1340 $page = new WikiPage( $page->getTitle() );
1341 $page->doEditContent(
1342 ContentHandler::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT ),
1343 'Adding second line',
1344 0,
1345 false,
1346 $secondUser
1347 );
1348
1349 // Now, try the rollback
1350 $admin->addGroup( 'sysop' ); // Make the test user a sysop
1351 $token = $admin->getEditToken( 'rollback' );
1352 $errors = $page->doRollback(
1353 $secondUser->getName(),
1354 'testing rollback',
1355 $token,
1356 false,
1357 $resultDetails,
1358 $admin
1359 );
1360
1361 // If doRollback completed without errors
1362 if ( $errors === [] ) {
1363 $tags = $resultDetails[ 'tags' ];
1364 $this->assertContains( 'mw-rollback', $tags );
1365 }
1366 }
1367
1368 public function provideGetAutoDeleteReason() {
1369 return [
1370 [
1371 [],
1372 false,
1373 false
1374 ],
1375
1376 [
1377 [
1378 [ "first edit", null ],
1379 ],
1380 "/first edit.*only contributor/",
1381 false
1382 ],
1383
1384 [
1385 [
1386 [ "first edit", null ],
1387 [ "second edit", null ],
1388 ],
1389 "/second edit.*only contributor/",
1390 true
1391 ],
1392
1393 [
1394 [
1395 [ "first edit", "127.0.2.22" ],
1396 [ "second edit", "127.0.3.33" ],
1397 ],
1398 "/second edit/",
1399 true
1400 ],
1401
1402 [
1403 [
1404 [
1405 "first edit: "
1406 . "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam "
1407 . " nonumy eirmod tempor invidunt ut labore et dolore magna "
1408 . "aliquyam erat, sed diam voluptua. At vero eos et accusam "
1409 . "et justo duo dolores et ea rebum. Stet clita kasd gubergren, "
1410 . "no sea takimata sanctus est Lorem ipsum dolor sit amet.'",
1411 null
1412 ],
1413 ],
1414 '/first edit:.*\.\.\."/',
1415 false
1416 ],
1417
1418 [
1419 [
1420 [ "first edit", "127.0.2.22" ],
1421 [ "", "127.0.3.33" ],
1422 ],
1423 "/before blanking.*first edit/",
1424 true
1425 ],
1426
1427 ];
1428 }
1429
1430 /**
1431 * @dataProvider provideGetAutoDeleteReason
1432 * @covers WikiPage::getAutoDeleteReason
1433 */
1434 public function testGetAutoDeleteReason( $edits, $expectedResult, $expectedHistory ) {
1435 global $wgUser;
1436
1437 // NOTE: assume Help namespace to contain wikitext
1438 $page = $this->newPage( "Help:WikiPageTest_testGetAutoDeleteReason" );
1439
1440 $c = 1;
1441
1442 foreach ( $edits as $edit ) {
1443 $user = new User();
1444
1445 if ( !empty( $edit[1] ) ) {
1446 $user->setName( $edit[1] );
1447 } else {
1448 $user = $wgUser;
1449 }
1450
1451 $content = ContentHandler::makeContent( $edit[0], $page->getTitle(), $page->getContentModel() );
1452
1453 $page->doEditContent( $content, "test edit $c", $c < 2 ? EDIT_NEW : 0, false, $user );
1454
1455 $c += 1;
1456 }
1457
1458 $reason = $page->getAutoDeleteReason( $hasHistory );
1459
1460 if ( is_bool( $expectedResult ) || is_null( $expectedResult ) ) {
1461 $this->assertEquals( $expectedResult, $reason );
1462 } else {
1463 $this->assertTrue( (bool)preg_match( $expectedResult, $reason ),
1464 "Autosummary didn't match expected pattern $expectedResult: $reason" );
1465 }
1466
1467 $this->assertEquals( $expectedHistory, $hasHistory,
1468 "expected \$hasHistory to be " . var_export( $expectedHistory, true ) );
1469
1470 $page->doDeleteArticle( "done" );
1471 }
1472
1473 public function providePreSaveTransform() {
1474 return [
1475 [ 'hello this is ~~~',
1476 "hello this is [[Special:Contributions/127.0.0.1|127.0.0.1]]",
1477 ],
1478 [ 'hello \'\'this\'\' is <nowiki>~~~</nowiki>',
1479 'hello \'\'this\'\' is <nowiki>~~~</nowiki>',
1480 ],
1481 ];
1482 }
1483
1484 /**
1485 * @covers WikiPage::factory
1486 */
1487 public function testWikiPageFactory() {
1488 $title = Title::makeTitle( NS_FILE, 'Someimage.png' );
1489 $page = WikiPage::factory( $title );
1490 $this->assertEquals( WikiFilePage::class, get_class( $page ) );
1491
1492 $title = Title::makeTitle( NS_CATEGORY, 'SomeCategory' );
1493 $page = WikiPage::factory( $title );
1494 $this->assertEquals( WikiCategoryPage::class, get_class( $page ) );
1495
1496 $title = Title::makeTitle( NS_MAIN, 'SomePage' );
1497 $page = WikiPage::factory( $title );
1498 $this->assertEquals( WikiPage::class, get_class( $page ) );
1499 }
1500
1501 /**
1502 * @covers WikiPage::loadPageData
1503 * @covers WikiPage::wasLoadedFrom
1504 */
1505 public function testLoadPageData() {
1506 $title = Title::makeTitle( NS_MAIN, 'SomePage' );
1507 $page = WikiPage::factory( $title );
1508
1509 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject::READ_NORMAL ) );
1510 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject::READ_LATEST ) );
1511 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject::READ_LOCKING ) );
1512 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject::READ_EXCLUSIVE ) );
1513
1514 $page->loadPageData( IDBAccessObject::READ_NORMAL );
1515 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject::READ_NORMAL ) );
1516 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject::READ_LATEST ) );
1517 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject::READ_LOCKING ) );
1518 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject::READ_EXCLUSIVE ) );
1519
1520 $page->loadPageData( IDBAccessObject::READ_LATEST );
1521 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject::READ_NORMAL ) );
1522 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject::READ_LATEST ) );
1523 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject::READ_LOCKING ) );
1524 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject::READ_EXCLUSIVE ) );
1525
1526 $page->loadPageData( IDBAccessObject::READ_LOCKING );
1527 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject::READ_NORMAL ) );
1528 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject::READ_LATEST ) );
1529 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject::READ_LOCKING ) );
1530 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject::READ_EXCLUSIVE ) );
1531
1532 $page->loadPageData( IDBAccessObject::READ_EXCLUSIVE );
1533 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject::READ_NORMAL ) );
1534 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject::READ_LATEST ) );
1535 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject::READ_LOCKING ) );
1536 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject::READ_EXCLUSIVE ) );
1537 }
1538
1539 /**
1540 * @dataProvider provideCommentMigrationOnDeletion
1541 *
1542 * @param int $writeStage
1543 * @param int $readStage
1544 */
1545 public function testCommentMigrationOnDeletion( $writeStage, $readStage ) {
1546 $this->setMwGlobals( 'wgCommentTableSchemaMigrationStage', $writeStage );
1547 $this->overrideMwServices();
1548
1549 $dbr = wfGetDB( DB_REPLICA );
1550
1551 $page = $this->createPage(
1552 __METHOD__,
1553 "foo",
1554 CONTENT_MODEL_WIKITEXT
1555 );
1556 $revid = $page->getLatest();
1557 if ( $writeStage > MIGRATION_OLD ) {
1558 $comment_id = $dbr->selectField(
1559 'revision_comment_temp',
1560 'revcomment_comment_id',
1561 [ 'revcomment_rev' => $revid ],
1562 __METHOD__
1563 );
1564 }
1565
1566 $this->setMwGlobals( 'wgCommentTableSchemaMigrationStage', $readStage );
1567 $this->overrideMwServices();
1568
1569 $page->doDeleteArticle( "testing deletion" );
1570
1571 if ( $readStage > MIGRATION_OLD ) {
1572 // Didn't leave behind any 'revision_comment_temp' rows
1573 $n = $dbr->selectField(
1574 'revision_comment_temp', 'COUNT(*)', [ 'revcomment_rev' => $revid ], __METHOD__
1575 );
1576 $this->assertEquals( 0, $n, 'no entry in revision_comment_temp after deletion' );
1577
1578 // Copied or upgraded the comment_id, as applicable
1579 $ar_comment_id = $dbr->selectField(
1580 'archive',
1581 'ar_comment_id',
1582 [ 'ar_rev_id' => $revid ],
1583 __METHOD__
1584 );
1585 if ( $writeStage > MIGRATION_OLD ) {
1586 $this->assertSame( $comment_id, $ar_comment_id );
1587 } else {
1588 $this->assertNotEquals( 0, $ar_comment_id );
1589 }
1590 }
1591
1592 // Copied rev_comment, if applicable
1593 if ( $readStage <= MIGRATION_WRITE_BOTH && $writeStage <= MIGRATION_WRITE_BOTH ) {
1594 $ar_comment = $dbr->selectField(
1595 'archive',
1596 'ar_comment',
1597 [ 'ar_rev_id' => $revid ],
1598 __METHOD__
1599 );
1600 $this->assertSame( 'testing', $ar_comment );
1601 }
1602 }
1603
1604 public function provideCommentMigrationOnDeletion() {
1605 return [
1606 [ MIGRATION_OLD, MIGRATION_OLD ],
1607 [ MIGRATION_OLD, MIGRATION_WRITE_BOTH ],
1608 [ MIGRATION_OLD, MIGRATION_WRITE_NEW ],
1609 [ MIGRATION_WRITE_BOTH, MIGRATION_OLD ],
1610 [ MIGRATION_WRITE_BOTH, MIGRATION_WRITE_BOTH ],
1611 [ MIGRATION_WRITE_BOTH, MIGRATION_WRITE_NEW ],
1612 [ MIGRATION_WRITE_BOTH, MIGRATION_NEW ],
1613 [ MIGRATION_WRITE_NEW, MIGRATION_WRITE_BOTH ],
1614 [ MIGRATION_WRITE_NEW, MIGRATION_WRITE_NEW ],
1615 [ MIGRATION_WRITE_NEW, MIGRATION_NEW ],
1616 [ MIGRATION_NEW, MIGRATION_WRITE_BOTH ],
1617 [ MIGRATION_NEW, MIGRATION_WRITE_NEW ],
1618 [ MIGRATION_NEW, MIGRATION_NEW ],
1619 ];
1620 }
1621
1622 /**
1623 * @covers WikiPage::updateCategoryCounts
1624 */
1625 public function testUpdateCategoryCounts() {
1626 $page = new WikiPage( Title::newFromText( __METHOD__ ) );
1627
1628 // Add an initial category
1629 $page->updateCategoryCounts( [ 'A' ], [], 0 );
1630
1631 $this->assertEquals( 1, Category::newFromName( 'A' )->getPageCount() );
1632 $this->assertEquals( 0, Category::newFromName( 'B' )->getPageCount() );
1633 $this->assertEquals( 0, Category::newFromName( 'C' )->getPageCount() );
1634
1635 // Add a new category
1636 $page->updateCategoryCounts( [ 'B' ], [], 0 );
1637
1638 $this->assertEquals( 1, Category::newFromName( 'A' )->getPageCount() );
1639 $this->assertEquals( 1, Category::newFromName( 'B' )->getPageCount() );
1640 $this->assertEquals( 0, Category::newFromName( 'C' )->getPageCount() );
1641
1642 // Add and remove a category
1643 $page->updateCategoryCounts( [ 'C' ], [ 'A' ], 0 );
1644
1645 $this->assertEquals( 0, Category::newFromName( 'A' )->getPageCount() );
1646 $this->assertEquals( 1, Category::newFromName( 'B' )->getPageCount() );
1647 $this->assertEquals( 1, Category::newFromName( 'C' )->getPageCount() );
1648 }
1649
1650 public function provideUpdateRedirectOn() {
1651 yield [ '#REDIRECT [[Foo]]', true, null, true, true, 0 ];
1652 yield [ '#REDIRECT [[Foo]]', true, 'Foo', true, false, 1 ];
1653 yield [ 'SomeText', false, null, false, true, 0 ];
1654 yield [ 'SomeText', false, 'Foo', false, false, 1 ];
1655 }
1656
1657 /**
1658 * @dataProvider provideUpdateRedirectOn
1659 * @covers WikiPage::updateRedirectOn
1660 *
1661 * @param string $initialText
1662 * @param bool $initialRedirectState
1663 * @param string|null $redirectTitle
1664 * @param bool|null $lastRevIsRedirect
1665 * @param bool $expectedSuccess
1666 * @param int $expectedRowCount
1667 */
1668 public function testUpdateRedirectOn(
1669 $initialText,
1670 $initialRedirectState,
1671 $redirectTitle,
1672 $lastRevIsRedirect,
1673 $expectedSuccess,
1674 $expectedRowCount
1675 ) {
1676 // FIXME: fails under sqlite and postgres
1677 $this->markTestSkippedIfDbType( 'sqlite' );
1678 $this->markTestSkippedIfDbType( 'postgres' );
1679 static $pageCounter = 0;
1680 $pageCounter++;
1681
1682 $page = $this->createPage( Title::newFromText( __METHOD__ . $pageCounter ), $initialText );
1683 $this->assertSame( $initialRedirectState, $page->isRedirect() );
1684
1685 $redirectTitle = is_string( $redirectTitle )
1686 ? Title::newFromText( $redirectTitle )
1687 : $redirectTitle;
1688
1689 $success = $page->updateRedirectOn( $this->db, $redirectTitle, $lastRevIsRedirect );
1690 $this->assertSame( $expectedSuccess, $success, 'Success assertion' );
1691 /**
1692 * updateRedirectOn explicitly updates the redirect table (and not the page table).
1693 * Most of core checks the page table for redirect status, so we have to be ugly and
1694 * assert a select from the table here.
1695 */
1696 $this->assertRedirectTableCountForPageId( $page->getId(), $expectedRowCount );
1697 }
1698
1699 private function assertRedirectTableCountForPageId( $pageId, $expected ) {
1700 $this->assertSelect(
1701 'redirect',
1702 'COUNT(*)',
1703 [ 'rd_from' => $pageId ],
1704 [ [ strval( $expected ) ] ]
1705 );
1706 }
1707
1708 /**
1709 * @covers WikiPage::insertRedirectEntry
1710 */
1711 public function testInsertRedirectEntry_insertsRedirectEntry() {
1712 $page = $this->createPage( Title::newFromText( __METHOD__ ), 'A' );
1713 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1714
1715 $targetTitle = Title::newFromText( 'SomeTarget#Frag' );
1716 $targetTitle->mInterwiki = 'eninter';
1717 $page->insertRedirectEntry( $targetTitle, null );
1718
1719 $this->assertSelect(
1720 'redirect',
1721 [ 'rd_from', 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
1722 [ 'rd_from' => $page->getId() ],
1723 [ [
1724 strval( $page->getId() ),
1725 strval( $targetTitle->getNamespace() ),
1726 strval( $targetTitle->getDBkey() ),
1727 strval( $targetTitle->getFragment() ),
1728 strval( $targetTitle->getInterwiki() ),
1729 ] ]
1730 );
1731 }
1732
1733 /**
1734 * @covers WikiPage::insertRedirectEntry
1735 */
1736 public function testInsertRedirectEntry_insertsRedirectEntryWithPageLatest() {
1737 $page = $this->createPage( Title::newFromText( __METHOD__ ), 'A' );
1738 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1739
1740 $targetTitle = Title::newFromText( 'SomeTarget#Frag' );
1741 $targetTitle->mInterwiki = 'eninter';
1742 $page->insertRedirectEntry( $targetTitle, $page->getLatest() );
1743
1744 $this->assertSelect(
1745 'redirect',
1746 [ 'rd_from', 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
1747 [ 'rd_from' => $page->getId() ],
1748 [ [
1749 strval( $page->getId() ),
1750 strval( $targetTitle->getNamespace() ),
1751 strval( $targetTitle->getDBkey() ),
1752 strval( $targetTitle->getFragment() ),
1753 strval( $targetTitle->getInterwiki() ),
1754 ] ]
1755 );
1756 }
1757
1758 /**
1759 * @covers WikiPage::insertRedirectEntry
1760 */
1761 public function testInsertRedirectEntry_doesNotInsertIfPageLatestIncorrect() {
1762 $page = $this->createPage( Title::newFromText( __METHOD__ ), 'A' );
1763 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1764
1765 $targetTitle = Title::newFromText( 'SomeTarget#Frag' );
1766 $targetTitle->mInterwiki = 'eninter';
1767 $page->insertRedirectEntry( $targetTitle, 215251 );
1768
1769 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1770 }
1771
1772 private function getRow( array $overrides = [] ) {
1773 $row = [
1774 'page_id' => '44',
1775 'page_len' => '76',
1776 'page_is_redirect' => '1',
1777 'page_latest' => '99',
1778 'page_namespace' => '3',
1779 'page_title' => 'JaJaTitle',
1780 'page_restrictions' => 'edit=autoconfirmed,sysop:move=sysop',
1781 'page_touched' => '20120101020202',
1782 'page_links_updated' => '20140101020202',
1783 ];
1784 foreach ( $overrides as $key => $value ) {
1785 $row[$key] = $value;
1786 }
1787 return (object)$row;
1788 }
1789
1790 public function provideNewFromRowSuccess() {
1791 yield 'basic row' => [
1792 $this->getRow(),
1793 function ( WikiPage $wikiPage, self $test ) {
1794 $test->assertSame( 44, $wikiPage->getId() );
1795 $test->assertSame( 76, $wikiPage->getTitle()->getLength() );
1796 $test->assertTrue( $wikiPage->isRedirect() );
1797 $test->assertSame( 99, $wikiPage->getLatest() );
1798 $test->assertSame( 3, $wikiPage->getTitle()->getNamespace() );
1799 $test->assertSame( 'JaJaTitle', $wikiPage->getTitle()->getDBkey() );
1800 $test->assertSame(
1801 [
1802 'edit' => [ 'autoconfirmed', 'sysop' ],
1803 'move' => [ 'sysop' ],
1804 ],
1805 $wikiPage->getTitle()->getAllRestrictions()
1806 );
1807 $test->assertSame( '20120101020202', $wikiPage->getTouched() );
1808 $test->assertSame( '20140101020202', $wikiPage->getLinksTimestamp() );
1809 }
1810 ];
1811 yield 'different timestamp formats' => [
1812 $this->getRow( [
1813 'page_touched' => '2012-01-01 02:02:02',
1814 'page_links_updated' => '2014-01-01 02:02:02',
1815 ] ),
1816 function ( WikiPage $wikiPage, self $test ) {
1817 $test->assertSame( '20120101020202', $wikiPage->getTouched() );
1818 $test->assertSame( '20140101020202', $wikiPage->getLinksTimestamp() );
1819 }
1820 ];
1821 yield 'no restrictions' => [
1822 $this->getRow( [
1823 'page_restrictions' => '',
1824 ] ),
1825 function ( WikiPage $wikiPage, self $test ) {
1826 $test->assertSame(
1827 [
1828 'edit' => [],
1829 'move' => [],
1830 ],
1831 $wikiPage->getTitle()->getAllRestrictions()
1832 );
1833 }
1834 ];
1835 yield 'not redirect' => [
1836 $this->getRow( [
1837 'page_is_redirect' => '0',
1838 ] ),
1839 function ( WikiPage $wikiPage, self $test ) {
1840 $test->assertFalse( $wikiPage->isRedirect() );
1841 }
1842 ];
1843 }
1844
1845 /**
1846 * @covers WikiPage::newFromRow
1847 * @covers WikiPage::loadFromRow
1848 * @dataProvider provideNewFromRowSuccess
1849 *
1850 * @param object $row
1851 * @param callable $assertions
1852 */
1853 public function testNewFromRow( $row, $assertions ) {
1854 $page = WikiPage::newFromRow( $row, 'fromdb' );
1855 $assertions( $page, $this );
1856 }
1857
1858 public function provideTestNewFromId_returnsNullOnBadPageId() {
1859 yield[ 0 ];
1860 yield[ -11 ];
1861 }
1862
1863 /**
1864 * @covers WikiPage::newFromID
1865 * @dataProvider provideTestNewFromId_returnsNullOnBadPageId
1866 */
1867 public function testNewFromId_returnsNullOnBadPageId( $pageId ) {
1868 $this->assertNull( WikiPage::newFromID( $pageId ) );
1869 }
1870
1871 /**
1872 * @covers WikiPage::newFromID
1873 */
1874 public function testNewFromId_appearsToFetchCorrectRow() {
1875 $createdPage = $this->createPage( __METHOD__, 'Xsfaij09' );
1876 $fetchedPage = WikiPage::newFromID( $createdPage->getId() );
1877 $this->assertSame( $createdPage->getId(), $fetchedPage->getId() );
1878 $this->assertEquals(
1879 $createdPage->getContent()->getNativeData(),
1880 $fetchedPage->getContent()->getNativeData()
1881 );
1882 }
1883
1884 /**
1885 * @covers WikiPage::newFromID
1886 */
1887 public function testNewFromId_returnsNullOnNonExistingId() {
1888 $this->assertNull( WikiPage::newFromID( 2147483647 ) );
1889 }
1890
1891 public function provideTestInsertProtectNullRevision() {
1892 // phpcs:disable Generic.Files.LineLength
1893 yield [
1894 'goat-message-key',
1895 [ 'edit' => 'sysop' ],
1896 [ 'edit' => '20200101040404' ],
1897 false,
1898 'Goat Reason',
1899 true,
1900 '(goat-message-key: WikiPageDbTestBase::testInsertProtectNullRevision, UTSysop)(colon-separator)Goat Reason(word-separator)(parentheses: (protect-summary-desc: (restriction-edit), (protect-level-sysop), (protect-expiring: 04:04, 1 (january) 2020, 1 (january) 2020, 04:04)))'
1901 ];
1902 yield [
1903 'goat-key',
1904 [ 'edit' => 'sysop', 'move' => 'something' ],
1905 [ 'edit' => '20200101040404', 'move' => '20210101050505' ],
1906 false,
1907 'Goat Goat',
1908 true,
1909 '(goat-key: WikiPageDbTestBase::testInsertProtectNullRevision, UTSysop)(colon-separator)Goat Goat(word-separator)(parentheses: (protect-summary-desc: (restriction-edit), (protect-level-sysop), (protect-expiring: 04:04, 1 (january) 2020, 1 (january) 2020, 04:04))(word-separator)(protect-summary-desc: (restriction-move), (protect-level-something), (protect-expiring: 05:05, 1 (january) 2021, 1 (january) 2021, 05:05)))'
1910 ];
1911 // phpcs:enable
1912 }
1913
1914 /**
1915 * @dataProvider provideTestInsertProtectNullRevision
1916 * @covers WikiPage::insertProtectNullRevision
1917 * @covers WikiPage::protectDescription
1918 *
1919 * @param string $revCommentMsg
1920 * @param array $limit
1921 * @param array $expiry
1922 * @param bool $cascade
1923 * @param string $reason
1924 * @param bool|null $user true if the test sysop should be used, or null
1925 * @param string $expectedComment
1926 */
1927 public function testInsertProtectNullRevision(
1928 $revCommentMsg,
1929 array $limit,
1930 array $expiry,
1931 $cascade,
1932 $reason,
1933 $user,
1934 $expectedComment
1935 ) {
1936 $this->setContentLang( 'qqx' );
1937
1938 $page = $this->createPage( __METHOD__, 'Goat' );
1939
1940 $user = $user === null ? $user : $this->getTestSysop()->getUser();
1941
1942 $result = $page->insertProtectNullRevision(
1943 $revCommentMsg,
1944 $limit,
1945 $expiry,
1946 $cascade,
1947 $reason,
1948 $user
1949 );
1950
1951 $this->assertTrue( $result instanceof Revision );
1952 $this->assertSame( $expectedComment, $result->getComment( Revision::RAW ) );
1953 }
1954
1955 /**
1956 * @covers WikiPage::updateRevisionOn
1957 */
1958 public function testUpdateRevisionOn_existingPage() {
1959 $user = $this->getTestSysop()->getUser();
1960 $page = $this->createPage( __METHOD__, 'StartText' );
1961
1962 $revision = new Revision(
1963 [
1964 'id' => 9989,
1965 'page' => $page->getId(),
1966 'title' => $page->getTitle(),
1967 'comment' => __METHOD__,
1968 'minor_edit' => true,
1969 'text' => __METHOD__ . '-text',
1970 'len' => strlen( __METHOD__ . '-text' ),
1971 'user' => $user->getId(),
1972 'user_text' => $user->getName(),
1973 'timestamp' => '20170707040404',
1974 'content_model' => CONTENT_MODEL_WIKITEXT,
1975 'content_format' => CONTENT_FORMAT_WIKITEXT,
1976 ]
1977 );
1978
1979 $result = $page->updateRevisionOn( $this->db, $revision );
1980 $this->assertTrue( $result );
1981 $this->assertSame( 9989, $page->getLatest() );
1982 $this->assertEquals( $revision, $page->getRevision() );
1983 }
1984
1985 /**
1986 * @covers WikiPage::updateRevisionOn
1987 */
1988 public function testUpdateRevisionOn_NonExistingPage() {
1989 $user = $this->getTestSysop()->getUser();
1990 $page = $this->createPage( __METHOD__, 'StartText' );
1991 $page->doDeleteArticle( 'reason' );
1992
1993 $revision = new Revision(
1994 [
1995 'id' => 9989,
1996 'page' => $page->getId(),
1997 'title' => $page->getTitle(),
1998 'comment' => __METHOD__,
1999 'minor_edit' => true,
2000 'text' => __METHOD__ . '-text',
2001 'len' => strlen( __METHOD__ . '-text' ),
2002 'user' => $user->getId(),
2003 'user_text' => $user->getName(),
2004 'timestamp' => '20170707040404',
2005 'content_model' => CONTENT_MODEL_WIKITEXT,
2006 'content_format' => CONTENT_FORMAT_WIKITEXT,
2007 ]
2008 );
2009
2010 $result = $page->updateRevisionOn( $this->db, $revision );
2011 $this->assertFalse( $result );
2012 }
2013
2014 /**
2015 * @covers WikiPage::updateIfNewerOn
2016 */
2017 public function testUpdateIfNewerOn_olderRevision() {
2018 $user = $this->getTestSysop()->getUser();
2019 $page = $this->createPage( __METHOD__, 'StartText' );
2020 $initialRevision = $page->getRevision();
2021
2022 $olderTimeStamp = wfTimestamp(
2023 TS_MW,
2024 wfTimestamp( TS_UNIX, $initialRevision->getTimestamp() ) - 1
2025 );
2026
2027 $olderRevison = new Revision(
2028 [
2029 'id' => 9989,
2030 'page' => $page->getId(),
2031 'title' => $page->getTitle(),
2032 'comment' => __METHOD__,
2033 'minor_edit' => true,
2034 'text' => __METHOD__ . '-text',
2035 'len' => strlen( __METHOD__ . '-text' ),
2036 'user' => $user->getId(),
2037 'user_text' => $user->getName(),
2038 'timestamp' => $olderTimeStamp,
2039 'content_model' => CONTENT_MODEL_WIKITEXT,
2040 'content_format' => CONTENT_FORMAT_WIKITEXT,
2041 ]
2042 );
2043
2044 $result = $page->updateIfNewerOn( $this->db, $olderRevison );
2045 $this->assertFalse( $result );
2046 }
2047
2048 /**
2049 * @covers WikiPage::updateIfNewerOn
2050 */
2051 public function testUpdateIfNewerOn_newerRevision() {
2052 $user = $this->getTestSysop()->getUser();
2053 $page = $this->createPage( __METHOD__, 'StartText' );
2054 $initialRevision = $page->getRevision();
2055
2056 $newerTimeStamp = wfTimestamp(
2057 TS_MW,
2058 wfTimestamp( TS_UNIX, $initialRevision->getTimestamp() ) + 1
2059 );
2060
2061 $newerRevision = new Revision(
2062 [
2063 'id' => 9989,
2064 'page' => $page->getId(),
2065 'title' => $page->getTitle(),
2066 'comment' => __METHOD__,
2067 'minor_edit' => true,
2068 'text' => __METHOD__ . '-text',
2069 'len' => strlen( __METHOD__ . '-text' ),
2070 'user' => $user->getId(),
2071 'user_text' => $user->getName(),
2072 'timestamp' => $newerTimeStamp,
2073 'content_model' => CONTENT_MODEL_WIKITEXT,
2074 'content_format' => CONTENT_FORMAT_WIKITEXT,
2075 ]
2076 );
2077 $result = $page->updateIfNewerOn( $this->db, $newerRevision );
2078 $this->assertTrue( $result );
2079 }
2080
2081 /**
2082 * @covers WikiPage::insertOn
2083 */
2084 public function testInsertOn() {
2085 $title = Title::newFromText( __METHOD__ );
2086 $page = new WikiPage( $title );
2087
2088 $startTimeStamp = wfTimestampNow();
2089 $result = $page->insertOn( $this->db );
2090 $endTimeStamp = wfTimestampNow();
2091
2092 $this->assertInternalType( 'int', $result );
2093 $this->assertTrue( $result > 0 );
2094
2095 $condition = [ 'page_id' => $result ];
2096
2097 // Check the default fields have been filled
2098 $this->assertSelect(
2099 'page',
2100 [
2101 'page_namespace',
2102 'page_title',
2103 'page_restrictions',
2104 'page_is_redirect',
2105 'page_is_new',
2106 'page_latest',
2107 'page_len',
2108 ],
2109 $condition,
2110 [ [
2111 '0',
2112 __METHOD__,
2113 '',
2114 '0',
2115 '1',
2116 '0',
2117 '0',
2118 ] ]
2119 );
2120
2121 // Check the page_random field has been filled
2122 $pageRandom = $this->db->selectField( 'page', 'page_random', $condition );
2123 $this->assertTrue( (float)$pageRandom < 1 && (float)$pageRandom > 0 );
2124
2125 // Assert the touched timestamp in the DB is roughly when we inserted the page
2126 $pageTouched = $this->db->selectField( 'page', 'page_touched', $condition );
2127 $this->assertTrue(
2128 wfTimestamp( TS_UNIX, $startTimeStamp )
2129 <= wfTimestamp( TS_UNIX, $pageTouched )
2130 );
2131 $this->assertTrue(
2132 wfTimestamp( TS_UNIX, $endTimeStamp )
2133 >= wfTimestamp( TS_UNIX, $pageTouched )
2134 );
2135
2136 // Try inserting the same page again and checking the result is false (no change)
2137 $result = $page->insertOn( $this->db );
2138 $this->assertFalse( $result );
2139 }
2140
2141 /**
2142 * @covers WikiPage::insertOn
2143 */
2144 public function testInsertOn_idSpecified() {
2145 $title = Title::newFromText( __METHOD__ );
2146 $page = new WikiPage( $title );
2147 $id = 1478952189;
2148
2149 $result = $page->insertOn( $this->db, $id );
2150
2151 $this->assertSame( $id, $result );
2152
2153 $condition = [ 'page_id' => $result ];
2154
2155 // Check there is actually a row in the db
2156 $this->assertSelect(
2157 'page',
2158 [ 'page_title' ],
2159 $condition,
2160 [ [ __METHOD__ ] ]
2161 );
2162 }
2163
2164 public function provideTestDoUpdateRestrictions_setBasicRestrictions() {
2165 // Note: Once the current dates passes the date in these tests they will fail.
2166 yield 'move something' => [
2167 true,
2168 [ 'move' => 'something' ],
2169 [],
2170 [ 'edit' => [], 'move' => [ 'something' ] ],
2171 [],
2172 ];
2173 yield 'move something, edit blank' => [
2174 true,
2175 [ 'move' => 'something', 'edit' => '' ],
2176 [],
2177 [ 'edit' => [], 'move' => [ 'something' ] ],
2178 [],
2179 ];
2180 yield 'edit sysop, with expiry' => [
2181 true,
2182 [ 'edit' => 'sysop' ],
2183 [ 'edit' => '21330101020202' ],
2184 [ 'edit' => [ 'sysop' ], 'move' => [] ],
2185 [ 'edit' => '21330101020202' ],
2186 ];
2187 yield 'move and edit, move with expiry' => [
2188 true,
2189 [ 'move' => 'something', 'edit' => 'another' ],
2190 [ 'move' => '22220202010101' ],
2191 [ 'edit' => [ 'another' ], 'move' => [ 'something' ] ],
2192 [ 'move' => '22220202010101' ],
2193 ];
2194 yield 'move and edit, edit with infinity expiry' => [
2195 true,
2196 [ 'move' => 'something', 'edit' => 'another' ],
2197 [ 'edit' => 'infinity' ],
2198 [ 'edit' => [ 'another' ], 'move' => [ 'something' ] ],
2199 [ 'edit' => 'infinity' ],
2200 ];
2201 yield 'non existing, create something' => [
2202 false,
2203 [ 'create' => 'something' ],
2204 [],
2205 [ 'create' => [ 'something' ] ],
2206 [],
2207 ];
2208 yield 'non existing, create something with expiry' => [
2209 false,
2210 [ 'create' => 'something' ],
2211 [ 'create' => '23451212112233' ],
2212 [ 'create' => [ 'something' ] ],
2213 [ 'create' => '23451212112233' ],
2214 ];
2215 }
2216
2217 /**
2218 * @dataProvider provideTestDoUpdateRestrictions_setBasicRestrictions
2219 * @covers WikiPage::doUpdateRestrictions
2220 */
2221 public function testDoUpdateRestrictions_setBasicRestrictions(
2222 $pageExists,
2223 array $limit,
2224 array $expiry,
2225 array $expectedRestrictions,
2226 array $expectedRestrictionExpiries
2227 ) {
2228 if ( $pageExists ) {
2229 $page = $this->createPage( __METHOD__, 'ABC' );
2230 } else {
2231 $page = new WikiPage( Title::newFromText( __METHOD__ . '-nonexist' ) );
2232 }
2233 $user = $this->getTestSysop()->getUser();
2234 $cascade = false;
2235
2236 $status = $page->doUpdateRestrictions( $limit, $expiry, $cascade, 'aReason', $user, [] );
2237
2238 $logId = $status->getValue();
2239 $allRestrictions = $page->getTitle()->getAllRestrictions();
2240
2241 $this->assertTrue( $status->isGood() );
2242 $this->assertInternalType( 'int', $logId );
2243 $this->assertSame( $expectedRestrictions, $allRestrictions );
2244 foreach ( $expectedRestrictionExpiries as $key => $value ) {
2245 $this->assertSame( $value, $page->getTitle()->getRestrictionExpiry( $key ) );
2246 }
2247
2248 // Make sure the log entry looks good
2249 // log_params is not checked here
2250 $actorQuery = ActorMigration::newMigration()->getJoin( 'log_user' );
2251 $this->assertSelect(
2252 [ 'logging' ] + $actorQuery['tables'],
2253 [
2254 'log_comment',
2255 'log_user' => $actorQuery['fields']['log_user'],
2256 'log_user_text' => $actorQuery['fields']['log_user_text'],
2257 'log_namespace',
2258 'log_title',
2259 ],
2260 [ 'log_id' => $logId ],
2261 [ [
2262 'aReason',
2263 (string)$user->getId(),
2264 $user->getName(),
2265 (string)$page->getTitle()->getNamespace(),
2266 $page->getTitle()->getDBkey(),
2267 ] ],
2268 [],
2269 $actorQuery['joins']
2270 );
2271 }
2272
2273 /**
2274 * @covers WikiPage::doUpdateRestrictions
2275 */
2276 public function testDoUpdateRestrictions_failsOnReadOnly() {
2277 $page = $this->createPage( __METHOD__, 'ABC' );
2278 $user = $this->getTestSysop()->getUser();
2279 $cascade = false;
2280
2281 // Set read only
2282 $readOnly = $this->getMockBuilder( ReadOnlyMode::class )
2283 ->disableOriginalConstructor()
2284 ->setMethods( [ 'isReadOnly', 'getReason' ] )
2285 ->getMock();
2286 $readOnly->expects( $this->once() )
2287 ->method( 'isReadOnly' )
2288 ->will( $this->returnValue( true ) );
2289 $readOnly->expects( $this->once() )
2290 ->method( 'getReason' )
2291 ->will( $this->returnValue( 'Some Read Only Reason' ) );
2292 $this->setService( 'ReadOnlyMode', $readOnly );
2293
2294 $status = $page->doUpdateRestrictions( [], [], $cascade, 'aReason', $user, [] );
2295 $this->assertFalse( $status->isOK() );
2296 $this->assertSame( 'readonlytext', $status->getMessage()->getKey() );
2297 }
2298
2299 /**
2300 * @covers WikiPage::doUpdateRestrictions
2301 */
2302 public function testDoUpdateRestrictions_returnsGoodIfNothingChanged() {
2303 $page = $this->createPage( __METHOD__, 'ABC' );
2304 $user = $this->getTestSysop()->getUser();
2305 $cascade = false;
2306 $limit = [ 'edit' => 'sysop' ];
2307
2308 $status = $page->doUpdateRestrictions(
2309 $limit,
2310 [],
2311 $cascade,
2312 'aReason',
2313 $user,
2314 []
2315 );
2316
2317 // The first entry should have a logId as it did something
2318 $this->assertTrue( $status->isGood() );
2319 $this->assertInternalType( 'int', $status->getValue() );
2320
2321 $status = $page->doUpdateRestrictions(
2322 $limit,
2323 [],
2324 $cascade,
2325 'aReason',
2326 $user,
2327 []
2328 );
2329
2330 // The second entry should not have a logId as nothing changed
2331 $this->assertTrue( $status->isGood() );
2332 $this->assertNull( $status->getValue() );
2333 }
2334
2335 /**
2336 * @covers WikiPage::doUpdateRestrictions
2337 */
2338 public function testDoUpdateRestrictions_logEntryTypeAndAction() {
2339 $page = $this->createPage( __METHOD__, 'ABC' );
2340 $user = $this->getTestSysop()->getUser();
2341 $cascade = false;
2342
2343 // Protect the page
2344 $status = $page->doUpdateRestrictions(
2345 [ 'edit' => 'sysop' ],
2346 [],
2347 $cascade,
2348 'aReason',
2349 $user,
2350 []
2351 );
2352 $this->assertTrue( $status->isGood() );
2353 $this->assertInternalType( 'int', $status->getValue() );
2354 $this->assertSelect(
2355 'logging',
2356 [ 'log_type', 'log_action' ],
2357 [ 'log_id' => $status->getValue() ],
2358 [ [ 'protect', 'protect' ] ]
2359 );
2360
2361 // Modify the protection
2362 $status = $page->doUpdateRestrictions(
2363 [ 'edit' => 'somethingElse' ],
2364 [],
2365 $cascade,
2366 'aReason',
2367 $user,
2368 []
2369 );
2370 $this->assertTrue( $status->isGood() );
2371 $this->assertInternalType( 'int', $status->getValue() );
2372 $this->assertSelect(
2373 'logging',
2374 [ 'log_type', 'log_action' ],
2375 [ 'log_id' => $status->getValue() ],
2376 [ [ 'protect', 'modify' ] ]
2377 );
2378
2379 // Remove the protection
2380 $status = $page->doUpdateRestrictions(
2381 [],
2382 [],
2383 $cascade,
2384 'aReason',
2385 $user,
2386 []
2387 );
2388 $this->assertTrue( $status->isGood() );
2389 $this->assertInternalType( 'int', $status->getValue() );
2390 $this->assertSelect(
2391 'logging',
2392 [ 'log_type', 'log_action' ],
2393 [ 'log_id' => $status->getValue() ],
2394 [ [ 'protect', 'unprotect' ] ]
2395 );
2396 }
2397
2398 /**
2399 * @covers WikiPage::newPageUpdater
2400 * @covers WikiPage::getDerivedDataUpdater
2401 */
2402 public function testNewPageUpdater() {
2403 $user = $this->getTestUser()->getUser();
2404 $page = $this->newPage( __METHOD__, __METHOD__ );
2405
2406 /** @var Content $content */
2407 $content = $this->getMockBuilder( WikitextContent::class )
2408 ->setConstructorArgs( [ 'Hello World' ] )
2409 ->setMethods( [ 'getParserOutput' ] )
2410 ->getMock();
2411 $content->expects( $this->once() )
2412 ->method( 'getParserOutput' )
2413 ->willReturn( new ParserOutput( 'HTML' ) );
2414
2415 $preparedEditBefore = $page->prepareContentForEdit( $content, null, $user );
2416
2417 // provide context, so the cache can be kept in place
2418 $slotsUpdate = new revisionSlotsUpdate();
2419 $slotsUpdate->modifyContent( 'main', $content );
2420
2421 $updater = $page->newPageUpdater( $user, $slotsUpdate );
2422 $updater->setContent( 'main', $content );
2423 $revision = $updater->saveRevision(
2424 CommentStoreComment::newUnsavedComment( 'test' ),
2425 EDIT_NEW
2426 );
2427
2428 $preparedEditAfter = $page->prepareContentForEdit( $content, $revision, $user );
2429
2430 $this->assertSame( $revision->getId(), $page->getLatest() );
2431
2432 // Parsed output must remain cached throughout.
2433 $this->assertSame( $preparedEditBefore->output, $preparedEditAfter->output );
2434 }
2435
2436 /**
2437 * @covers WikiPage::newPageUpdater
2438 * @covers WikiPage::getDerivedDataUpdater
2439 */
2440 public function testGetDerivedDataUpdater() {
2441 $admin = $this->getTestSysop()->getUser();
2442
2443 /** @var object $page */
2444 $page = $this->createPage( __METHOD__, __METHOD__ );
2445 $page = TestingAccessWrapper::newFromObject( $page );
2446
2447 $revision = $page->getRevision()->getRevisionRecord();
2448 $user = $revision->getUser();
2449
2450 $slotsUpdate = new RevisionSlotsUpdate();
2451 $slotsUpdate->modifyContent( 'main', new WikitextContent( 'Hello World' ) );
2452
2453 // get a virgin updater
2454 $updater1 = $page->getDerivedDataUpdater( $user );
2455 $this->assertFalse( $updater1->isUpdatePrepared() );
2456
2457 $updater1->prepareUpdate( $revision );
2458
2459 // Re-use updater with same revision or content, even if base changed
2460 $this->assertSame( $updater1, $page->getDerivedDataUpdater( $user, $revision ) );
2461
2462 $slotsUpdate = RevisionSlotsUpdate::newFromContent(
2463 [ 'main' => $revision->getContent( 'main' ) ]
2464 );
2465 $this->assertSame( $updater1, $page->getDerivedDataUpdater( $user, null, $slotsUpdate ) );
2466
2467 // Don't re-use for edit if base revision ID changed
2468 $this->assertNotSame(
2469 $updater1,
2470 $page->getDerivedDataUpdater( $user, null, $slotsUpdate, true )
2471 );
2472
2473 // Don't re-use with different user
2474 $updater2a = $page->getDerivedDataUpdater( $admin, null, $slotsUpdate );
2475 $updater2a->prepareContent( $admin, $slotsUpdate, false );
2476
2477 $updater2b = $page->getDerivedDataUpdater( $user, null, $slotsUpdate );
2478 $updater2b->prepareContent( $user, $slotsUpdate, false );
2479 $this->assertNotSame( $updater2a, $updater2b );
2480
2481 // Don't re-use with different content
2482 $updater3 = $page->getDerivedDataUpdater( $admin, null, $slotsUpdate );
2483 $updater3->prepareUpdate( $revision );
2484 $this->assertNotSame( $updater2b, $updater3 );
2485
2486 // Don't re-use if no context given
2487 $updater4 = $page->getDerivedDataUpdater( $admin );
2488 $updater4->prepareUpdate( $revision );
2489 $this->assertNotSame( $updater3, $updater4 );
2490
2491 // Don't re-use if AGAIN no context given
2492 $updater5 = $page->getDerivedDataUpdater( $admin );
2493 $this->assertNotSame( $updater4, $updater5 );
2494
2495 // Don't re-use cached "virgin" unprepared updater
2496 $updater6 = $page->getDerivedDataUpdater( $admin, $revision );
2497 $this->assertNotSame( $updater5, $updater6 );
2498 }
2499
2500 protected function assertPreparedEditEquals(
2501 PreparedEdit $edit, PreparedEdit $edit2, $message = ''
2502 ) {
2503 // suppress differences caused by a clock tick between generating the two PreparedEdits
2504 if ( abs( $edit->timestamp - $edit2->timestamp ) < 3 ) {
2505 $edit2 = clone $edit2;
2506 $edit2->timestamp = $edit->timestamp;
2507 }
2508 $this->assertEquals( $edit, $edit2, $message );
2509 }
2510
2511 protected function assertPreparedEditNotEquals(
2512 PreparedEdit $edit, PreparedEdit $edit2, $message = ''
2513 ) {
2514 if ( abs( $edit->timestamp - $edit2->timestamp ) < 3 ) {
2515 $edit2 = clone $edit2;
2516 $edit2->timestamp = $edit->timestamp;
2517 }
2518 $this->assertNotEquals( $edit, $edit2, $message );
2519 }
2520
2521 }