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