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