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