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