Disable PHPUnit tests that fail under sqlite
[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 // FIXME: fails under sqlite
1573 $this->markTestSkippedIfDbType( 'sqlite' );
1574 static $pageCounter = 0;
1575 $pageCounter++;
1576
1577 $page = $this->createPage( Title::newFromText( __METHOD__ . $pageCounter ), $initialText );
1578 $this->assertSame( $initialRedirectState, $page->isRedirect() );
1579
1580 $redirectTitle = is_string( $redirectTitle )
1581 ? Title::newFromText( $redirectTitle )
1582 : $redirectTitle;
1583
1584 $success = $page->updateRedirectOn( $this->db, $redirectTitle, $lastRevIsRedirect );
1585 $this->assertSame( $expectedSuccess, $success, 'Success assertion' );
1586 /**
1587 * updateRedirectOn explicitly updates the redirect table (and not the page table).
1588 * Most of core checks the page table for redirect status, so we have to be ugly and
1589 * assert a select from the table here.
1590 */
1591 $this->assertRedirectTableCountForPageId( $page->getId(), $expectedRowCount );
1592 }
1593
1594 private function assertRedirectTableCountForPageId( $pageId, $expected ) {
1595 $this->assertSelect(
1596 'redirect',
1597 'COUNT(*)',
1598 [ 'rd_from' => $pageId ],
1599 [ [ strval( $expected ) ] ]
1600 );
1601 }
1602
1603 /**
1604 * @covers WikiPage::insertRedirectEntry
1605 */
1606 public function testInsertRedirectEntry_insertsRedirectEntry() {
1607 $page = $this->createPage( Title::newFromText( __METHOD__ ), 'A' );
1608 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1609
1610 $targetTitle = Title::newFromText( 'SomeTarget#Frag' );
1611 $targetTitle->mInterwiki = 'eninter';
1612 $page->insertRedirectEntry( $targetTitle, null );
1613
1614 $this->assertSelect(
1615 'redirect',
1616 [ 'rd_from', 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
1617 [ 'rd_from' => $page->getId() ],
1618 [ [
1619 strval( $page->getId() ),
1620 strval( $targetTitle->getNamespace() ),
1621 strval( $targetTitle->getDBkey() ),
1622 strval( $targetTitle->getFragment() ),
1623 strval( $targetTitle->getInterwiki() ),
1624 ] ]
1625 );
1626 }
1627
1628 /**
1629 * @covers WikiPage::insertRedirectEntry
1630 */
1631 public function testInsertRedirectEntry_insertsRedirectEntryWithPageLatest() {
1632 $page = $this->createPage( Title::newFromText( __METHOD__ ), 'A' );
1633 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1634
1635 $targetTitle = Title::newFromText( 'SomeTarget#Frag' );
1636 $targetTitle->mInterwiki = 'eninter';
1637 $page->insertRedirectEntry( $targetTitle, $page->getLatest() );
1638
1639 $this->assertSelect(
1640 'redirect',
1641 [ 'rd_from', 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
1642 [ 'rd_from' => $page->getId() ],
1643 [ [
1644 strval( $page->getId() ),
1645 strval( $targetTitle->getNamespace() ),
1646 strval( $targetTitle->getDBkey() ),
1647 strval( $targetTitle->getFragment() ),
1648 strval( $targetTitle->getInterwiki() ),
1649 ] ]
1650 );
1651 }
1652
1653 /**
1654 * @covers WikiPage::insertRedirectEntry
1655 */
1656 public function testInsertRedirectEntry_doesNotInsertIfPageLatestIncorrect() {
1657 $page = $this->createPage( Title::newFromText( __METHOD__ ), 'A' );
1658 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1659
1660 $targetTitle = Title::newFromText( 'SomeTarget#Frag' );
1661 $targetTitle->mInterwiki = 'eninter';
1662 $page->insertRedirectEntry( $targetTitle, 215251 );
1663
1664 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1665 }
1666
1667 private function getRow( array $overrides = [] ) {
1668 $row = [
1669 'page_id' => '44',
1670 'page_len' => '76',
1671 'page_is_redirect' => '1',
1672 'page_latest' => '99',
1673 'page_namespace' => '3',
1674 'page_title' => 'JaJaTitle',
1675 'page_restrictions' => 'edit=autoconfirmed,sysop:move=sysop',
1676 'page_touched' => '20120101020202',
1677 'page_links_updated' => '20140101020202',
1678 ];
1679 foreach ( $overrides as $key => $value ) {
1680 $row[$key] = $value;
1681 }
1682 return (object)$row;
1683 }
1684
1685 public function provideNewFromRowSuccess() {
1686 yield 'basic row' => [
1687 $this->getRow(),
1688 function ( WikiPage $wikiPage, self $test ) {
1689 $test->assertSame( 44, $wikiPage->getId() );
1690 $test->assertSame( 76, $wikiPage->getTitle()->getLength() );
1691 $test->assertTrue( $wikiPage->isRedirect() );
1692 $test->assertSame( 99, $wikiPage->getLatest() );
1693 $test->assertSame( 3, $wikiPage->getTitle()->getNamespace() );
1694 $test->assertSame( 'JaJaTitle', $wikiPage->getTitle()->getDBkey() );
1695 $test->assertSame(
1696 [
1697 'edit' => [ 'autoconfirmed', 'sysop' ],
1698 'move' => [ 'sysop' ],
1699 ],
1700 $wikiPage->getTitle()->getAllRestrictions()
1701 );
1702 $test->assertSame( '20120101020202', $wikiPage->getTouched() );
1703 $test->assertSame( '20140101020202', $wikiPage->getLinksTimestamp() );
1704 }
1705 ];
1706 yield 'different timestamp formats' => [
1707 $this->getRow( [
1708 'page_touched' => '2012-01-01 02:02:02',
1709 'page_links_updated' => '2014-01-01 02:02:02',
1710 ] ),
1711 function ( WikiPage $wikiPage, self $test ) {
1712 $test->assertSame( '20120101020202', $wikiPage->getTouched() );
1713 $test->assertSame( '20140101020202', $wikiPage->getLinksTimestamp() );
1714 }
1715 ];
1716 yield 'no restrictions' => [
1717 $this->getRow( [
1718 'page_restrictions' => '',
1719 ] ),
1720 function ( WikiPage $wikiPage, self $test ) {
1721 $test->assertSame(
1722 [
1723 'edit' => [],
1724 'move' => [],
1725 ],
1726 $wikiPage->getTitle()->getAllRestrictions()
1727 );
1728 }
1729 ];
1730 yield 'not redirect' => [
1731 $this->getRow( [
1732 'page_is_redirect' => '0',
1733 ] ),
1734 function ( WikiPage $wikiPage, self $test ) {
1735 $test->assertFalse( $wikiPage->isRedirect() );
1736 }
1737 ];
1738 }
1739
1740 /**
1741 * @covers WikiPage::newFromRow
1742 * @covers WikiPage::loadFromRow
1743 * @dataProvider provideNewFromRowSuccess
1744 *
1745 * @param object $row
1746 * @param callable $assertions
1747 */
1748 public function testNewFromRow( $row, $assertions ) {
1749 $page = WikiPage::newFromRow( $row, 'fromdb' );
1750 $assertions( $page, $this );
1751 }
1752
1753 public function provideTestNewFromId_returnsNullOnBadPageId() {
1754 yield[ 0 ];
1755 yield[ -11 ];
1756 }
1757
1758 /**
1759 * @covers WikiPage::newFromID
1760 * @dataProvider provideTestNewFromId_returnsNullOnBadPageId
1761 */
1762 public function testNewFromId_returnsNullOnBadPageId( $pageId ) {
1763 $this->assertNull( WikiPage::newFromID( $pageId ) );
1764 }
1765
1766 /**
1767 * @covers WikiPage::newFromID
1768 */
1769 public function testNewFromId_appearsToFetchCorrectRow() {
1770 $createdPage = $this->createPage( __METHOD__, 'Xsfaij09' );
1771 $fetchedPage = WikiPage::newFromID( $createdPage->getId() );
1772 $this->assertSame( $createdPage->getId(), $fetchedPage->getId() );
1773 $this->assertEquals(
1774 $createdPage->getContent()->getNativeData(),
1775 $fetchedPage->getContent()->getNativeData()
1776 );
1777 }
1778
1779 /**
1780 * @covers WikiPage::newFromID
1781 */
1782 public function testNewFromId_returnsNullOnNonExistingId() {
1783 $this->assertNull( WikiPage::newFromID( 2147483647 ) );
1784 }
1785
1786 public function provideTestInsertProtectNullRevision() {
1787 // phpcs:disable Generic.Files.LineLength
1788 yield [
1789 'goat-message-key',
1790 [ 'edit' => 'sysop' ],
1791 [ 'edit' => '20200101040404' ],
1792 false,
1793 'Goat Reason',
1794 true,
1795 '(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)))'
1796 ];
1797 yield [
1798 'goat-key',
1799 [ 'edit' => 'sysop', 'move' => 'something' ],
1800 [ 'edit' => '20200101040404', 'move' => '20210101050505' ],
1801 false,
1802 'Goat Goat',
1803 true,
1804 '(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)))'
1805 ];
1806 // phpcs:enable
1807 }
1808
1809 /**
1810 * @dataProvider provideTestInsertProtectNullRevision
1811 * @covers WikiPage::insertProtectNullRevision
1812 * @covers WikiPage::protectDescription
1813 *
1814 * @param string $revCommentMsg
1815 * @param array $limit
1816 * @param array $expiry
1817 * @param bool $cascade
1818 * @param string $reason
1819 * @param bool|null $user true if the test sysop should be used, or null
1820 * @param string $expectedComment
1821 */
1822 public function testInsertProtectNullRevision(
1823 $revCommentMsg,
1824 array $limit,
1825 array $expiry,
1826 $cascade,
1827 $reason,
1828 $user,
1829 $expectedComment
1830 ) {
1831 $this->setContentLang( 'qqx' );
1832
1833 $page = $this->createPage( __METHOD__, 'Goat' );
1834
1835 $user = $user === null ? $user : $this->getTestSysop()->getUser();
1836
1837 $result = $page->insertProtectNullRevision(
1838 $revCommentMsg,
1839 $limit,
1840 $expiry,
1841 $cascade,
1842 $reason,
1843 $user
1844 );
1845
1846 $this->assertTrue( $result instanceof Revision );
1847 $this->assertSame( $expectedComment, $result->getComment( Revision::RAW ) );
1848 }
1849
1850 /**
1851 * @covers WikiPage::updateRevisionOn
1852 */
1853 public function testUpdateRevisionOn_existingPage() {
1854 $user = $this->getTestSysop()->getUser();
1855 $page = $this->createPage( __METHOD__, 'StartText' );
1856
1857 $revision = new Revision(
1858 [
1859 'id' => 9989,
1860 'page' => $page->getId(),
1861 'title' => $page->getTitle(),
1862 'comment' => __METHOD__,
1863 'minor_edit' => true,
1864 'text' => __METHOD__ . '-text',
1865 'len' => strlen( __METHOD__ . '-text' ),
1866 'user' => $user->getId(),
1867 'user_text' => $user->getName(),
1868 'timestamp' => '20170707040404',
1869 'content_model' => CONTENT_MODEL_WIKITEXT,
1870 'content_format' => CONTENT_FORMAT_WIKITEXT,
1871 ]
1872 );
1873
1874 $result = $page->updateRevisionOn( $this->db, $revision );
1875 $this->assertTrue( $result );
1876 $this->assertSame( 9989, $page->getLatest() );
1877 $this->assertEquals( $revision, $page->getRevision() );
1878 }
1879
1880 /**
1881 * @covers WikiPage::updateRevisionOn
1882 */
1883 public function testUpdateRevisionOn_NonExistingPage() {
1884 $user = $this->getTestSysop()->getUser();
1885 $page = $this->createPage( __METHOD__, 'StartText' );
1886 $page->doDeleteArticle( 'reason' );
1887
1888 $revision = new Revision(
1889 [
1890 'id' => 9989,
1891 'page' => $page->getId(),
1892 'title' => $page->getTitle(),
1893 'comment' => __METHOD__,
1894 'minor_edit' => true,
1895 'text' => __METHOD__ . '-text',
1896 'len' => strlen( __METHOD__ . '-text' ),
1897 'user' => $user->getId(),
1898 'user_text' => $user->getName(),
1899 'timestamp' => '20170707040404',
1900 'content_model' => CONTENT_MODEL_WIKITEXT,
1901 'content_format' => CONTENT_FORMAT_WIKITEXT,
1902 ]
1903 );
1904
1905 $result = $page->updateRevisionOn( $this->db, $revision );
1906 $this->assertFalse( $result );
1907 }
1908
1909 /**
1910 * @covers WikiPage::updateIfNewerOn
1911 */
1912 public function testUpdateIfNewerOn_olderRevision() {
1913 $user = $this->getTestSysop()->getUser();
1914 $page = $this->createPage( __METHOD__, 'StartText' );
1915 $initialRevision = $page->getRevision();
1916
1917 $olderTimeStamp = wfTimestamp(
1918 TS_MW,
1919 wfTimestamp( TS_UNIX, $initialRevision->getTimestamp() ) - 1
1920 );
1921
1922 $olderRevison = new Revision(
1923 [
1924 'id' => 9989,
1925 'page' => $page->getId(),
1926 'title' => $page->getTitle(),
1927 'comment' => __METHOD__,
1928 'minor_edit' => true,
1929 'text' => __METHOD__ . '-text',
1930 'len' => strlen( __METHOD__ . '-text' ),
1931 'user' => $user->getId(),
1932 'user_text' => $user->getName(),
1933 'timestamp' => $olderTimeStamp,
1934 'content_model' => CONTENT_MODEL_WIKITEXT,
1935 'content_format' => CONTENT_FORMAT_WIKITEXT,
1936 ]
1937 );
1938
1939 $result = $page->updateIfNewerOn( $this->db, $olderRevison );
1940 $this->assertFalse( $result );
1941 }
1942
1943 /**
1944 * @covers WikiPage::updateIfNewerOn
1945 */
1946 public function testUpdateIfNewerOn_newerRevision() {
1947 $user = $this->getTestSysop()->getUser();
1948 $page = $this->createPage( __METHOD__, 'StartText' );
1949 $initialRevision = $page->getRevision();
1950
1951 $newerTimeStamp = wfTimestamp(
1952 TS_MW,
1953 wfTimestamp( TS_UNIX, $initialRevision->getTimestamp() ) + 1
1954 );
1955
1956 $newerRevision = new Revision(
1957 [
1958 'id' => 9989,
1959 'page' => $page->getId(),
1960 'title' => $page->getTitle(),
1961 'comment' => __METHOD__,
1962 'minor_edit' => true,
1963 'text' => __METHOD__ . '-text',
1964 'len' => strlen( __METHOD__ . '-text' ),
1965 'user' => $user->getId(),
1966 'user_text' => $user->getName(),
1967 'timestamp' => $newerTimeStamp,
1968 'content_model' => CONTENT_MODEL_WIKITEXT,
1969 'content_format' => CONTENT_FORMAT_WIKITEXT,
1970 ]
1971 );
1972 $result = $page->updateIfNewerOn( $this->db, $newerRevision );
1973 $this->assertTrue( $result );
1974 }
1975
1976 /**
1977 * @covers WikiPage::insertOn
1978 */
1979 public function testInsertOn() {
1980 $title = Title::newFromText( __METHOD__ );
1981 $page = new WikiPage( $title );
1982
1983 $startTimeStamp = wfTimestampNow();
1984 $result = $page->insertOn( $this->db );
1985 $endTimeStamp = wfTimestampNow();
1986
1987 $this->assertInternalType( 'int', $result );
1988 $this->assertTrue( $result > 0 );
1989
1990 $condition = [ 'page_id' => $result ];
1991
1992 // Check the default fields have been filled
1993 $this->assertSelect(
1994 'page',
1995 [
1996 'page_namespace',
1997 'page_title',
1998 'page_restrictions',
1999 'page_is_redirect',
2000 'page_is_new',
2001 'page_latest',
2002 'page_len',
2003 ],
2004 $condition,
2005 [ [
2006 '0',
2007 __METHOD__,
2008 '',
2009 '0',
2010 '1',
2011 '0',
2012 '0',
2013 ] ]
2014 );
2015
2016 // Check the page_random field has been filled
2017 $pageRandom = $this->db->selectField( 'page', 'page_random', $condition );
2018 $this->assertTrue( (float)$pageRandom < 1 && (float)$pageRandom > 0 );
2019
2020 // Assert the touched timestamp in the DB is roughly when we inserted the page
2021 $pageTouched = $this->db->selectField( 'page', 'page_touched', $condition );
2022 $this->assertTrue(
2023 wfTimestamp( TS_UNIX, $startTimeStamp )
2024 <= wfTimestamp( TS_UNIX, $pageTouched )
2025 );
2026 $this->assertTrue(
2027 wfTimestamp( TS_UNIX, $endTimeStamp )
2028 >= wfTimestamp( TS_UNIX, $pageTouched )
2029 );
2030
2031 // Try inserting the same page again and checking the result is false (no change)
2032 $result = $page->insertOn( $this->db );
2033 $this->assertFalse( $result );
2034 }
2035
2036 /**
2037 * @covers WikiPage::insertOn
2038 */
2039 public function testInsertOn_idSpecified() {
2040 $title = Title::newFromText( __METHOD__ );
2041 $page = new WikiPage( $title );
2042 $id = 1478952189;
2043
2044 $result = $page->insertOn( $this->db, $id );
2045
2046 $this->assertSame( $id, $result );
2047
2048 $condition = [ 'page_id' => $result ];
2049
2050 // Check there is actually a row in the db
2051 $this->assertSelect(
2052 'page',
2053 [ 'page_title' ],
2054 $condition,
2055 [ [ __METHOD__ ] ]
2056 );
2057 }
2058
2059 public function provideTestDoUpdateRestrictions_setBasicRestrictions() {
2060 // Note: Once the current dates passes the date in these tests they will fail.
2061 yield 'move something' => [
2062 true,
2063 [ 'move' => 'something' ],
2064 [],
2065 [ 'edit' => [], 'move' => [ 'something' ] ],
2066 [],
2067 ];
2068 yield 'move something, edit blank' => [
2069 true,
2070 [ 'move' => 'something', 'edit' => '' ],
2071 [],
2072 [ 'edit' => [], 'move' => [ 'something' ] ],
2073 [],
2074 ];
2075 yield 'edit sysop, with expiry' => [
2076 true,
2077 [ 'edit' => 'sysop' ],
2078 [ 'edit' => '21330101020202' ],
2079 [ 'edit' => [ 'sysop' ], 'move' => [] ],
2080 [ 'edit' => '21330101020202' ],
2081 ];
2082 yield 'move and edit, move with expiry' => [
2083 true,
2084 [ 'move' => 'something', 'edit' => 'another' ],
2085 [ 'move' => '22220202010101' ],
2086 [ 'edit' => [ 'another' ], 'move' => [ 'something' ] ],
2087 [ 'move' => '22220202010101' ],
2088 ];
2089 yield 'move and edit, edit with infinity expiry' => [
2090 true,
2091 [ 'move' => 'something', 'edit' => 'another' ],
2092 [ 'edit' => 'infinity' ],
2093 [ 'edit' => [ 'another' ], 'move' => [ 'something' ] ],
2094 [ 'edit' => 'infinity' ],
2095 ];
2096 yield 'non existing, create something' => [
2097 false,
2098 [ 'create' => 'something' ],
2099 [],
2100 [ 'create' => [ 'something' ] ],
2101 [],
2102 ];
2103 yield 'non existing, create something with expiry' => [
2104 false,
2105 [ 'create' => 'something' ],
2106 [ 'create' => '23451212112233' ],
2107 [ 'create' => [ 'something' ] ],
2108 [ 'create' => '23451212112233' ],
2109 ];
2110 }
2111
2112 /**
2113 * @dataProvider provideTestDoUpdateRestrictions_setBasicRestrictions
2114 * @covers WikiPage::doUpdateRestrictions
2115 */
2116 public function testDoUpdateRestrictions_setBasicRestrictions(
2117 $pageExists,
2118 array $limit,
2119 array $expiry,
2120 array $expectedRestrictions,
2121 array $expectedRestrictionExpiries
2122 ) {
2123 if ( $pageExists ) {
2124 $page = $this->createPage( __METHOD__, 'ABC' );
2125 } else {
2126 $page = new WikiPage( Title::newFromText( __METHOD__ . '-nonexist' ) );
2127 }
2128 $user = $this->getTestSysop()->getUser();
2129 $cascade = false;
2130
2131 $status = $page->doUpdateRestrictions( $limit, $expiry, $cascade, 'aReason', $user, [] );
2132
2133 $logId = $status->getValue();
2134 $allRestrictions = $page->getTitle()->getAllRestrictions();
2135
2136 $this->assertTrue( $status->isGood() );
2137 $this->assertInternalType( 'int', $logId );
2138 $this->assertSame( $expectedRestrictions, $allRestrictions );
2139 foreach ( $expectedRestrictionExpiries as $key => $value ) {
2140 $this->assertSame( $value, $page->getTitle()->getRestrictionExpiry( $key ) );
2141 }
2142
2143 // Make sure the log entry looks good
2144 // log_params is not checked here
2145 $actorQuery = ActorMigration::newMigration()->getJoin( 'log_user' );
2146 $this->assertSelect(
2147 [ 'logging' ] + $actorQuery['tables'],
2148 [
2149 'log_comment',
2150 'log_user' => $actorQuery['fields']['log_user'],
2151 'log_user_text' => $actorQuery['fields']['log_user_text'],
2152 'log_namespace',
2153 'log_title',
2154 ],
2155 [ 'log_id' => $logId ],
2156 [ [
2157 'aReason',
2158 (string)$user->getId(),
2159 $user->getName(),
2160 (string)$page->getTitle()->getNamespace(),
2161 $page->getTitle()->getDBkey(),
2162 ] ],
2163 [],
2164 $actorQuery['joins']
2165 );
2166 }
2167
2168 /**
2169 * @covers WikiPage::doUpdateRestrictions
2170 */
2171 public function testDoUpdateRestrictions_failsOnReadOnly() {
2172 $page = $this->createPage( __METHOD__, 'ABC' );
2173 $user = $this->getTestSysop()->getUser();
2174 $cascade = false;
2175
2176 // Set read only
2177 $readOnly = $this->getMockBuilder( ReadOnlyMode::class )
2178 ->disableOriginalConstructor()
2179 ->setMethods( [ 'isReadOnly', 'getReason' ] )
2180 ->getMock();
2181 $readOnly->expects( $this->once() )
2182 ->method( 'isReadOnly' )
2183 ->will( $this->returnValue( true ) );
2184 $readOnly->expects( $this->once() )
2185 ->method( 'getReason' )
2186 ->will( $this->returnValue( 'Some Read Only Reason' ) );
2187 $this->setService( 'ReadOnlyMode', $readOnly );
2188
2189 $status = $page->doUpdateRestrictions( [], [], $cascade, 'aReason', $user, [] );
2190 $this->assertFalse( $status->isOK() );
2191 $this->assertSame( 'readonlytext', $status->getMessage()->getKey() );
2192 }
2193
2194 /**
2195 * @covers WikiPage::doUpdateRestrictions
2196 */
2197 public function testDoUpdateRestrictions_returnsGoodIfNothingChanged() {
2198 $page = $this->createPage( __METHOD__, 'ABC' );
2199 $user = $this->getTestSysop()->getUser();
2200 $cascade = false;
2201 $limit = [ 'edit' => 'sysop' ];
2202
2203 $status = $page->doUpdateRestrictions(
2204 $limit,
2205 [],
2206 $cascade,
2207 'aReason',
2208 $user,
2209 []
2210 );
2211
2212 // The first entry should have a logId as it did something
2213 $this->assertTrue( $status->isGood() );
2214 $this->assertInternalType( 'int', $status->getValue() );
2215
2216 $status = $page->doUpdateRestrictions(
2217 $limit,
2218 [],
2219 $cascade,
2220 'aReason',
2221 $user,
2222 []
2223 );
2224
2225 // The second entry should not have a logId as nothing changed
2226 $this->assertTrue( $status->isGood() );
2227 $this->assertNull( $status->getValue() );
2228 }
2229
2230 /**
2231 * @covers WikiPage::doUpdateRestrictions
2232 */
2233 public function testDoUpdateRestrictions_logEntryTypeAndAction() {
2234 $page = $this->createPage( __METHOD__, 'ABC' );
2235 $user = $this->getTestSysop()->getUser();
2236 $cascade = false;
2237
2238 // Protect the page
2239 $status = $page->doUpdateRestrictions(
2240 [ 'edit' => 'sysop' ],
2241 [],
2242 $cascade,
2243 'aReason',
2244 $user,
2245 []
2246 );
2247 $this->assertTrue( $status->isGood() );
2248 $this->assertInternalType( 'int', $status->getValue() );
2249 $this->assertSelect(
2250 'logging',
2251 [ 'log_type', 'log_action' ],
2252 [ 'log_id' => $status->getValue() ],
2253 [ [ 'protect', 'protect' ] ]
2254 );
2255
2256 // Modify the protection
2257 $status = $page->doUpdateRestrictions(
2258 [ 'edit' => 'somethingElse' ],
2259 [],
2260 $cascade,
2261 'aReason',
2262 $user,
2263 []
2264 );
2265 $this->assertTrue( $status->isGood() );
2266 $this->assertInternalType( 'int', $status->getValue() );
2267 $this->assertSelect(
2268 'logging',
2269 [ 'log_type', 'log_action' ],
2270 [ 'log_id' => $status->getValue() ],
2271 [ [ 'protect', 'modify' ] ]
2272 );
2273
2274 // Remove the protection
2275 $status = $page->doUpdateRestrictions(
2276 [],
2277 [],
2278 $cascade,
2279 'aReason',
2280 $user,
2281 []
2282 );
2283 $this->assertTrue( $status->isGood() );
2284 $this->assertInternalType( 'int', $status->getValue() );
2285 $this->assertSelect(
2286 'logging',
2287 [ 'log_type', 'log_action' ],
2288 [ 'log_id' => $status->getValue() ],
2289 [ [ 'protect', 'unprotect' ] ]
2290 );
2291 }
2292
2293 /**
2294 * @covers WikiPage::newPageUpdater
2295 * @covers WikiPage::getDerivedDataUpdater
2296 */
2297 public function testNewPageUpdater() {
2298 $user = $this->getTestUser()->getUser();
2299 $page = $this->newPage( __METHOD__, __METHOD__ );
2300
2301 /** @var Content $content */
2302 $content = $this->getMockBuilder( WikitextContent::class )
2303 ->setConstructorArgs( [ 'Hello World' ] )
2304 ->setMethods( [ 'getParserOutput' ] )
2305 ->getMock();
2306 $content->expects( $this->once() )
2307 ->method( 'getParserOutput' )
2308 ->willReturn( new ParserOutput( 'HTML' ) );
2309
2310 $preparedEditBefore = $page->prepareContentForEdit( $content, null, $user );
2311
2312 // provide context, so the cache can be kept in place
2313 $slotsUpdate = new revisionSlotsUpdate();
2314 $slotsUpdate->modifyContent( 'main', $content );
2315
2316 $updater = $page->newPageUpdater( $user, $slotsUpdate );
2317 $updater->setContent( 'main', $content );
2318 $revision = $updater->saveRevision(
2319 CommentStoreComment::newUnsavedComment( 'test' ),
2320 EDIT_NEW
2321 );
2322
2323 $preparedEditAfter = $page->prepareContentForEdit( $content, $revision, $user );
2324
2325 $this->assertSame( $revision->getId(), $page->getLatest() );
2326
2327 // Parsed output must remain cached throughout.
2328 $this->assertSame( $preparedEditBefore->output, $preparedEditAfter->output );
2329 }
2330
2331 /**
2332 * @covers WikiPage::newPageUpdater
2333 * @covers WikiPage::getDerivedDataUpdater
2334 */
2335 public function testGetDerivedDataUpdater() {
2336 $admin = $this->getTestSysop()->getUser();
2337
2338 /** @var object $page */
2339 $page = $this->createPage( __METHOD__, __METHOD__ );
2340 $page = TestingAccessWrapper::newFromObject( $page );
2341
2342 $revision = $page->getRevision()->getRevisionRecord();
2343 $user = $revision->getUser();
2344
2345 $slotsUpdate = new RevisionSlotsUpdate();
2346 $slotsUpdate->modifyContent( 'main', new WikitextContent( 'Hello World' ) );
2347
2348 // get a virgin updater
2349 $updater1 = $page->getDerivedDataUpdater( $user );
2350 $this->assertFalse( $updater1->isUpdatePrepared() );
2351
2352 $updater1->prepareUpdate( $revision );
2353
2354 // Re-use updater with same revision or content, even if base changed
2355 $this->assertSame( $updater1, $page->getDerivedDataUpdater( $user, $revision ) );
2356
2357 $slotsUpdate = RevisionSlotsUpdate::newFromContent(
2358 [ 'main' => $revision->getContent( 'main' ) ]
2359 );
2360 $this->assertSame( $updater1, $page->getDerivedDataUpdater( $user, null, $slotsUpdate ) );
2361
2362 // Don't re-use for edit if base revision ID changed
2363 $this->assertNotSame(
2364 $updater1,
2365 $page->getDerivedDataUpdater( $user, null, $slotsUpdate, true )
2366 );
2367
2368 // Don't re-use with different user
2369 $updater2a = $page->getDerivedDataUpdater( $admin, null, $slotsUpdate );
2370 $updater2a->prepareContent( $admin, $slotsUpdate, false );
2371
2372 $updater2b = $page->getDerivedDataUpdater( $user, null, $slotsUpdate );
2373 $updater2b->prepareContent( $user, $slotsUpdate, false );
2374 $this->assertNotSame( $updater2a, $updater2b );
2375
2376 // Don't re-use with different content
2377 $updater3 = $page->getDerivedDataUpdater( $admin, null, $slotsUpdate );
2378 $updater3->prepareUpdate( $revision );
2379 $this->assertNotSame( $updater2b, $updater3 );
2380
2381 // Don't re-use if no context given
2382 $updater4 = $page->getDerivedDataUpdater( $admin );
2383 $updater4->prepareUpdate( $revision );
2384 $this->assertNotSame( $updater3, $updater4 );
2385
2386 // Don't re-use if AGAIN no context given
2387 $updater5 = $page->getDerivedDataUpdater( $admin );
2388 $this->assertNotSame( $updater4, $updater5 );
2389
2390 // Don't re-use cached "virgin" unprepared updater
2391 $updater6 = $page->getDerivedDataUpdater( $admin, $revision );
2392 $this->assertNotSame( $updater5, $updater6 );
2393 }
2394
2395 }