Merge "Fix 'Tags' padding to keep it farther from the edge and document the source...
[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 // TODO: MCR: test rollback of multiple slots!
1032 $page = $this->newPage( __METHOD__ );
1033
1034 // Make some edits
1035 $text = "one";
1036 $status1 = $page->doEditContent( ContentHandler::makeContent( $text, $page->getTitle() ),
1037 "section one", EDIT_NEW, false, $admin );
1038
1039 $text .= "\n\ntwo";
1040 $status2 = $page->doEditContent( ContentHandler::makeContent( $text, $page->getTitle() ),
1041 "adding section two", 0, false, $user1 );
1042
1043 $text .= "\n\nthree";
1044 $status3 = $page->doEditContent( ContentHandler::makeContent( $text, $page->getTitle() ),
1045 "adding section three", 0, false, $user2 );
1046
1047 /** @var Revision $rev1 */
1048 /** @var Revision $rev2 */
1049 /** @var Revision $rev3 */
1050 $rev1 = $status1->getValue()['revision'];
1051 $rev2 = $status2->getValue()['revision'];
1052 $rev3 = $status3->getValue()['revision'];
1053
1054 /**
1055 * We are having issues with doRollback spuriously failing. Apparently
1056 * the last revision somehow goes missing or not committed under some
1057 * circumstances. So, make sure the revisions have the correct usernames.
1058 */
1059 $this->assertEquals( 3, Revision::countByPageId( wfGetDB( DB_REPLICA ), $page->getId() ) );
1060 $this->assertEquals( $admin->getName(), $rev1->getUserText() );
1061 $this->assertEquals( $user1->getName(), $rev2->getUserText() );
1062 $this->assertEquals( $user2->getName(), $rev3->getUserText() );
1063
1064 // Now, try the actual rollback
1065 $token = $admin->getEditToken( 'rollback' );
1066 $rollbackErrors = $page->doRollback(
1067 $user2->getName(),
1068 "testing rollback",
1069 $token,
1070 false,
1071 $resultDetails,
1072 $admin
1073 );
1074
1075 if ( $rollbackErrors ) {
1076 $this->fail(
1077 "Rollback failed:\n" .
1078 print_r( $rollbackErrors, true ) . ";\n" .
1079 print_r( $resultDetails, true )
1080 );
1081 }
1082
1083 $page = new WikiPage( $page->getTitle() );
1084 $this->assertEquals( $rev2->getSha1(), $page->getRevision()->getSha1(),
1085 "rollback did not revert to the correct revision" );
1086 $this->assertEquals( "one\n\ntwo", $page->getContent()->getNativeData() );
1087
1088 // TODO: MCR: assert origin once we write slot data
1089 // $mainSlot = $page->getRevision()->getRevisionRecord()->getSlot( 'main' );
1090 // $this->assertTrue( $mainSlot->isInherited(), 'isInherited' );
1091 // $this->assertSame( $rev2->getId(), $mainSlot->getOrigin(), 'getOrigin' );
1092 }
1093
1094 /**
1095 * @covers WikiPage::doRollback
1096 * @covers WikiPage::commitRollback
1097 */
1098 public function testDoRollback_simple() {
1099 $admin = $this->getTestSysop()->getUser();
1100
1101 $text = "one";
1102 $page = $this->newPage( __METHOD__ );
1103 $page->doEditContent(
1104 ContentHandler::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT ),
1105 "section one",
1106 EDIT_NEW,
1107 false,
1108 $admin
1109 );
1110 $rev1 = $page->getRevision();
1111
1112 $user1 = $this->getTestUser()->getUser();
1113 $text .= "\n\ntwo";
1114 $page = new WikiPage( $page->getTitle() );
1115 $page->doEditContent(
1116 ContentHandler::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT ),
1117 "adding section two",
1118 0,
1119 false,
1120 $user1
1121 );
1122
1123 # now, try the rollback
1124 $token = $admin->getEditToken( 'rollback' );
1125 $errors = $page->doRollback(
1126 $user1->getName(),
1127 "testing revert",
1128 $token,
1129 false,
1130 $details,
1131 $admin
1132 );
1133
1134 if ( $errors ) {
1135 $this->fail( "Rollback failed:\n" . print_r( $errors, true )
1136 . ";\n" . print_r( $details, true ) );
1137 }
1138
1139 $page = new WikiPage( $page->getTitle() );
1140 $this->assertEquals( $rev1->getSha1(), $page->getRevision()->getSha1(),
1141 "rollback did not revert to the correct revision" );
1142 $this->assertEquals( "one", $page->getContent()->getNativeData() );
1143 }
1144
1145 /**
1146 * @covers WikiPage::doRollback
1147 * @covers WikiPage::commitRollback
1148 */
1149 public function testDoRollbackFailureSameContent() {
1150 $admin = $this->getTestSysop()->getUser();
1151
1152 $text = "one";
1153 $page = $this->newPage( __METHOD__ );
1154 $page->doEditContent(
1155 ContentHandler::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT ),
1156 "section one",
1157 EDIT_NEW,
1158 false,
1159 $admin
1160 );
1161 $rev1 = $page->getRevision();
1162
1163 $user1 = $this->getTestUser( [ 'sysop' ] )->getUser();
1164 $text .= "\n\ntwo";
1165 $page = new WikiPage( $page->getTitle() );
1166 $page->doEditContent(
1167 ContentHandler::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT ),
1168 "adding section two",
1169 0,
1170 false,
1171 $user1
1172 );
1173
1174 # now, do a the rollback from the same user was doing the edit before
1175 $resultDetails = [];
1176 $token = $user1->getEditToken( 'rollback' );
1177 $errors = $page->doRollback(
1178 $user1->getName(),
1179 "testing revert same user",
1180 $token,
1181 false,
1182 $resultDetails,
1183 $admin
1184 );
1185
1186 $this->assertEquals( [], $errors, "Rollback failed same user" );
1187
1188 # now, try the rollback
1189 $resultDetails = [];
1190 $token = $admin->getEditToken( 'rollback' );
1191 $errors = $page->doRollback(
1192 $user1->getName(),
1193 "testing revert",
1194 $token,
1195 false,
1196 $resultDetails,
1197 $admin
1198 );
1199
1200 $this->assertEquals(
1201 [
1202 [
1203 'alreadyrolled',
1204 __METHOD__,
1205 $user1->getName(),
1206 $admin->getName(),
1207 ],
1208 ],
1209 $errors,
1210 "Rollback not failed"
1211 );
1212
1213 $page = new WikiPage( $page->getTitle() );
1214 $this->assertEquals( $rev1->getSha1(), $page->getRevision()->getSha1(),
1215 "rollback did not revert to the correct revision" );
1216 $this->assertEquals( "one", $page->getContent()->getNativeData() );
1217 }
1218
1219 /**
1220 * Tests tagging for edits that do rollback action
1221 * @covers WikiPage::doRollback
1222 */
1223 public function testDoRollbackTagging() {
1224 if ( !in_array( 'mw-rollback', ChangeTags::getSoftwareTags() ) ) {
1225 $this->markTestSkipped( 'Rollback tag deactivated, skipped the test.' );
1226 }
1227
1228 $admin = new User();
1229 $admin->setName( 'Administrator' );
1230 $admin->addToDatabase();
1231
1232 $text = 'First line';
1233 $page = $this->newPage( 'WikiPageTest_testDoRollbackTagging' );
1234 $page->doEditContent(
1235 ContentHandler::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT ),
1236 'Added first line',
1237 EDIT_NEW,
1238 false,
1239 $admin
1240 );
1241
1242 $secondUser = new User();
1243 $secondUser->setName( '92.65.217.32' );
1244 $text .= '\n\nSecond line';
1245 $page = new WikiPage( $page->getTitle() );
1246 $page->doEditContent(
1247 ContentHandler::makeContent( $text, $page->getTitle(), CONTENT_MODEL_WIKITEXT ),
1248 'Adding second line',
1249 0,
1250 false,
1251 $secondUser
1252 );
1253
1254 // Now, try the rollback
1255 $admin->addGroup( 'sysop' ); // Make the test user a sysop
1256 $token = $admin->getEditToken( 'rollback' );
1257 $errors = $page->doRollback(
1258 $secondUser->getName(),
1259 'testing rollback',
1260 $token,
1261 false,
1262 $resultDetails,
1263 $admin
1264 );
1265
1266 // If doRollback completed without errors
1267 if ( $errors === [] ) {
1268 $tags = $resultDetails[ 'tags' ];
1269 $this->assertContains( 'mw-rollback', $tags );
1270 }
1271 }
1272
1273 public function provideGetAutoDeleteReason() {
1274 return [
1275 [
1276 [],
1277 false,
1278 false
1279 ],
1280
1281 [
1282 [
1283 [ "first edit", null ],
1284 ],
1285 "/first edit.*only contributor/",
1286 false
1287 ],
1288
1289 [
1290 [
1291 [ "first edit", null ],
1292 [ "second edit", null ],
1293 ],
1294 "/second edit.*only contributor/",
1295 true
1296 ],
1297
1298 [
1299 [
1300 [ "first edit", "127.0.2.22" ],
1301 [ "second edit", "127.0.3.33" ],
1302 ],
1303 "/second edit/",
1304 true
1305 ],
1306
1307 [
1308 [
1309 [
1310 "first edit: "
1311 . "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam "
1312 . " nonumy eirmod tempor invidunt ut labore et dolore magna "
1313 . "aliquyam erat, sed diam voluptua. At vero eos et accusam "
1314 . "et justo duo dolores et ea rebum. Stet clita kasd gubergren, "
1315 . "no sea takimata sanctus est Lorem ipsum dolor sit amet.'",
1316 null
1317 ],
1318 ],
1319 '/first edit:.*\.\.\."/',
1320 false
1321 ],
1322
1323 [
1324 [
1325 [ "first edit", "127.0.2.22" ],
1326 [ "", "127.0.3.33" ],
1327 ],
1328 "/before blanking.*first edit/",
1329 true
1330 ],
1331
1332 ];
1333 }
1334
1335 /**
1336 * @dataProvider provideGetAutoDeleteReason
1337 * @covers WikiPage::getAutoDeleteReason
1338 */
1339 public function testGetAutoDeleteReason( $edits, $expectedResult, $expectedHistory ) {
1340 global $wgUser;
1341
1342 // NOTE: assume Help namespace to contain wikitext
1343 $page = $this->newPage( "Help:WikiPageTest_testGetAutoDeleteReason" );
1344
1345 $c = 1;
1346
1347 foreach ( $edits as $edit ) {
1348 $user = new User();
1349
1350 if ( !empty( $edit[1] ) ) {
1351 $user->setName( $edit[1] );
1352 } else {
1353 $user = $wgUser;
1354 }
1355
1356 $content = ContentHandler::makeContent( $edit[0], $page->getTitle(), $page->getContentModel() );
1357
1358 $page->doEditContent( $content, "test edit $c", $c < 2 ? EDIT_NEW : 0, false, $user );
1359
1360 $c += 1;
1361 }
1362
1363 $reason = $page->getAutoDeleteReason( $hasHistory );
1364
1365 if ( is_bool( $expectedResult ) || is_null( $expectedResult ) ) {
1366 $this->assertEquals( $expectedResult, $reason );
1367 } else {
1368 $this->assertTrue( (bool)preg_match( $expectedResult, $reason ),
1369 "Autosummary didn't match expected pattern $expectedResult: $reason" );
1370 }
1371
1372 $this->assertEquals( $expectedHistory, $hasHistory,
1373 "expected \$hasHistory to be " . var_export( $expectedHistory, true ) );
1374
1375 $page->doDeleteArticle( "done" );
1376 }
1377
1378 public function providePreSaveTransform() {
1379 return [
1380 [ 'hello this is ~~~',
1381 "hello this is [[Special:Contributions/127.0.0.1|127.0.0.1]]",
1382 ],
1383 [ 'hello \'\'this\'\' is <nowiki>~~~</nowiki>',
1384 'hello \'\'this\'\' is <nowiki>~~~</nowiki>',
1385 ],
1386 ];
1387 }
1388
1389 /**
1390 * @covers WikiPage::factory
1391 */
1392 public function testWikiPageFactory() {
1393 $title = Title::makeTitle( NS_FILE, 'Someimage.png' );
1394 $page = WikiPage::factory( $title );
1395 $this->assertEquals( WikiFilePage::class, get_class( $page ) );
1396
1397 $title = Title::makeTitle( NS_CATEGORY, 'SomeCategory' );
1398 $page = WikiPage::factory( $title );
1399 $this->assertEquals( WikiCategoryPage::class, get_class( $page ) );
1400
1401 $title = Title::makeTitle( NS_MAIN, 'SomePage' );
1402 $page = WikiPage::factory( $title );
1403 $this->assertEquals( WikiPage::class, get_class( $page ) );
1404 }
1405
1406 /**
1407 * @covers WikiPage::loadPageData
1408 * @covers WikiPage::wasLoadedFrom
1409 */
1410 public function testLoadPageData() {
1411 $title = Title::makeTitle( NS_MAIN, 'SomePage' );
1412 $page = WikiPage::factory( $title );
1413
1414 $this->assertFalse( $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_NORMAL );
1420 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject::READ_NORMAL ) );
1421 $this->assertFalse( $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_LATEST );
1426 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject::READ_NORMAL ) );
1427 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject::READ_LATEST ) );
1428 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject::READ_LOCKING ) );
1429 $this->assertFalse( $page->wasLoadedFrom( IDBAccessObject::READ_EXCLUSIVE ) );
1430
1431 $page->loadPageData( IDBAccessObject::READ_LOCKING );
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->assertFalse( $page->wasLoadedFrom( IDBAccessObject::READ_EXCLUSIVE ) );
1436
1437 $page->loadPageData( IDBAccessObject::READ_EXCLUSIVE );
1438 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject::READ_NORMAL ) );
1439 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject::READ_LATEST ) );
1440 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject::READ_LOCKING ) );
1441 $this->assertTrue( $page->wasLoadedFrom( IDBAccessObject::READ_EXCLUSIVE ) );
1442 }
1443
1444 /**
1445 * @dataProvider provideCommentMigrationOnDeletion
1446 *
1447 * @param int $writeStage
1448 * @param int $readStage
1449 */
1450 public function testCommentMigrationOnDeletion( $writeStage, $readStage ) {
1451 $this->setMwGlobals( 'wgCommentTableSchemaMigrationStage', $writeStage );
1452 $this->overrideMwServices();
1453
1454 $dbr = wfGetDB( DB_REPLICA );
1455
1456 $page = $this->createPage(
1457 __METHOD__,
1458 "foo",
1459 CONTENT_MODEL_WIKITEXT
1460 );
1461 $revid = $page->getLatest();
1462 if ( $writeStage > MIGRATION_OLD ) {
1463 $comment_id = $dbr->selectField(
1464 'revision_comment_temp',
1465 'revcomment_comment_id',
1466 [ 'revcomment_rev' => $revid ],
1467 __METHOD__
1468 );
1469 }
1470
1471 $this->setMwGlobals( 'wgCommentTableSchemaMigrationStage', $readStage );
1472 $this->overrideMwServices();
1473
1474 $page->doDeleteArticle( "testing deletion" );
1475
1476 if ( $readStage > MIGRATION_OLD ) {
1477 // Didn't leave behind any 'revision_comment_temp' rows
1478 $n = $dbr->selectField(
1479 'revision_comment_temp', 'COUNT(*)', [ 'revcomment_rev' => $revid ], __METHOD__
1480 );
1481 $this->assertEquals( 0, $n, 'no entry in revision_comment_temp after deletion' );
1482
1483 // Copied or upgraded the comment_id, as applicable
1484 $ar_comment_id = $dbr->selectField(
1485 'archive',
1486 'ar_comment_id',
1487 [ 'ar_rev_id' => $revid ],
1488 __METHOD__
1489 );
1490 if ( $writeStage > MIGRATION_OLD ) {
1491 $this->assertSame( $comment_id, $ar_comment_id );
1492 } else {
1493 $this->assertNotEquals( 0, $ar_comment_id );
1494 }
1495 }
1496
1497 // Copied rev_comment, if applicable
1498 if ( $readStage <= MIGRATION_WRITE_BOTH && $writeStage <= MIGRATION_WRITE_BOTH ) {
1499 $ar_comment = $dbr->selectField(
1500 'archive',
1501 'ar_comment',
1502 [ 'ar_rev_id' => $revid ],
1503 __METHOD__
1504 );
1505 $this->assertSame( 'testing', $ar_comment );
1506 }
1507 }
1508
1509 public function provideCommentMigrationOnDeletion() {
1510 return [
1511 [ MIGRATION_OLD, MIGRATION_OLD ],
1512 [ MIGRATION_OLD, MIGRATION_WRITE_BOTH ],
1513 [ MIGRATION_OLD, MIGRATION_WRITE_NEW ],
1514 [ MIGRATION_WRITE_BOTH, MIGRATION_OLD ],
1515 [ MIGRATION_WRITE_BOTH, MIGRATION_WRITE_BOTH ],
1516 [ MIGRATION_WRITE_BOTH, MIGRATION_WRITE_NEW ],
1517 [ MIGRATION_WRITE_BOTH, MIGRATION_NEW ],
1518 [ MIGRATION_WRITE_NEW, MIGRATION_WRITE_BOTH ],
1519 [ MIGRATION_WRITE_NEW, MIGRATION_WRITE_NEW ],
1520 [ MIGRATION_WRITE_NEW, MIGRATION_NEW ],
1521 [ MIGRATION_NEW, MIGRATION_WRITE_BOTH ],
1522 [ MIGRATION_NEW, MIGRATION_WRITE_NEW ],
1523 [ MIGRATION_NEW, MIGRATION_NEW ],
1524 ];
1525 }
1526
1527 /**
1528 * @covers WikiPage::updateCategoryCounts
1529 */
1530 public function testUpdateCategoryCounts() {
1531 $page = new WikiPage( Title::newFromText( __METHOD__ ) );
1532
1533 // Add an initial category
1534 $page->updateCategoryCounts( [ 'A' ], [], 0 );
1535
1536 $this->assertEquals( 1, Category::newFromName( 'A' )->getPageCount() );
1537 $this->assertEquals( 0, Category::newFromName( 'B' )->getPageCount() );
1538 $this->assertEquals( 0, Category::newFromName( 'C' )->getPageCount() );
1539
1540 // Add a new category
1541 $page->updateCategoryCounts( [ 'B' ], [], 0 );
1542
1543 $this->assertEquals( 1, Category::newFromName( 'A' )->getPageCount() );
1544 $this->assertEquals( 1, Category::newFromName( 'B' )->getPageCount() );
1545 $this->assertEquals( 0, Category::newFromName( 'C' )->getPageCount() );
1546
1547 // Add and remove a category
1548 $page->updateCategoryCounts( [ 'C' ], [ 'A' ], 0 );
1549
1550 $this->assertEquals( 0, Category::newFromName( 'A' )->getPageCount() );
1551 $this->assertEquals( 1, Category::newFromName( 'B' )->getPageCount() );
1552 $this->assertEquals( 1, Category::newFromName( 'C' )->getPageCount() );
1553 }
1554
1555 public function provideUpdateRedirectOn() {
1556 yield [ '#REDIRECT [[Foo]]', true, null, true, true, 0 ];
1557 yield [ '#REDIRECT [[Foo]]', true, 'Foo', true, false, 1 ];
1558 yield [ 'SomeText', false, null, false, true, 0 ];
1559 yield [ 'SomeText', false, 'Foo', false, false, 1 ];
1560 }
1561
1562 /**
1563 * @dataProvider provideUpdateRedirectOn
1564 * @covers WikiPage::updateRedirectOn
1565 *
1566 * @param string $initialText
1567 * @param bool $initialRedirectState
1568 * @param string|null $redirectTitle
1569 * @param bool|null $lastRevIsRedirect
1570 * @param bool $expectedSuccess
1571 * @param int $expectedRowCount
1572 */
1573 public function testUpdateRedirectOn(
1574 $initialText,
1575 $initialRedirectState,
1576 $redirectTitle,
1577 $lastRevIsRedirect,
1578 $expectedSuccess,
1579 $expectedRowCount
1580 ) {
1581 static $pageCounter = 0;
1582 $pageCounter++;
1583
1584 $page = $this->createPage( Title::newFromText( __METHOD__ . $pageCounter ), $initialText );
1585 $this->assertSame( $initialRedirectState, $page->isRedirect() );
1586
1587 $redirectTitle = is_string( $redirectTitle )
1588 ? Title::newFromText( $redirectTitle )
1589 : $redirectTitle;
1590
1591 $success = $page->updateRedirectOn( $this->db, $redirectTitle, $lastRevIsRedirect );
1592 $this->assertSame( $expectedSuccess, $success, 'Success assertion' );
1593 /**
1594 * updateRedirectOn explicitly updates the redirect table (and not the page table).
1595 * Most of core checks the page table for redirect status, so we have to be ugly and
1596 * assert a select from the table here.
1597 */
1598 $this->assertRedirectTableCountForPageId( $page->getId(), $expectedRowCount );
1599 }
1600
1601 private function assertRedirectTableCountForPageId( $pageId, $expected ) {
1602 $this->assertSelect(
1603 'redirect',
1604 'COUNT(*)',
1605 [ 'rd_from' => $pageId ],
1606 [ [ strval( $expected ) ] ]
1607 );
1608 }
1609
1610 /**
1611 * @covers WikiPage::insertRedirectEntry
1612 */
1613 public function testInsertRedirectEntry_insertsRedirectEntry() {
1614 $page = $this->createPage( Title::newFromText( __METHOD__ ), 'A' );
1615 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1616
1617 $targetTitle = Title::newFromText( 'SomeTarget#Frag' );
1618 $targetTitle->mInterwiki = 'eninter';
1619 $page->insertRedirectEntry( $targetTitle, null );
1620
1621 $this->assertSelect(
1622 'redirect',
1623 [ 'rd_from', 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
1624 [ 'rd_from' => $page->getId() ],
1625 [ [
1626 strval( $page->getId() ),
1627 strval( $targetTitle->getNamespace() ),
1628 strval( $targetTitle->getDBkey() ),
1629 strval( $targetTitle->getFragment() ),
1630 strval( $targetTitle->getInterwiki() ),
1631 ] ]
1632 );
1633 }
1634
1635 /**
1636 * @covers WikiPage::insertRedirectEntry
1637 */
1638 public function testInsertRedirectEntry_insertsRedirectEntryWithPageLatest() {
1639 $page = $this->createPage( Title::newFromText( __METHOD__ ), 'A' );
1640 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1641
1642 $targetTitle = Title::newFromText( 'SomeTarget#Frag' );
1643 $targetTitle->mInterwiki = 'eninter';
1644 $page->insertRedirectEntry( $targetTitle, $page->getLatest() );
1645
1646 $this->assertSelect(
1647 'redirect',
1648 [ 'rd_from', 'rd_namespace', 'rd_title', 'rd_fragment', 'rd_interwiki' ],
1649 [ 'rd_from' => $page->getId() ],
1650 [ [
1651 strval( $page->getId() ),
1652 strval( $targetTitle->getNamespace() ),
1653 strval( $targetTitle->getDBkey() ),
1654 strval( $targetTitle->getFragment() ),
1655 strval( $targetTitle->getInterwiki() ),
1656 ] ]
1657 );
1658 }
1659
1660 /**
1661 * @covers WikiPage::insertRedirectEntry
1662 */
1663 public function testInsertRedirectEntry_doesNotInsertIfPageLatestIncorrect() {
1664 $page = $this->createPage( Title::newFromText( __METHOD__ ), 'A' );
1665 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1666
1667 $targetTitle = Title::newFromText( 'SomeTarget#Frag' );
1668 $targetTitle->mInterwiki = 'eninter';
1669 $page->insertRedirectEntry( $targetTitle, 215251 );
1670
1671 $this->assertRedirectTableCountForPageId( $page->getId(), 0 );
1672 }
1673
1674 private function getRow( array $overrides = [] ) {
1675 $row = [
1676 'page_id' => '44',
1677 'page_len' => '76',
1678 'page_is_redirect' => '1',
1679 'page_latest' => '99',
1680 'page_namespace' => '3',
1681 'page_title' => 'JaJaTitle',
1682 'page_restrictions' => 'edit=autoconfirmed,sysop:move=sysop',
1683 'page_touched' => '20120101020202',
1684 'page_links_updated' => '20140101020202',
1685 ];
1686 foreach ( $overrides as $key => $value ) {
1687 $row[$key] = $value;
1688 }
1689 return (object)$row;
1690 }
1691
1692 public function provideNewFromRowSuccess() {
1693 yield 'basic row' => [
1694 $this->getRow(),
1695 function ( WikiPage $wikiPage, self $test ) {
1696 $test->assertSame( 44, $wikiPage->getId() );
1697 $test->assertSame( 76, $wikiPage->getTitle()->getLength() );
1698 $test->assertTrue( $wikiPage->isRedirect() );
1699 $test->assertSame( 99, $wikiPage->getLatest() );
1700 $test->assertSame( 3, $wikiPage->getTitle()->getNamespace() );
1701 $test->assertSame( 'JaJaTitle', $wikiPage->getTitle()->getDBkey() );
1702 $test->assertSame(
1703 [
1704 'edit' => [ 'autoconfirmed', 'sysop' ],
1705 'move' => [ 'sysop' ],
1706 ],
1707 $wikiPage->getTitle()->getAllRestrictions()
1708 );
1709 $test->assertSame( '20120101020202', $wikiPage->getTouched() );
1710 $test->assertSame( '20140101020202', $wikiPage->getLinksTimestamp() );
1711 }
1712 ];
1713 yield 'different timestamp formats' => [
1714 $this->getRow( [
1715 'page_touched' => '2012-01-01 02:02:02',
1716 'page_links_updated' => '2014-01-01 02:02:02',
1717 ] ),
1718 function ( WikiPage $wikiPage, self $test ) {
1719 $test->assertSame( '20120101020202', $wikiPage->getTouched() );
1720 $test->assertSame( '20140101020202', $wikiPage->getLinksTimestamp() );
1721 }
1722 ];
1723 yield 'no restrictions' => [
1724 $this->getRow( [
1725 'page_restrictions' => '',
1726 ] ),
1727 function ( WikiPage $wikiPage, self $test ) {
1728 $test->assertSame(
1729 [
1730 'edit' => [],
1731 'move' => [],
1732 ],
1733 $wikiPage->getTitle()->getAllRestrictions()
1734 );
1735 }
1736 ];
1737 yield 'not redirect' => [
1738 $this->getRow( [
1739 'page_is_redirect' => '0',
1740 ] ),
1741 function ( WikiPage $wikiPage, self $test ) {
1742 $test->assertFalse( $wikiPage->isRedirect() );
1743 }
1744 ];
1745 }
1746
1747 /**
1748 * @covers WikiPage::newFromRow
1749 * @covers WikiPage::loadFromRow
1750 * @dataProvider provideNewFromRowSuccess
1751 *
1752 * @param object $row
1753 * @param callable $assertions
1754 */
1755 public function testNewFromRow( $row, $assertions ) {
1756 $page = WikiPage::newFromRow( $row, 'fromdb' );
1757 $assertions( $page, $this );
1758 }
1759
1760 public function provideTestNewFromId_returnsNullOnBadPageId() {
1761 yield[ 0 ];
1762 yield[ -11 ];
1763 }
1764
1765 /**
1766 * @covers WikiPage::newFromID
1767 * @dataProvider provideTestNewFromId_returnsNullOnBadPageId
1768 */
1769 public function testNewFromId_returnsNullOnBadPageId( $pageId ) {
1770 $this->assertNull( WikiPage::newFromID( $pageId ) );
1771 }
1772
1773 /**
1774 * @covers WikiPage::newFromID
1775 */
1776 public function testNewFromId_appearsToFetchCorrectRow() {
1777 $createdPage = $this->createPage( __METHOD__, 'Xsfaij09' );
1778 $fetchedPage = WikiPage::newFromID( $createdPage->getId() );
1779 $this->assertSame( $createdPage->getId(), $fetchedPage->getId() );
1780 $this->assertEquals(
1781 $createdPage->getContent()->getNativeData(),
1782 $fetchedPage->getContent()->getNativeData()
1783 );
1784 }
1785
1786 /**
1787 * @covers WikiPage::newFromID
1788 */
1789 public function testNewFromId_returnsNullOnNonExistingId() {
1790 $this->assertNull( WikiPage::newFromID( 2147483647 ) );
1791 }
1792
1793 public function provideTestInsertProtectNullRevision() {
1794 // phpcs:disable Generic.Files.LineLength
1795 yield [
1796 'goat-message-key',
1797 [ 'edit' => 'sysop' ],
1798 [ 'edit' => '20200101040404' ],
1799 false,
1800 'Goat Reason',
1801 true,
1802 '(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)))'
1803 ];
1804 yield [
1805 'goat-key',
1806 [ 'edit' => 'sysop', 'move' => 'something' ],
1807 [ 'edit' => '20200101040404', 'move' => '20210101050505' ],
1808 false,
1809 'Goat Goat',
1810 true,
1811 '(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)))'
1812 ];
1813 // phpcs:enable
1814 }
1815
1816 /**
1817 * @dataProvider provideTestInsertProtectNullRevision
1818 * @covers WikiPage::insertProtectNullRevision
1819 * @covers WikiPage::protectDescription
1820 *
1821 * @param string $revCommentMsg
1822 * @param array $limit
1823 * @param array $expiry
1824 * @param bool $cascade
1825 * @param string $reason
1826 * @param bool|null $user true if the test sysop should be used, or null
1827 * @param string $expectedComment
1828 */
1829 public function testInsertProtectNullRevision(
1830 $revCommentMsg,
1831 array $limit,
1832 array $expiry,
1833 $cascade,
1834 $reason,
1835 $user,
1836 $expectedComment
1837 ) {
1838 $this->setContentLang( 'qqx' );
1839
1840 $page = $this->createPage( __METHOD__, 'Goat' );
1841
1842 $user = $user === null ? $user : $this->getTestSysop()->getUser();
1843
1844 $result = $page->insertProtectNullRevision(
1845 $revCommentMsg,
1846 $limit,
1847 $expiry,
1848 $cascade,
1849 $reason,
1850 $user
1851 );
1852
1853 $this->assertTrue( $result instanceof Revision );
1854 $this->assertSame( $expectedComment, $result->getComment( Revision::RAW ) );
1855 }
1856
1857 /**
1858 * @covers WikiPage::updateRevisionOn
1859 */
1860 public function testUpdateRevisionOn_existingPage() {
1861 $user = $this->getTestSysop()->getUser();
1862 $page = $this->createPage( __METHOD__, 'StartText' );
1863
1864 $revision = new Revision(
1865 [
1866 'id' => 9989,
1867 'page' => $page->getId(),
1868 'title' => $page->getTitle(),
1869 'comment' => __METHOD__,
1870 'minor_edit' => true,
1871 'text' => __METHOD__ . '-text',
1872 'len' => strlen( __METHOD__ . '-text' ),
1873 'user' => $user->getId(),
1874 'user_text' => $user->getName(),
1875 'timestamp' => '20170707040404',
1876 'content_model' => CONTENT_MODEL_WIKITEXT,
1877 'content_format' => CONTENT_FORMAT_WIKITEXT,
1878 ]
1879 );
1880
1881 $result = $page->updateRevisionOn( $this->db, $revision );
1882 $this->assertTrue( $result );
1883 $this->assertSame( 9989, $page->getLatest() );
1884 $this->assertEquals( $revision, $page->getRevision() );
1885 }
1886
1887 /**
1888 * @covers WikiPage::updateRevisionOn
1889 */
1890 public function testUpdateRevisionOn_NonExistingPage() {
1891 $user = $this->getTestSysop()->getUser();
1892 $page = $this->createPage( __METHOD__, 'StartText' );
1893 $page->doDeleteArticle( 'reason' );
1894
1895 $revision = new Revision(
1896 [
1897 'id' => 9989,
1898 'page' => $page->getId(),
1899 'title' => $page->getTitle(),
1900 'comment' => __METHOD__,
1901 'minor_edit' => true,
1902 'text' => __METHOD__ . '-text',
1903 'len' => strlen( __METHOD__ . '-text' ),
1904 'user' => $user->getId(),
1905 'user_text' => $user->getName(),
1906 'timestamp' => '20170707040404',
1907 'content_model' => CONTENT_MODEL_WIKITEXT,
1908 'content_format' => CONTENT_FORMAT_WIKITEXT,
1909 ]
1910 );
1911
1912 $result = $page->updateRevisionOn( $this->db, $revision );
1913 $this->assertFalse( $result );
1914 }
1915
1916 /**
1917 * @covers WikiPage::updateIfNewerOn
1918 */
1919 public function testUpdateIfNewerOn_olderRevision() {
1920 $user = $this->getTestSysop()->getUser();
1921 $page = $this->createPage( __METHOD__, 'StartText' );
1922 $initialRevision = $page->getRevision();
1923
1924 $olderTimeStamp = wfTimestamp(
1925 TS_MW,
1926 wfTimestamp( TS_UNIX, $initialRevision->getTimestamp() ) - 1
1927 );
1928
1929 $olderRevison = new Revision(
1930 [
1931 'id' => 9989,
1932 'page' => $page->getId(),
1933 'title' => $page->getTitle(),
1934 'comment' => __METHOD__,
1935 'minor_edit' => true,
1936 'text' => __METHOD__ . '-text',
1937 'len' => strlen( __METHOD__ . '-text' ),
1938 'user' => $user->getId(),
1939 'user_text' => $user->getName(),
1940 'timestamp' => $olderTimeStamp,
1941 'content_model' => CONTENT_MODEL_WIKITEXT,
1942 'content_format' => CONTENT_FORMAT_WIKITEXT,
1943 ]
1944 );
1945
1946 $result = $page->updateIfNewerOn( $this->db, $olderRevison );
1947 $this->assertFalse( $result );
1948 }
1949
1950 /**
1951 * @covers WikiPage::updateIfNewerOn
1952 */
1953 public function testUpdateIfNewerOn_newerRevision() {
1954 $user = $this->getTestSysop()->getUser();
1955 $page = $this->createPage( __METHOD__, 'StartText' );
1956 $initialRevision = $page->getRevision();
1957
1958 $newerTimeStamp = wfTimestamp(
1959 TS_MW,
1960 wfTimestamp( TS_UNIX, $initialRevision->getTimestamp() ) + 1
1961 );
1962
1963 $newerRevision = new Revision(
1964 [
1965 'id' => 9989,
1966 'page' => $page->getId(),
1967 'title' => $page->getTitle(),
1968 'comment' => __METHOD__,
1969 'minor_edit' => true,
1970 'text' => __METHOD__ . '-text',
1971 'len' => strlen( __METHOD__ . '-text' ),
1972 'user' => $user->getId(),
1973 'user_text' => $user->getName(),
1974 'timestamp' => $newerTimeStamp,
1975 'content_model' => CONTENT_MODEL_WIKITEXT,
1976 'content_format' => CONTENT_FORMAT_WIKITEXT,
1977 ]
1978 );
1979 $result = $page->updateIfNewerOn( $this->db, $newerRevision );
1980 $this->assertTrue( $result );
1981 }
1982
1983 /**
1984 * @covers WikiPage::insertOn
1985 */
1986 public function testInsertOn() {
1987 $title = Title::newFromText( __METHOD__ );
1988 $page = new WikiPage( $title );
1989
1990 $startTimeStamp = wfTimestampNow();
1991 $result = $page->insertOn( $this->db );
1992 $endTimeStamp = wfTimestampNow();
1993
1994 $this->assertInternalType( 'int', $result );
1995 $this->assertTrue( $result > 0 );
1996
1997 $condition = [ 'page_id' => $result ];
1998
1999 // Check the default fields have been filled
2000 $this->assertSelect(
2001 'page',
2002 [
2003 'page_namespace',
2004 'page_title',
2005 'page_restrictions',
2006 'page_is_redirect',
2007 'page_is_new',
2008 'page_latest',
2009 'page_len',
2010 ],
2011 $condition,
2012 [ [
2013 '0',
2014 __METHOD__,
2015 '',
2016 '0',
2017 '1',
2018 '0',
2019 '0',
2020 ] ]
2021 );
2022
2023 // Check the page_random field has been filled
2024 $pageRandom = $this->db->selectField( 'page', 'page_random', $condition );
2025 $this->assertTrue( (float)$pageRandom < 1 && (float)$pageRandom > 0 );
2026
2027 // Assert the touched timestamp in the DB is roughly when we inserted the page
2028 $pageTouched = $this->db->selectField( 'page', 'page_touched', $condition );
2029 $this->assertTrue(
2030 wfTimestamp( TS_UNIX, $startTimeStamp )
2031 <= wfTimestamp( TS_UNIX, $pageTouched )
2032 );
2033 $this->assertTrue(
2034 wfTimestamp( TS_UNIX, $endTimeStamp )
2035 >= wfTimestamp( TS_UNIX, $pageTouched )
2036 );
2037
2038 // Try inserting the same page again and checking the result is false (no change)
2039 $result = $page->insertOn( $this->db );
2040 $this->assertFalse( $result );
2041 }
2042
2043 /**
2044 * @covers WikiPage::insertOn
2045 */
2046 public function testInsertOn_idSpecified() {
2047 $title = Title::newFromText( __METHOD__ );
2048 $page = new WikiPage( $title );
2049 $id = 1478952189;
2050
2051 $result = $page->insertOn( $this->db, $id );
2052
2053 $this->assertSame( $id, $result );
2054
2055 $condition = [ 'page_id' => $result ];
2056
2057 // Check there is actually a row in the db
2058 $this->assertSelect(
2059 'page',
2060 [ 'page_title' ],
2061 $condition,
2062 [ [ __METHOD__ ] ]
2063 );
2064 }
2065
2066 public function provideTestDoUpdateRestrictions_setBasicRestrictions() {
2067 // Note: Once the current dates passes the date in these tests they will fail.
2068 yield 'move something' => [
2069 true,
2070 [ 'move' => 'something' ],
2071 [],
2072 [ 'edit' => [], 'move' => [ 'something' ] ],
2073 [],
2074 ];
2075 yield 'move something, edit blank' => [
2076 true,
2077 [ 'move' => 'something', 'edit' => '' ],
2078 [],
2079 [ 'edit' => [], 'move' => [ 'something' ] ],
2080 [],
2081 ];
2082 yield 'edit sysop, with expiry' => [
2083 true,
2084 [ 'edit' => 'sysop' ],
2085 [ 'edit' => '21330101020202' ],
2086 [ 'edit' => [ 'sysop' ], 'move' => [] ],
2087 [ 'edit' => '21330101020202' ],
2088 ];
2089 yield 'move and edit, move with expiry' => [
2090 true,
2091 [ 'move' => 'something', 'edit' => 'another' ],
2092 [ 'move' => '22220202010101' ],
2093 [ 'edit' => [ 'another' ], 'move' => [ 'something' ] ],
2094 [ 'move' => '22220202010101' ],
2095 ];
2096 yield 'move and edit, edit with infinity expiry' => [
2097 true,
2098 [ 'move' => 'something', 'edit' => 'another' ],
2099 [ 'edit' => 'infinity' ],
2100 [ 'edit' => [ 'another' ], 'move' => [ 'something' ] ],
2101 [ 'edit' => 'infinity' ],
2102 ];
2103 yield 'non existing, create something' => [
2104 false,
2105 [ 'create' => 'something' ],
2106 [],
2107 [ 'create' => [ 'something' ] ],
2108 [],
2109 ];
2110 yield 'non existing, create something with expiry' => [
2111 false,
2112 [ 'create' => 'something' ],
2113 [ 'create' => '23451212112233' ],
2114 [ 'create' => [ 'something' ] ],
2115 [ 'create' => '23451212112233' ],
2116 ];
2117 }
2118
2119 /**
2120 * @dataProvider provideTestDoUpdateRestrictions_setBasicRestrictions
2121 * @covers WikiPage::doUpdateRestrictions
2122 */
2123 public function testDoUpdateRestrictions_setBasicRestrictions(
2124 $pageExists,
2125 array $limit,
2126 array $expiry,
2127 array $expectedRestrictions,
2128 array $expectedRestrictionExpiries
2129 ) {
2130 if ( $pageExists ) {
2131 $page = $this->createPage( __METHOD__, 'ABC' );
2132 } else {
2133 $page = new WikiPage( Title::newFromText( __METHOD__ . '-nonexist' ) );
2134 }
2135 $user = $this->getTestSysop()->getUser();
2136 $cascade = false;
2137
2138 $status = $page->doUpdateRestrictions( $limit, $expiry, $cascade, 'aReason', $user, [] );
2139
2140 $logId = $status->getValue();
2141 $allRestrictions = $page->getTitle()->getAllRestrictions();
2142
2143 $this->assertTrue( $status->isGood() );
2144 $this->assertInternalType( 'int', $logId );
2145 $this->assertSame( $expectedRestrictions, $allRestrictions );
2146 foreach ( $expectedRestrictionExpiries as $key => $value ) {
2147 $this->assertSame( $value, $page->getTitle()->getRestrictionExpiry( $key ) );
2148 }
2149
2150 // Make sure the log entry looks good
2151 // log_params is not checked here
2152 $actorQuery = ActorMigration::newMigration()->getJoin( 'log_user' );
2153 $this->assertSelect(
2154 [ 'logging' ] + $actorQuery['tables'],
2155 [
2156 'log_comment',
2157 'log_user' => $actorQuery['fields']['log_user'],
2158 'log_user_text' => $actorQuery['fields']['log_user_text'],
2159 'log_namespace',
2160 'log_title',
2161 ],
2162 [ 'log_id' => $logId ],
2163 [ [
2164 'aReason',
2165 (string)$user->getId(),
2166 $user->getName(),
2167 (string)$page->getTitle()->getNamespace(),
2168 $page->getTitle()->getDBkey(),
2169 ] ],
2170 [],
2171 $actorQuery['joins']
2172 );
2173 }
2174
2175 /**
2176 * @covers WikiPage::doUpdateRestrictions
2177 */
2178 public function testDoUpdateRestrictions_failsOnReadOnly() {
2179 $page = $this->createPage( __METHOD__, 'ABC' );
2180 $user = $this->getTestSysop()->getUser();
2181 $cascade = false;
2182
2183 // Set read only
2184 $readOnly = $this->getMockBuilder( ReadOnlyMode::class )
2185 ->disableOriginalConstructor()
2186 ->setMethods( [ 'isReadOnly', 'getReason' ] )
2187 ->getMock();
2188 $readOnly->expects( $this->once() )
2189 ->method( 'isReadOnly' )
2190 ->will( $this->returnValue( true ) );
2191 $readOnly->expects( $this->once() )
2192 ->method( 'getReason' )
2193 ->will( $this->returnValue( 'Some Read Only Reason' ) );
2194 $this->setService( 'ReadOnlyMode', $readOnly );
2195
2196 $status = $page->doUpdateRestrictions( [], [], $cascade, 'aReason', $user, [] );
2197 $this->assertFalse( $status->isOK() );
2198 $this->assertSame( 'readonlytext', $status->getMessage()->getKey() );
2199 }
2200
2201 /**
2202 * @covers WikiPage::doUpdateRestrictions
2203 */
2204 public function testDoUpdateRestrictions_returnsGoodIfNothingChanged() {
2205 $page = $this->createPage( __METHOD__, 'ABC' );
2206 $user = $this->getTestSysop()->getUser();
2207 $cascade = false;
2208 $limit = [ 'edit' => 'sysop' ];
2209
2210 $status = $page->doUpdateRestrictions(
2211 $limit,
2212 [],
2213 $cascade,
2214 'aReason',
2215 $user,
2216 []
2217 );
2218
2219 // The first entry should have a logId as it did something
2220 $this->assertTrue( $status->isGood() );
2221 $this->assertInternalType( 'int', $status->getValue() );
2222
2223 $status = $page->doUpdateRestrictions(
2224 $limit,
2225 [],
2226 $cascade,
2227 'aReason',
2228 $user,
2229 []
2230 );
2231
2232 // The second entry should not have a logId as nothing changed
2233 $this->assertTrue( $status->isGood() );
2234 $this->assertNull( $status->getValue() );
2235 }
2236
2237 /**
2238 * @covers WikiPage::doUpdateRestrictions
2239 */
2240 public function testDoUpdateRestrictions_logEntryTypeAndAction() {
2241 $page = $this->createPage( __METHOD__, 'ABC' );
2242 $user = $this->getTestSysop()->getUser();
2243 $cascade = false;
2244
2245 // Protect the page
2246 $status = $page->doUpdateRestrictions(
2247 [ 'edit' => 'sysop' ],
2248 [],
2249 $cascade,
2250 'aReason',
2251 $user,
2252 []
2253 );
2254 $this->assertTrue( $status->isGood() );
2255 $this->assertInternalType( 'int', $status->getValue() );
2256 $this->assertSelect(
2257 'logging',
2258 [ 'log_type', 'log_action' ],
2259 [ 'log_id' => $status->getValue() ],
2260 [ [ 'protect', 'protect' ] ]
2261 );
2262
2263 // Modify the protection
2264 $status = $page->doUpdateRestrictions(
2265 [ 'edit' => 'somethingElse' ],
2266 [],
2267 $cascade,
2268 'aReason',
2269 $user,
2270 []
2271 );
2272 $this->assertTrue( $status->isGood() );
2273 $this->assertInternalType( 'int', $status->getValue() );
2274 $this->assertSelect(
2275 'logging',
2276 [ 'log_type', 'log_action' ],
2277 [ 'log_id' => $status->getValue() ],
2278 [ [ 'protect', 'modify' ] ]
2279 );
2280
2281 // Remove the protection
2282 $status = $page->doUpdateRestrictions(
2283 [],
2284 [],
2285 $cascade,
2286 'aReason',
2287 $user,
2288 []
2289 );
2290 $this->assertTrue( $status->isGood() );
2291 $this->assertInternalType( 'int', $status->getValue() );
2292 $this->assertSelect(
2293 'logging',
2294 [ 'log_type', 'log_action' ],
2295 [ 'log_id' => $status->getValue() ],
2296 [ [ 'protect', 'unprotect' ] ]
2297 );
2298 }
2299
2300 /**
2301 * @covers WikiPage::newPageUpdater
2302 * @covers WikiPage::getDerivedDataUpdater
2303 */
2304 public function testNewPageUpdater() {
2305 $user = $this->getTestUser()->getUser();
2306 $page = $this->newPage( __METHOD__, __METHOD__ );
2307
2308 /** @var Content $content */
2309 $content = $this->getMockBuilder( WikitextContent::class )
2310 ->setConstructorArgs( [ 'Hello World' ] )
2311 ->setMethods( [ 'getParserOutput' ] )
2312 ->getMock();
2313 $content->expects( $this->once() )
2314 ->method( 'getParserOutput' )
2315 ->willReturn( new ParserOutput( 'HTML' ) );
2316
2317 $updater = $page->newPageUpdater( $user );
2318 $updater->setContent( 'main', $content );
2319 $revision = $updater->saveRevision(
2320 CommentStoreComment::newUnsavedComment( 'test' ),
2321 EDIT_NEW
2322 );
2323
2324 $this->assertSame( $revision->getId(), $page->getLatest() );
2325 }
2326
2327 /**
2328 * @covers WikiPage::newPageUpdater
2329 * @covers WikiPage::getDerivedDataUpdater
2330 */
2331 public function testGetDerivedDataUpdater() {
2332 $admin = $this->getTestSysop()->getUser();
2333
2334 /** @var object $page */
2335 $page = $this->createPage( __METHOD__, __METHOD__ );
2336 $page = TestingAccessWrapper::newFromObject( $page );
2337
2338 $revision = $page->getRevision()->getRevisionRecord();
2339 $user = $revision->getUser();
2340
2341 $slotsUpdate = new RevisionSlotsUpdate();
2342 $slotsUpdate->modifyContent( 'main', new WikitextContent( 'Hello World' ) );
2343
2344 // get a virgin updater
2345 $updater1 = $page->getDerivedDataUpdater( $user );
2346 $this->assertFalse( $updater1->isUpdatePrepared() );
2347
2348 $updater1->prepareUpdate( $revision );
2349
2350 // Re-use updater with same revision or content
2351 $this->assertSame( $updater1, $page->getDerivedDataUpdater( $user, $revision ) );
2352
2353 $slotsUpdate = RevisionSlotsUpdate::newFromContent(
2354 [ 'main' => $revision->getContent( 'main' ) ]
2355 );
2356 $this->assertSame( $updater1, $page->getDerivedDataUpdater( $user, null, $slotsUpdate ) );
2357
2358 // Don't re-use with different user
2359 $updater2a = $page->getDerivedDataUpdater( $admin, null, $slotsUpdate );
2360 $updater2a->prepareContent( $admin, $slotsUpdate, false );
2361
2362 $updater2b = $page->getDerivedDataUpdater( $user, null, $slotsUpdate );
2363 $updater2b->prepareContent( $user, $slotsUpdate, false );
2364 $this->assertNotSame( $updater2a, $updater2b );
2365
2366 // Don't re-use with different content
2367 $updater3 = $page->getDerivedDataUpdater( $admin, null, $slotsUpdate );
2368 $updater3->prepareUpdate( $revision );
2369 $this->assertNotSame( $updater2b, $updater3 );
2370
2371 // Don't re-use if no context given
2372 $updater4 = $page->getDerivedDataUpdater( $admin );
2373 $updater4->prepareUpdate( $revision );
2374 $this->assertNotSame( $updater3, $updater4 );
2375
2376 // Don't re-use if AGAIN no context given
2377 $updater5 = $page->getDerivedDataUpdater( $admin );
2378 $this->assertNotSame( $updater4, $updater5 );
2379
2380 // Don't re-use cached "virgin" unprepared updater
2381 $updater6 = $page->getDerivedDataUpdater( $admin, $revision );
2382 $this->assertNotSame( $updater5, $updater6 );
2383 }
2384
2385 }