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