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