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