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