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