MediaWiki  master
RevisionStoreDbTestBase.php
Go to the documentation of this file.
1 <?php
2 
4 
28 use Title;
38 
44 
48  private $testPageTitle;
49 
53  private $testPage;
54 
58  abstract protected function getMcrMigrationStage();
59 
63  protected function getContentHandlerUseDB() {
64  return true;
65  }
66 
70  abstract protected function getMcrTablesToReset();
71 
72  public function setUp() {
73  parent::setUp();
74  $this->tablesUsed[] = 'archive';
75  $this->tablesUsed[] = 'page';
76  $this->tablesUsed[] = 'revision';
77  $this->tablesUsed[] = 'comment';
78 
79  $this->tablesUsed += $this->getMcrTablesToReset();
80 
81  $this->setMwGlobals( [
82  'wgMultiContentRevisionSchemaMigrationStage' => $this->getMcrMigrationStage(),
83  'wgContentHandlerUseDB' => $this->getContentHandlerUseDB(),
84  'wgActorTableSchemaMigrationStage' => SCHEMA_COMPAT_OLD,
85  ] );
86 
87  $this->overrideMwServices();
88  }
89 
90  protected function addCoreDBData() {
91  // Blank out. This would fail with a modified schema, and we don't need it.
92  }
93 
97  protected function getTestPageTitle() {
98  if ( $this->testPageTitle ) {
99  return $this->testPageTitle;
100  }
101 
102  $this->testPageTitle = Title::newFromText( 'UTPage-' . __CLASS__ );
103  return $this->testPageTitle;
104  }
105 
109  protected function getTestPage() {
110  if ( $this->testPage ) {
111  return $this->testPage;
112  }
113 
114  $title = $this->getTestPageTitle();
115  $this->testPage = WikiPage::factory( $title );
116 
117  if ( !$this->testPage->exists() ) {
118  // Make sure we don't write to the live db.
120 
121  $user = static::getTestSysop()->getUser();
122 
123  $this->testPage->doEditContent(
124  new WikitextContent( 'UTContent-' . __CLASS__ ),
125  'UTPageSummary-' . __CLASS__,
127  false,
128  $user
129  );
130  }
131 
132  return $this->testPage;
133  }
134 
138  private function getLoadBalancerMock( array $server ) {
139  $domain = new DatabaseDomain( $server['dbname'], null, $server['tablePrefix'] );
140 
141  $lb = $this->getMockBuilder( LoadBalancer::class )
142  ->setMethods( [ 'reallyOpenConnection' ] )
143  ->setConstructorArgs( [
144  [ 'servers' => [ $server ], 'localDomain' => $domain ]
145  ] )
146  ->getMock();
147 
148  $lb->method( 'reallyOpenConnection' )->willReturnCallback(
149  function ( array $server, $dbNameOverride ) {
150  return $this->getDatabaseMock( $server );
151  }
152  );
153 
154  return $lb;
155  }
156 
160  private function getDatabaseMock( array $params ) {
161  $db = $this->getMockBuilder( DatabaseSqlite::class )
162  ->setMethods( [ 'select', 'doQuery', 'open', 'closeConnection', 'isOpen' ] )
163  ->setConstructorArgs( [ $params ] )
164  ->getMock();
165 
166  $db->method( 'select' )->willReturn( new FakeResultWrapper( [] ) );
167  $db->method( 'isOpen' )->willReturn( true );
168 
169  return $db;
170  }
171 
172  public function provideDomainCheck() {
173  yield [ false, 'test', '' ];
174  yield [ 'test', 'test', '' ];
175 
176  yield [ false, 'test', 'foo_' ];
177  yield [ 'test-foo_', 'test', 'foo_' ];
178 
179  yield [ false, 'dash-test', '' ];
180  yield [ 'dash-test', 'dash-test', '' ];
181 
182  yield [ false, 'underscore_test', 'foo_' ];
183  yield [ 'underscore_test-foo_', 'underscore_test', 'foo_' ];
184  }
185 
190  public function testDomainCheck( $wikiId, $dbName, $dbPrefix ) {
191  $this->setMwGlobals(
192  [
193  'wgDBname' => $dbName,
194  'wgDBprefix' => $dbPrefix,
195  ]
196  );
197 
198  $loadBalancer = $this->getLoadBalancerMock(
199  [
200  'host' => '*dummy*',
201  'dbDirectory' => '*dummy*',
202  'user' => 'test',
203  'password' => 'test',
204  'flags' => 0,
205  'variables' => [],
206  'schema' => '',
207  'cliMode' => true,
208  'agent' => '',
209  'load' => 100,
210  'profiler' => null,
211  'trxProfiler' => new TransactionProfiler(),
212  'connLogger' => new \Psr\Log\NullLogger(),
213  'queryLogger' => new \Psr\Log\NullLogger(),
214  'errorLogger' => function () {
215  },
216  'deprecationLogger' => function () {
217  },
218  'type' => 'test',
219  'dbname' => $dbName,
220  'tablePrefix' => $dbPrefix,
221  ]
222  );
223  $db = $loadBalancer->getConnection( DB_REPLICA );
224 
226  $blobStore = $this->getMockBuilder( SqlBlobStore::class )
227  ->disableOriginalConstructor()
228  ->getMock();
229 
230  $store = new RevisionStore(
231  $loadBalancer,
232  $blobStore,
233  new WANObjectCache( [ 'cache' => new HashBagOStuff() ] ),
234  MediaWikiServices::getInstance()->getCommentStore(),
235  MediaWikiServices::getInstance()->getContentModelStore(),
236  MediaWikiServices::getInstance()->getSlotRoleStore(),
237  MediaWikiServices::getInstance()->getSlotRoleRegistry(),
238  $this->getMcrMigrationStage(),
239  MediaWikiServices::getInstance()->getActorMigration(),
240  $wikiId
241  );
242 
243  $count = $store->countRevisionsByPageId( $db, 0 );
244 
245  // Dummy check to make PhpUnit happy. We are really only interested in
246  // countRevisionsByPageId not failing due to the DB domain check.
247  $this->assertSame( 0, $count );
248  }
249 
250  protected function assertLinkTargetsEqual( LinkTarget $l1, LinkTarget $l2 ) {
251  $this->assertEquals( $l1->getDBkey(), $l2->getDBkey() );
252  $this->assertEquals( $l1->getNamespace(), $l2->getNamespace() );
253  $this->assertEquals( $l1->getFragment(), $l2->getFragment() );
254  $this->assertEquals( $l1->getInterwiki(), $l2->getInterwiki() );
255  }
256 
258  $this->assertEquals(
259  $r1->getPageAsLinkTarget()->getNamespace(),
260  $r2->getPageAsLinkTarget()->getNamespace()
261  );
262 
263  $this->assertEquals(
264  $r1->getPageAsLinkTarget()->getText(),
265  $r2->getPageAsLinkTarget()->getText()
266  );
267 
268  if ( $r1->getParentId() ) {
269  $this->assertEquals( $r1->getParentId(), $r2->getParentId() );
270  }
271 
272  $this->assertEquals( $r1->getUser()->getName(), $r2->getUser()->getName() );
273  $this->assertEquals( $r1->getUser()->getId(), $r2->getUser()->getId() );
274  $this->assertEquals( $r1->getComment(), $r2->getComment() );
275  $this->assertEquals( $r1->getTimestamp(), $r2->getTimestamp() );
276  $this->assertEquals( $r1->getVisibility(), $r2->getVisibility() );
277  $this->assertEquals( $r1->getSha1(), $r2->getSha1() );
278  $this->assertEquals( $r1->getSize(), $r2->getSize() );
279  $this->assertEquals( $r1->getPageId(), $r2->getPageId() );
280  $this->assertArrayEquals( $r1->getSlotRoles(), $r2->getSlotRoles() );
281  $this->assertEquals( $r1->getWikiId(), $r2->getWikiId() );
282  $this->assertEquals( $r1->isMinor(), $r2->isMinor() );
283  foreach ( $r1->getSlotRoles() as $role ) {
284  $this->assertSlotRecordsEqual( $r1->getSlot( $role ), $r2->getSlot( $role ) );
285  $this->assertTrue( $r1->getContent( $role )->equals( $r2->getContent( $role ) ) );
286  }
287  foreach ( [
292  ] as $field ) {
293  $this->assertEquals( $r1->isDeleted( $field ), $r2->isDeleted( $field ) );
294  }
295  }
296 
297  protected function assertSlotRecordsEqual( SlotRecord $s1, SlotRecord $s2 ) {
298  $this->assertSame( $s1->getRole(), $s2->getRole() );
299  $this->assertSame( $s1->getModel(), $s2->getModel() );
300  $this->assertSame( $s1->getFormat(), $s2->getFormat() );
301  $this->assertSame( $s1->getSha1(), $s2->getSha1() );
302  $this->assertSame( $s1->getSize(), $s2->getSize() );
303  $this->assertTrue( $s1->getContent()->equals( $s2->getContent() ) );
304 
305  $s1->hasRevision() ? $this->assertSame( $s1->getRevision(), $s2->getRevision() ) : null;
306  $s1->hasAddress() ? $this->assertSame( $s1->hasAddress(), $s2->hasAddress() ) : null;
307  }
308 
309  protected function assertRevisionCompleteness( RevisionRecord $r ) {
310  $this->assertTrue( $r->hasSlot( SlotRecord::MAIN ) );
311  $this->assertInstanceOf( SlotRecord::class, $r->getSlot( SlotRecord::MAIN ) );
312  $this->assertInstanceOf( Content::class, $r->getContent( SlotRecord::MAIN ) );
313 
314  foreach ( $r->getSlotRoles() as $role ) {
315  $this->assertSlotCompleteness( $r, $r->getSlot( $role ) );
316  }
317  }
318 
319  protected function assertSlotCompleteness( RevisionRecord $r, SlotRecord $slot ) {
320  $this->assertTrue( $slot->hasAddress() );
321  $this->assertSame( $r->getId(), $slot->getRevision() );
322 
323  $this->assertInstanceOf( Content::class, $slot->getContent() );
324  }
325 
331  private function getRevisionRecordFromDetailsArray( $details = [] ) {
332  // Convert some values that can't be provided by dataProviders
333  if ( isset( $details['user'] ) && $details['user'] === true ) {
334  $details['user'] = $this->getTestUser()->getUser();
335  }
336  if ( isset( $details['page'] ) && $details['page'] === true ) {
337  $details['page'] = $this->getTestPage()->getId();
338  }
339  if ( isset( $details['parent'] ) && $details['parent'] === true ) {
340  $details['parent'] = $this->getTestPage()->getLatest();
341  }
342 
343  // Create the RevisionRecord with any available data
344  $rev = new MutableRevisionRecord( $this->getTestPageTitle() );
345  isset( $details['slot'] ) ? $rev->setSlot( $details['slot'] ) : null;
346  isset( $details['parent'] ) ? $rev->setParentId( $details['parent'] ) : null;
347  isset( $details['page'] ) ? $rev->setPageId( $details['page'] ) : null;
348  isset( $details['size'] ) ? $rev->setSize( $details['size'] ) : null;
349  isset( $details['sha1'] ) ? $rev->setSha1( $details['sha1'] ) : null;
350  isset( $details['comment'] ) ? $rev->setComment( $details['comment'] ) : null;
351  isset( $details['timestamp'] ) ? $rev->setTimestamp( $details['timestamp'] ) : null;
352  isset( $details['minor'] ) ? $rev->setMinorEdit( $details['minor'] ) : null;
353  isset( $details['user'] ) ? $rev->setUser( $details['user'] ) : null;
354  isset( $details['visibility'] ) ? $rev->setVisibility( $details['visibility'] ) : null;
355  isset( $details['id'] ) ? $rev->setId( $details['id'] ) : null;
356 
357  if ( isset( $details['content'] ) ) {
358  foreach ( $details['content'] as $role => $content ) {
359  $rev->setContent( $role, $content );
360  }
361  }
362 
363  return $rev;
364  }
365 
367  yield 'Bare minimum revision insertion' => [
368  [
369  'slot' => SlotRecord::newUnsaved( SlotRecord::MAIN, new WikitextContent( 'Chicken' ) ),
370  'page' => true,
371  'comment' => $this->getRandomCommentStoreComment(),
372  'timestamp' => '20171117010101',
373  'user' => true,
374  ],
375  ];
376  yield 'Detailed revision insertion' => [
377  [
378  'slot' => SlotRecord::newUnsaved( SlotRecord::MAIN, new WikitextContent( 'Chicken' ) ),
379  'parent' => true,
380  'page' => true,
381  'comment' => $this->getRandomCommentStoreComment(),
382  'timestamp' => '20171117010101',
383  'user' => true,
384  'minor' => true,
385  'visibility' => RevisionRecord::DELETED_RESTRICTED,
386  ],
387  ];
388  }
389 
390  protected function getRandomCommentStoreComment() {
391  return CommentStoreComment::newUnsavedComment( __METHOD__ . '.' . rand( 0, 1000 ) );
392  }
393 
401  array $revDetails = []
402  ) {
403  $title = $this->getTestPageTitle();
404  $rev = $this->getRevisionRecordFromDetailsArray( $revDetails );
405 
406  $this->overrideMwServices();
407  $store = MediaWikiServices::getInstance()->getRevisionStore();
408  $return = $store->insertRevisionOn( $rev, wfGetDB( DB_MASTER ) );
409 
410  // is the new revision correct?
411  $this->assertRevisionCompleteness( $return );
412  $this->assertLinkTargetsEqual( $title, $return->getPageAsLinkTarget() );
413  $this->assertRevisionRecordsEqual( $rev, $return );
414 
415  // can we load it from the store?
416  $loaded = $store->getRevisionById( $return->getId() );
417  $this->assertRevisionCompleteness( $loaded );
418  $this->assertRevisionRecordsEqual( $return, $loaded );
419 
420  // can we find it directly in the database?
421  $this->assertRevisionExistsInDatabase( $return );
422  }
423 
425  $row = $this->revisionToRow( new Revision( $rev ), [] );
426 
427  // unset nulled fields
428  unset( $row->rev_content_model );
429  unset( $row->rev_content_format );
430 
431  // unset fake fields
432  unset( $row->rev_comment_text );
433  unset( $row->rev_comment_data );
434  unset( $row->rev_comment_cid );
435  unset( $row->rev_comment_id );
436 
437  $store = MediaWikiServices::getInstance()->getRevisionStore();
438  $queryInfo = $store->getQueryInfo( [ 'user' ] );
439 
440  $row = get_object_vars( $row );
441  $this->assertSelect(
442  $queryInfo['tables'],
443  array_keys( $row ),
444  [ 'rev_id' => $rev->getId() ],
445  [ array_values( $row ) ],
446  [],
447  $queryInfo['joins']
448  );
449  }
450 
455  protected function assertSameSlotContent( SlotRecord $a, SlotRecord $b ) {
456  // Assert that the same blob address has been used.
457  $this->assertSame( $a->getAddress(), $b->getAddress() );
458  }
459 
464  $title = $this->getTestPageTitle();
465  $revDetails = [
466  'slot' => SlotRecord::newUnsaved( SlotRecord::MAIN, new WikitextContent( 'Chicken' ) ),
467  'parent' => true,
468  'comment' => $this->getRandomCommentStoreComment(),
469  'timestamp' => '20171117010101',
470  'user' => true,
471  ];
472 
473  $this->overrideMwServices();
474  $store = MediaWikiServices::getInstance()->getRevisionStore();
475 
476  // Insert the first revision
477  $revOne = $this->getRevisionRecordFromDetailsArray( $revDetails );
478  $firstReturn = $store->insertRevisionOn( $revOne, wfGetDB( DB_MASTER ) );
479  $this->assertLinkTargetsEqual( $title, $firstReturn->getPageAsLinkTarget() );
480  $this->assertRevisionRecordsEqual( $revOne, $firstReturn );
481 
482  // Insert a second revision inheriting the same blob address
483  $revDetails['slot'] = SlotRecord::newInherited( $firstReturn->getSlot( SlotRecord::MAIN ) );
484  $revTwo = $this->getRevisionRecordFromDetailsArray( $revDetails );
485  $secondReturn = $store->insertRevisionOn( $revTwo, wfGetDB( DB_MASTER ) );
486  $this->assertLinkTargetsEqual( $title, $secondReturn->getPageAsLinkTarget() );
487  $this->assertRevisionRecordsEqual( $revTwo, $secondReturn );
488 
489  $firstMainSlot = $firstReturn->getSlot( SlotRecord::MAIN );
490  $secondMainSlot = $secondReturn->getSlot( SlotRecord::MAIN );
491 
492  $this->assertSameSlotContent( $firstMainSlot, $secondMainSlot );
493 
494  // And that different revisions have been created.
495  $this->assertNotSame( $firstReturn->getId(), $secondReturn->getId() );
496 
497  // Make sure the slot rows reference the correct revision
498  $this->assertSame( $firstReturn->getId(), $firstMainSlot->getRevision() );
499  $this->assertSame( $secondReturn->getId(), $secondMainSlot->getRevision() );
500  }
501 
503  yield 'no slot' => [
504  [
505  'comment' => $this->getRandomCommentStoreComment(),
506  'timestamp' => '20171117010101',
507  'user' => true,
508  ],
509  new InvalidArgumentException( 'main slot must be provided' )
510  ];
511  yield 'no main slot' => [
512  [
513  'slot' => SlotRecord::newUnsaved( 'aux', new WikitextContent( 'Turkey' ) ),
514  'comment' => $this->getRandomCommentStoreComment(),
515  'timestamp' => '20171117010101',
516  'user' => true,
517  ],
518  new InvalidArgumentException( 'main slot must be provided' )
519  ];
520  yield 'no timestamp' => [
521  [
522  'slot' => SlotRecord::newUnsaved( SlotRecord::MAIN, new WikitextContent( 'Chicken' ) ),
523  'comment' => $this->getRandomCommentStoreComment(),
524  'user' => true,
525  ],
526  new IncompleteRevisionException( 'timestamp field must not be NULL!' )
527  ];
528  yield 'no comment' => [
529  [
530  'slot' => SlotRecord::newUnsaved( SlotRecord::MAIN, new WikitextContent( 'Chicken' ) ),
531  'timestamp' => '20171117010101',
532  'user' => true,
533  ],
534  new IncompleteRevisionException( 'comment must not be NULL!' )
535  ];
536  yield 'no user' => [
537  [
538  'slot' => SlotRecord::newUnsaved( SlotRecord::MAIN, new WikitextContent( 'Chicken' ) ),
539  'comment' => $this->getRandomCommentStoreComment(),
540  'timestamp' => '20171117010101',
541  ],
542  new IncompleteRevisionException( 'user must not be NULL!' )
543  ];
544  }
545 
551  array $revDetails = [],
552  Exception $exception
553  ) {
554  $rev = $this->getRevisionRecordFromDetailsArray( $revDetails );
555 
556  $store = MediaWikiServices::getInstance()->getRevisionStore();
557 
558  $this->setExpectedException(
559  get_class( $exception ),
560  $exception->getMessage(),
561  $exception->getCode()
562  );
563  $store->insertRevisionOn( $rev, wfGetDB( DB_MASTER ) );
564  }
565 
566  public function provideNewNullRevision() {
567  yield [
568  Title::newFromText( 'UTPage_notAutoCreated' ),
569  [ 'content' => [ 'main' => new WikitextContent( 'Flubber1' ) ] ],
570  CommentStoreComment::newUnsavedComment( __METHOD__ . ' comment1' ),
571  true,
572  ];
573  yield [
574  Title::newFromText( 'UTPage_notAutoCreated' ),
575  [ 'content' => [ 'main' => new WikitextContent( 'Flubber2' ) ] ],
576  CommentStoreComment::newUnsavedComment( __METHOD__ . ' comment2', [ 'a' => 1 ] ),
577  false,
578  ];
579  }
580 
586  public function testNewNullRevision( Title $title, $revDetails, $comment, $minor = false ) {
587  $this->overrideMwServices();
588 
589  $user = TestUserRegistry::getMutableTestUser( __METHOD__ )->getUser();
590  $page = WikiPage::factory( $title );
591 
592  if ( !$page->exists() ) {
593  $page->doEditContent( new WikitextContent( __METHOD__ ), __METHOD__, EDIT_NEW );
594  }
595 
596  $revDetails['page'] = $page->getId();
597  $revDetails['timestamp'] = wfTimestampNow();
598  $revDetails['comment'] = CommentStoreComment::newUnsavedComment( 'Base' );
599  $revDetails['user'] = $user;
600 
601  $baseRev = $this->getRevisionRecordFromDetailsArray( $revDetails );
602  $store = MediaWikiServices::getInstance()->getRevisionStore();
603 
604  $dbw = wfGetDB( DB_MASTER );
605  $baseRev = $store->insertRevisionOn( $baseRev, $dbw );
606  $page->updateRevisionOn( $dbw, new Revision( $baseRev ), $page->getLatest() );
607 
608  $record = $store->newNullRevision(
609  wfGetDB( DB_MASTER ),
610  $title,
611  $comment,
612  $minor,
613  $user
614  );
615 
616  $this->assertEquals( $title->getNamespace(), $record->getPageAsLinkTarget()->getNamespace() );
617  $this->assertEquals( $title->getDBkey(), $record->getPageAsLinkTarget()->getDBkey() );
618  $this->assertEquals( $comment, $record->getComment() );
619  $this->assertEquals( $minor, $record->isMinor() );
620  $this->assertEquals( $user->getName(), $record->getUser()->getName() );
621  $this->assertEquals( $baseRev->getId(), $record->getParentId() );
622 
623  $this->assertArrayEquals(
624  $baseRev->getSlotRoles(),
625  $record->getSlotRoles()
626  );
627 
628  foreach ( $baseRev->getSlotRoles() as $role ) {
629  $parentSlot = $baseRev->getSlot( $role );
630  $slot = $record->getSlot( $role );
631 
632  $this->assertTrue( $slot->isInherited(), 'isInherited' );
633  $this->assertSame( $parentSlot->getOrigin(), $slot->getOrigin(), 'getOrigin' );
634  $this->assertSameSlotContent( $parentSlot, $slot );
635  }
636  }
637 
642  $store = MediaWikiServices::getInstance()->getRevisionStore();
643  $record = $store->newNullRevision(
644  wfGetDB( DB_MASTER ),
645  Title::newFromText( __METHOD__ . '.iDontExist!' ),
646  CommentStoreComment::newUnsavedComment( __METHOD__ . ' comment' ),
647  false,
648  TestUserRegistry::getMutableTestUser( __METHOD__ )->getUser()
649  );
650  $this->assertNull( $record );
651  }
652 
657  $page = $this->getTestPage();
658  $status = $page->doEditContent( new WikitextContent( __METHOD__ ), __METHOD__ );
660  $rev = $status->value['revision'];
661 
662  $store = MediaWikiServices::getInstance()->getRevisionStore();
663  $revisionRecord = $store->getRevisionById( $rev->getId() );
664  $result = $store->getRcIdIfUnpatrolled( $revisionRecord );
665 
666  $this->assertGreaterThan( 0, $result );
667  $this->assertSame(
668  $store->getRecentChange( $revisionRecord )->getAttribute( 'rc_id' ),
669  $result
670  );
671  }
672 
677  // This assumes that sysops are auto patrolled
678  $sysop = $this->getTestSysop()->getUser();
679  $page = $this->getTestPage();
680  $status = $page->doEditContent(
681  new WikitextContent( __METHOD__ ),
682  __METHOD__,
683  0,
684  false,
685  $sysop
686  );
688  $rev = $status->value['revision'];
689 
690  $store = MediaWikiServices::getInstance()->getRevisionStore();
691  $revisionRecord = $store->getRevisionById( $rev->getId() );
692  $result = $store->getRcIdIfUnpatrolled( $revisionRecord );
693 
694  $this->assertSame( 0, $result );
695  }
696 
700  public function testGetRecentChange() {
701  $page = $this->getTestPage();
702  $content = new WikitextContent( __METHOD__ );
703  $status = $page->doEditContent( $content, __METHOD__ );
705  $rev = $status->value['revision'];
706 
707  $store = MediaWikiServices::getInstance()->getRevisionStore();
708  $revRecord = $store->getRevisionById( $rev->getId() );
709  $recentChange = $store->getRecentChange( $revRecord );
710 
711  $this->assertEquals( $rev->getId(), $recentChange->getAttribute( 'rc_this_oldid' ) );
712  $this->assertEquals( $rev->getRecentChange(), $recentChange );
713  }
714 
718  public function testGetRevisionById() {
719  $page = $this->getTestPage();
720  $content = new WikitextContent( __METHOD__ );
721  $status = $page->doEditContent( $content, __METHOD__ );
723  $rev = $status->value['revision'];
724 
725  $store = MediaWikiServices::getInstance()->getRevisionStore();
726  $revRecord = $store->getRevisionById( $rev->getId() );
727 
728  $this->assertSame( $rev->getId(), $revRecord->getId() );
729  $this->assertTrue( $revRecord->getSlot( SlotRecord::MAIN )->getContent()->equals( $content ) );
730  $this->assertSame( __METHOD__, $revRecord->getComment()->text );
731  }
732 
736  public function testGetRevisionByTitle() {
737  $page = $this->getTestPage();
738  $content = new WikitextContent( __METHOD__ );
739  $status = $page->doEditContent( $content, __METHOD__ );
741  $rev = $status->value['revision'];
742 
743  $store = MediaWikiServices::getInstance()->getRevisionStore();
744  $revRecord = $store->getRevisionByTitle( $page->getTitle() );
745 
746  $this->assertSame( $rev->getId(), $revRecord->getId() );
747  $this->assertTrue( $revRecord->getSlot( SlotRecord::MAIN )->getContent()->equals( $content ) );
748  $this->assertSame( __METHOD__, $revRecord->getComment()->text );
749  }
750 
754  public function testGetRevisionByPageId() {
755  $page = $this->getTestPage();
756  $content = new WikitextContent( __METHOD__ );
757  $status = $page->doEditContent( $content, __METHOD__ );
759  $rev = $status->value['revision'];
760 
761  $store = MediaWikiServices::getInstance()->getRevisionStore();
762  $revRecord = $store->getRevisionByPageId( $page->getId() );
763 
764  $this->assertSame( $rev->getId(), $revRecord->getId() );
765  $this->assertTrue( $revRecord->getSlot( SlotRecord::MAIN )->getContent()->equals( $content ) );
766  $this->assertSame( __METHOD__, $revRecord->getComment()->text );
767  }
768 
772  public function testGetRevisionByTimestamp() {
773  // Make sure there is 1 second between the last revision and the rev we create...
774  // Otherwise we might not get the correct revision and the test may fail...
775  // :(
776  $page = $this->getTestPage();
777  sleep( 1 );
778  $content = new WikitextContent( __METHOD__ );
779  $status = $page->doEditContent( $content, __METHOD__ );
781  $rev = $status->value['revision'];
782 
783  $store = MediaWikiServices::getInstance()->getRevisionStore();
784  $revRecord = $store->getRevisionByTimestamp(
785  $page->getTitle(),
786  $rev->getTimestamp()
787  );
788 
789  $this->assertSame( $rev->getId(), $revRecord->getId() );
790  $this->assertTrue( $revRecord->getSlot( SlotRecord::MAIN )->getContent()->equals( $content ) );
791  $this->assertSame( __METHOD__, $revRecord->getComment()->text );
792  }
793 
794  protected function revisionToRow( Revision $rev, $options = [ 'page', 'user', 'comment' ] ) {
795  // XXX: the WikiPage object loads another RevisionRecord from the database. Not great.
796  $page = WikiPage::factory( $rev->getTitle() );
797 
798  $fields = [
799  'rev_id' => (string)$rev->getId(),
800  'rev_page' => (string)$rev->getPage(),
801  'rev_timestamp' => $this->db->timestamp( $rev->getTimestamp() ),
802  'rev_user_text' => (string)$rev->getUserText(),
803  'rev_user' => (string)$rev->getUser(),
804  'rev_minor_edit' => $rev->isMinor() ? '1' : '0',
805  'rev_deleted' => (string)$rev->getVisibility(),
806  'rev_len' => (string)$rev->getSize(),
807  'rev_parent_id' => (string)$rev->getParentId(),
808  'rev_sha1' => (string)$rev->getSha1(),
809  ];
810 
811  if ( in_array( 'page', $options ) ) {
812  $fields += [
813  'page_namespace' => (string)$page->getTitle()->getNamespace(),
814  'page_title' => $page->getTitle()->getDBkey(),
815  'page_id' => (string)$page->getId(),
816  'page_latest' => (string)$page->getLatest(),
817  'page_is_redirect' => $page->isRedirect() ? '1' : '0',
818  'page_len' => (string)$page->getContent()->getSize(),
819  ];
820  }
821 
822  if ( in_array( 'user', $options ) ) {
823  $fields += [
824  'user_name' => (string)$rev->getUserText(),
825  ];
826  }
827 
828  if ( in_array( 'comment', $options ) ) {
829  $fields += [
830  'rev_comment_text' => $rev->getComment(),
831  'rev_comment_data' => null,
832  'rev_comment_cid' => null,
833  ];
834  }
835 
836  if ( $rev->getId() ) {
837  $fields += [
838  'rev_id' => (string)$rev->getId(),
839  ];
840  }
841 
842  return (object)$fields;
843  }
844 
846  Revision $rev,
847  RevisionRecord $record
848  ) {
849  $this->assertSame( $rev->getId(), $record->getId() );
850  $this->assertSame( $rev->getPage(), $record->getPageId() );
851  $this->assertSame( $rev->getTimestamp(), $record->getTimestamp() );
852  $this->assertSame( $rev->getUserText(), $record->getUser()->getName() );
853  $this->assertSame( $rev->getUser(), $record->getUser()->getId() );
854  $this->assertSame( $rev->isMinor(), $record->isMinor() );
855  $this->assertSame( $rev->getVisibility(), $record->getVisibility() );
856  $this->assertSame( $rev->getSize(), $record->getSize() );
861  $expectedParent = $rev->getParentId();
862  if ( $expectedParent === null ) {
863  $expectedParent = 0;
864  }
865  $this->assertSame( $expectedParent, $record->getParentId() );
866  $this->assertSame( $rev->getSha1(), $record->getSha1() );
867  $this->assertSame( $rev->getComment(), $record->getComment()->text );
868  $this->assertSame( $rev->getContentFormat(),
869  $record->getContent( SlotRecord::MAIN )->getDefaultFormat() );
870  $this->assertSame( $rev->getContentModel(), $record->getContent( SlotRecord::MAIN )->getModel() );
871  $this->assertLinkTargetsEqual( $rev->getTitle(), $record->getPageAsLinkTarget() );
872 
873  $revRec = $rev->getRevisionRecord();
874  $revMain = $revRec->getSlot( SlotRecord::MAIN );
875  $recMain = $record->getSlot( SlotRecord::MAIN );
876 
877  $this->assertSame( $revMain->hasOrigin(), $recMain->hasOrigin(), 'hasOrigin' );
878  $this->assertSame( $revMain->hasAddress(), $recMain->hasAddress(), 'hasAddress' );
879  $this->assertSame( $revMain->hasContentId(), $recMain->hasContentId(), 'hasContentId' );
880 
881  if ( $revMain->hasOrigin() ) {
882  $this->assertSame( $revMain->getOrigin(), $recMain->getOrigin(), 'getOrigin' );
883  }
884 
885  if ( $revMain->hasAddress() ) {
886  $this->assertSame( $revMain->getAddress(), $recMain->getAddress(), 'getAddress' );
887  }
888 
889  if ( $revMain->hasContentId() ) {
890  $this->assertSame( $revMain->getContentId(), $recMain->getContentId(), 'getContentId' );
891  }
892  }
893 
899  $page = $this->getTestPage();
900  $text = __METHOD__ . 'a-ä';
902  $rev = $page->doEditContent(
903  new WikitextContent( $text ),
904  __METHOD__ . 'a'
905  )->value['revision'];
906 
907  $store = MediaWikiServices::getInstance()->getRevisionStore();
908  $info = $store->getQueryInfo();
909  $row = $this->db->selectRow(
910  $info['tables'],
911  $info['fields'],
912  [ 'rev_id' => $rev->getId() ],
913  __METHOD__,
914  [],
915  $info['joins']
916  );
917  $record = $store->newRevisionFromRow(
918  $row,
919  [],
920  $page->getTitle()
921  );
922  $this->assertRevisionRecordMatchesRevision( $rev, $record );
923  $this->assertSame( $text, $rev->getContent()->serialize() );
924  }
925 
930  $page = $this->getTestPage();
931  $text = __METHOD__ . 'a-ä';
933  $rev = $page->doEditContent(
934  new WikitextContent( $text ),
935  __METHOD__ . 'a'
936  )->value['revision'];
937 
938  $store = MediaWikiServices::getInstance()->getRevisionStore();
939  $record = $store->newRevisionFromRow(
940  $this->revisionToRow( $rev ),
941  [],
942  $page->getTitle()
943  );
944  $this->assertRevisionRecordMatchesRevision( $rev, $record );
945  $this->assertSame( $text, $rev->getContent()->serialize() );
946  }
947 
952  $this->setMwGlobals( 'wgLegacyEncoding', 'windows-1252' );
953  $this->overrideMwServices();
954  $page = $this->getTestPage();
955  $text = __METHOD__ . 'a-ä';
957  $rev = $page->doEditContent(
958  new WikitextContent( $text ),
959  __METHOD__ . 'a'
960  )->value['revision'];
961 
962  $store = MediaWikiServices::getInstance()->getRevisionStore();
963  $record = $store->newRevisionFromRow(
964  $this->revisionToRow( $rev ),
965  [],
966  $page->getTitle()
967  );
968  $this->assertRevisionRecordMatchesRevision( $rev, $record );
969  $this->assertSame( $text, $rev->getContent()->serialize() );
970  }
971 
976  $page = $this->getTestPage();
977  $text = __METHOD__ . 'b-ä';
979  $rev = $page->doEditContent(
980  new WikitextContent( $text ),
981  __METHOD__ . 'b',
982  0,
983  false,
984  $this->getTestUser()->getUser()
985  )->value['revision'];
986 
987  $store = MediaWikiServices::getInstance()->getRevisionStore();
988  $record = $store->newRevisionFromRow(
989  $this->revisionToRow( $rev ),
990  [],
991  $page->getTitle()
992  );
993  $this->assertRevisionRecordMatchesRevision( $rev, $record );
994  $this->assertSame( $text, $rev->getContent()->serialize() );
995  }
996 
1002  $store = MediaWikiServices::getInstance()->getRevisionStore();
1003  $title = Title::newFromText( __METHOD__ );
1004  $text = __METHOD__ . '-bä';
1005  $page = WikiPage::factory( $title );
1007  $orig = $page->doEditContent( new WikitextContent( $text ), __METHOD__ )
1008  ->value['revision'];
1009  $page->doDeleteArticle( __METHOD__ );
1010 
1011  $db = wfGetDB( DB_MASTER );
1012  $arQuery = $store->getArchiveQueryInfo();
1013  $res = $db->select(
1014  $arQuery['tables'], $arQuery['fields'], [ 'ar_rev_id' => $orig->getId() ],
1015  __METHOD__, [], $arQuery['joins']
1016  );
1017  $this->assertTrue( is_object( $res ), 'query failed' );
1018 
1019  $row = $res->fetchObject();
1020  $res->free();
1021  $record = $store->newRevisionFromArchiveRow( $row );
1022 
1023  $this->assertRevisionRecordMatchesRevision( $orig, $record );
1024  $this->assertSame( $text, $record->getContent( SlotRecord::MAIN )->serialize() );
1025  }
1026 
1031  $this->setMwGlobals( 'wgLegacyEncoding', 'windows-1252' );
1032  $this->overrideMwServices();
1033  $store = MediaWikiServices::getInstance()->getRevisionStore();
1034  $title = Title::newFromText( __METHOD__ );
1035  $text = __METHOD__ . '-bä';
1036  $page = WikiPage::factory( $title );
1038  $orig = $page->doEditContent( new WikitextContent( $text ), __METHOD__ )
1039  ->value['revision'];
1040  $page->doDeleteArticle( __METHOD__ );
1041 
1042  $db = wfGetDB( DB_MASTER );
1043  $arQuery = $store->getArchiveQueryInfo();
1044  $res = $db->select(
1045  $arQuery['tables'], $arQuery['fields'], [ 'ar_rev_id' => $orig->getId() ],
1046  __METHOD__, [], $arQuery['joins']
1047  );
1048  $this->assertTrue( is_object( $res ), 'query failed' );
1049 
1050  $row = $res->fetchObject();
1051  $res->free();
1052  $record = $store->newRevisionFromArchiveRow( $row );
1053 
1054  $this->assertRevisionRecordMatchesRevision( $orig, $record );
1055  $this->assertSame( $text, $record->getContent( SlotRecord::MAIN )->serialize() );
1056  }
1057 
1062  $store = MediaWikiServices::getInstance()->getRevisionStore();
1063 
1064  $row = (object)[
1065  'ar_id' => '1',
1066  'ar_page_id' => '2',
1067  'ar_namespace' => '0',
1068  'ar_title' => 'Something',
1069  'ar_rev_id' => '2',
1070  'ar_text_id' => '47',
1071  'ar_timestamp' => '20180528192356',
1072  'ar_minor_edit' => '0',
1073  'ar_deleted' => '0',
1074  'ar_len' => '78',
1075  'ar_parent_id' => '0',
1076  'ar_sha1' => 'deadbeef',
1077  'ar_comment_text' => 'whatever',
1078  'ar_comment_data' => null,
1079  'ar_comment_cid' => null,
1080  'ar_user' => '0',
1081  'ar_user_text' => '', // this is the important bit
1082  'ar_actor' => null,
1083  'ar_content_format' => null,
1084  'ar_content_model' => null,
1085  ];
1086 
1087  \Wikimedia\suppressWarnings();
1088  $record = $store->newRevisionFromArchiveRow( $row );
1089  \Wikimedia\suppressWarnings( true );
1090 
1091  $this->assertInstanceOf( RevisionRecord::class, $record );
1092  $this->assertInstanceOf( UserIdentityValue::class, $record->getUser() );
1093  $this->assertSame( 'Unknown user', $record->getUser()->getName() );
1094  }
1095 
1100  $store = MediaWikiServices::getInstance()->getRevisionStore();
1101  $title = Title::newFromText( __METHOD__ );
1102 
1103  $row = (object)[
1104  'rev_id' => '2',
1105  'rev_page' => '2',
1106  'page_namespace' => '0',
1107  'page_title' => $title->getText(),
1108  'rev_text_id' => '47',
1109  'rev_timestamp' => '20180528192356',
1110  'rev_minor_edit' => '0',
1111  'rev_deleted' => '0',
1112  'rev_len' => '78',
1113  'rev_parent_id' => '0',
1114  'rev_sha1' => 'deadbeef',
1115  'rev_comment_text' => 'whatever',
1116  'rev_comment_data' => null,
1117  'rev_comment_cid' => null,
1118  'rev_user' => '0',
1119  'rev_user_text' => '', // this is the important bit
1120  'rev_actor' => null,
1121  'rev_content_format' => null,
1122  'rev_content_model' => null,
1123  ];
1124 
1125  \Wikimedia\suppressWarnings();
1126  $record = $store->newRevisionFromRow( $row, 0, $title );
1127  \Wikimedia\suppressWarnings( true );
1128 
1129  $this->assertNotNull( $record );
1130  $this->assertNotNull( $record->getUser() );
1131  $this->assertNotEmpty( $record->getUser()->getName() );
1132  }
1133 
1137  public function testInsertRevisionOn_archive() {
1138  // This is a round trip test for deletion and undeletion of a
1139  // revision row via the archive table.
1140 
1141  $store = MediaWikiServices::getInstance()->getRevisionStore();
1142  $title = Title::newFromText( __METHOD__ );
1143 
1144  $page = WikiPage::factory( $title );
1146  $page->doEditContent( new WikitextContent( "First" ), __METHOD__ . '-first' );
1147  $origRev = $page->doEditContent( new WikitextContent( "Foo" ), __METHOD__ )
1148  ->value['revision'];
1149  $orig = $origRev->getRevisionRecord();
1150  $page->doDeleteArticle( __METHOD__ );
1151 
1152  // re-create page, so we can later load revisions for it
1153  $page->doEditContent( new WikitextContent( 'Two' ), __METHOD__ );
1154 
1155  $db = wfGetDB( DB_MASTER );
1156  $arQuery = $store->getArchiveQueryInfo();
1157  $row = $db->selectRow(
1158  $arQuery['tables'], $arQuery['fields'], [ 'ar_rev_id' => $orig->getId() ],
1159  __METHOD__, [], $arQuery['joins']
1160  );
1161 
1162  $this->assertNotFalse( $row, 'query failed' );
1163 
1164  $record = $store->newRevisionFromArchiveRow(
1165  $row,
1166  0,
1167  $title,
1168  [ 'page_id' => $title->getArticleID() ]
1169  );
1170 
1171  $restored = $store->insertRevisionOn( $record, $db );
1172 
1173  // is the new revision correct?
1174  $this->assertRevisionCompleteness( $restored );
1175  $this->assertRevisionRecordsEqual( $record, $restored );
1176 
1177  // does the new revision use the original slot?
1178  $recMain = $record->getSlot( SlotRecord::MAIN );
1179  $restMain = $restored->getSlot( SlotRecord::MAIN );
1180  $this->assertSame( $recMain->getAddress(), $restMain->getAddress() );
1181  $this->assertSame( $recMain->getContentId(), $restMain->getContentId() );
1182  $this->assertSame( $recMain->getOrigin(), $restMain->getOrigin() );
1183  $this->assertSame( 'Foo', $restMain->getContent()->serialize() );
1184 
1185  // can we load it from the store?
1186  $loaded = $store->getRevisionById( $restored->getId() );
1187  $this->assertNotNull( $loaded );
1188  $this->assertRevisionCompleteness( $loaded );
1189  $this->assertRevisionRecordsEqual( $restored, $loaded );
1190 
1191  // can we find it directly in the database?
1192  $this->assertRevisionExistsInDatabase( $restored );
1193  }
1194 
1198  public function testLoadRevisionFromId() {
1199  $title = Title::newFromText( __METHOD__ );
1200  $page = WikiPage::factory( $title );
1202  $rev = $page->doEditContent( new WikitextContent( __METHOD__ ), __METHOD__ )
1203  ->value['revision'];
1204 
1205  $store = MediaWikiServices::getInstance()->getRevisionStore();
1206  $result = $store->loadRevisionFromId( wfGetDB( DB_MASTER ), $rev->getId() );
1208  }
1209 
1213  public function testLoadRevisionFromPageId() {
1214  $title = Title::newFromText( __METHOD__ );
1215  $page = WikiPage::factory( $title );
1217  $rev = $page->doEditContent( new WikitextContent( __METHOD__ ), __METHOD__ )
1218  ->value['revision'];
1219 
1220  $store = MediaWikiServices::getInstance()->getRevisionStore();
1221  $result = $store->loadRevisionFromPageId( wfGetDB( DB_MASTER ), $page->getId() );
1223  }
1224 
1228  public function testLoadRevisionFromTitle() {
1229  $title = Title::newFromText( __METHOD__ );
1230  $page = WikiPage::factory( $title );
1232  $rev = $page->doEditContent( new WikitextContent( __METHOD__ ), __METHOD__ )
1233  ->value['revision'];
1234 
1235  $store = MediaWikiServices::getInstance()->getRevisionStore();
1236  $result = $store->loadRevisionFromTitle( wfGetDB( DB_MASTER ), $title );
1238  }
1239 
1243  public function testLoadRevisionFromTimestamp() {
1244  $title = Title::newFromText( __METHOD__ );
1245  $page = WikiPage::factory( $title );
1247  $revOne = $page->doEditContent( new WikitextContent( __METHOD__ ), __METHOD__ )
1248  ->value['revision'];
1249  // Sleep to ensure different timestamps... )(evil)
1250  sleep( 1 );
1252  $revTwo = $page->doEditContent( new WikitextContent( __METHOD__ . 'a' ), '' )
1253  ->value['revision'];
1254 
1255  $store = MediaWikiServices::getInstance()->getRevisionStore();
1256  $this->assertNull(
1257  $store->loadRevisionFromTimestamp( wfGetDB( DB_MASTER ), $title, '20150101010101' )
1258  );
1259  $this->assertSame(
1260  $revOne->getId(),
1261  $store->loadRevisionFromTimestamp(
1262  wfGetDB( DB_MASTER ),
1263  $title,
1264  $revOne->getTimestamp()
1265  )->getId()
1266  );
1267  $this->assertSame(
1268  $revTwo->getId(),
1269  $store->loadRevisionFromTimestamp(
1270  wfGetDB( DB_MASTER ),
1271  $title,
1272  $revTwo->getTimestamp()
1273  )->getId()
1274  );
1275  }
1276 
1280  public function testGetParentLengths() {
1281  $page = WikiPage::factory( Title::newFromText( __METHOD__ ) );
1283  $revOne = $page->doEditContent(
1284  new WikitextContent( __METHOD__ ), __METHOD__
1285  )->value['revision'];
1287  $revTwo = $page->doEditContent(
1288  new WikitextContent( __METHOD__ . '2' ), __METHOD__
1289  )->value['revision'];
1290 
1291  $store = MediaWikiServices::getInstance()->getRevisionStore();
1292  $this->assertSame(
1293  [
1294  $revOne->getId() => strlen( __METHOD__ ),
1295  ],
1296  $store->listRevisionSizes(
1297  wfGetDB( DB_MASTER ),
1298  [ $revOne->getId() ]
1299  )
1300  );
1301  $this->assertSame(
1302  [
1303  $revOne->getId() => strlen( __METHOD__ ),
1304  $revTwo->getId() => strlen( __METHOD__ ) + 1,
1305  ],
1306  $store->listRevisionSizes(
1307  wfGetDB( DB_MASTER ),
1308  [ $revOne->getId(), $revTwo->getId() ]
1309  )
1310  );
1311  }
1312 
1316  public function testGetPreviousRevision() {
1317  $page = WikiPage::factory( Title::newFromText( __METHOD__ ) );
1319  $revOne = $page->doEditContent(
1320  new WikitextContent( __METHOD__ ), __METHOD__
1321  )->value['revision'];
1323  $revTwo = $page->doEditContent(
1324  new WikitextContent( __METHOD__ . '2' ), __METHOD__
1325  )->value['revision'];
1326 
1327  $store = MediaWikiServices::getInstance()->getRevisionStore();
1328  $this->assertNull(
1329  $store->getPreviousRevision( $store->getRevisionById( $revOne->getId() ) )
1330  );
1331  $this->assertSame(
1332  $revOne->getId(),
1333  $store->getPreviousRevision( $store->getRevisionById( $revTwo->getId() ) )->getId()
1334  );
1335  }
1336 
1340  public function testGetNextRevision() {
1341  $page = WikiPage::factory( Title::newFromText( __METHOD__ ) );
1343  $revOne = $page->doEditContent(
1344  new WikitextContent( __METHOD__ ), __METHOD__
1345  )->value['revision'];
1347  $revTwo = $page->doEditContent(
1348  new WikitextContent( __METHOD__ . '2' ), __METHOD__
1349  )->value['revision'];
1350 
1351  $store = MediaWikiServices::getInstance()->getRevisionStore();
1352  $this->assertSame(
1353  $revTwo->getId(),
1354  $store->getNextRevision( $store->getRevisionById( $revOne->getId() ) )->getId()
1355  );
1356  $this->assertNull(
1357  $store->getNextRevision( $store->getRevisionById( $revTwo->getId() ) )
1358  );
1359  }
1360 
1361  public function provideNonHistoryRevision() {
1362  $title = Title::newFromText( __METHOD__ );
1364  yield [ $rev ];
1365 
1366  $user = new UserIdentityValue( 7, 'Frank', 0 );
1367  $comment = CommentStoreComment::newUnsavedComment( 'Test' );
1368  $row = (object)[
1369  'ar_id' => 3,
1370  'ar_rev_id' => 34567,
1371  'ar_page_id' => 5,
1372  'ar_deleted' => 0,
1373  'ar_minor_edit' => 0,
1374  'ar_timestamp' => '20180101020202',
1375  ];
1376  $slots = new RevisionSlots( [] );
1377  $rev = new RevisionArchiveRecord( $title, $user, $comment, $row, $slots );
1378  yield [ $rev ];
1379  }
1380 
1386  $store = MediaWikiServices::getInstance()->getRevisionStore();
1387  $this->assertNull( $store->getPreviousRevision( $rev ) );
1388  }
1389 
1395  $store = MediaWikiServices::getInstance()->getRevisionStore();
1396  $this->assertNull( $store->getNextRevision( $rev ) );
1397  }
1398 
1402  public function testGetTimestampFromId_found() {
1403  $page = $this->getTestPage();
1405  $rev = $page->doEditContent( new WikitextContent( __METHOD__ ), __METHOD__ )
1406  ->value['revision'];
1407 
1408  $store = MediaWikiServices::getInstance()->getRevisionStore();
1409  $result = $store->getTimestampFromId(
1410  $page->getTitle(),
1411  $rev->getId()
1412  );
1413 
1414  $this->assertSame( $rev->getTimestamp(), $result );
1415  }
1416 
1421  $page = $this->getTestPage();
1423  $rev = $page->doEditContent( new WikitextContent( __METHOD__ ), __METHOD__ )
1424  ->value['revision'];
1425 
1426  $store = MediaWikiServices::getInstance()->getRevisionStore();
1427  $result = $store->getTimestampFromId(
1428  $page->getTitle(),
1429  $rev->getId() + 1
1430  );
1431 
1432  $this->assertFalse( $result );
1433  }
1434 
1438  public function testCountRevisionsByPageId() {
1439  $store = MediaWikiServices::getInstance()->getRevisionStore();
1440  $page = WikiPage::factory( Title::newFromText( __METHOD__ ) );
1441 
1442  $this->assertSame(
1443  0,
1444  $store->countRevisionsByPageId( wfGetDB( DB_MASTER ), $page->getId() )
1445  );
1446  $page->doEditContent( new WikitextContent( 'a' ), 'a' );
1447  $this->assertSame(
1448  1,
1449  $store->countRevisionsByPageId( wfGetDB( DB_MASTER ), $page->getId() )
1450  );
1451  $page->doEditContent( new WikitextContent( 'b' ), 'b' );
1452  $this->assertSame(
1453  2,
1454  $store->countRevisionsByPageId( wfGetDB( DB_MASTER ), $page->getId() )
1455  );
1456  }
1457 
1461  public function testCountRevisionsByTitle() {
1462  $store = MediaWikiServices::getInstance()->getRevisionStore();
1463  $page = WikiPage::factory( Title::newFromText( __METHOD__ ) );
1464 
1465  $this->assertSame(
1466  0,
1467  $store->countRevisionsByTitle( wfGetDB( DB_MASTER ), $page->getTitle() )
1468  );
1469  $page->doEditContent( new WikitextContent( 'a' ), 'a' );
1470  $this->assertSame(
1471  1,
1472  $store->countRevisionsByTitle( wfGetDB( DB_MASTER ), $page->getTitle() )
1473  );
1474  $page->doEditContent( new WikitextContent( 'b' ), 'b' );
1475  $this->assertSame(
1476  2,
1477  $store->countRevisionsByTitle( wfGetDB( DB_MASTER ), $page->getTitle() )
1478  );
1479  }
1480 
1484  public function testUserWasLastToEdit_false() {
1485  $sysop = $this->getTestSysop()->getUser();
1486  $page = $this->getTestPage();
1487  $page->doEditContent( new WikitextContent( __METHOD__ ), __METHOD__ );
1488 
1489  $store = MediaWikiServices::getInstance()->getRevisionStore();
1490  $result = $store->userWasLastToEdit(
1491  wfGetDB( DB_MASTER ),
1492  $page->getId(),
1493  $sysop->getId(),
1494  '20160101010101'
1495  );
1496  $this->assertFalse( $result );
1497  }
1498 
1502  public function testUserWasLastToEdit_true() {
1503  $startTime = wfTimestampNow();
1504  $sysop = $this->getTestSysop()->getUser();
1505  $page = $this->getTestPage();
1506  $page->doEditContent(
1507  new WikitextContent( __METHOD__ ),
1508  __METHOD__,
1509  0,
1510  false,
1511  $sysop
1512  );
1513 
1514  $store = MediaWikiServices::getInstance()->getRevisionStore();
1515  $result = $store->userWasLastToEdit(
1516  wfGetDB( DB_MASTER ),
1517  $page->getId(),
1518  $sysop->getId(),
1519  $startTime
1520  );
1521  $this->assertTrue( $result );
1522  }
1523 
1527  public function testGetKnownCurrentRevision() {
1528  $page = $this->getTestPage();
1530  $rev = $page->doEditContent(
1531  new WikitextContent( __METHOD__ . 'b' ),
1532  __METHOD__ . 'b',
1533  0,
1534  false,
1535  $this->getTestUser()->getUser()
1536  )->value['revision'];
1537 
1538  $store = MediaWikiServices::getInstance()->getRevisionStore();
1539  $record = $store->getKnownCurrentRevision(
1540  $page->getTitle(),
1541  $rev->getId()
1542  );
1543 
1544  $this->assertRevisionRecordMatchesRevision( $rev, $record );
1545  }
1546 
1548  yield 'Basic array, content object' => [
1549  [
1550  'id' => 2,
1551  'page' => 1,
1552  'timestamp' => '20171017114835',
1553  'user_text' => '111.0.1.2',
1554  'user' => 0,
1555  'minor_edit' => false,
1556  'deleted' => 0,
1557  'len' => 46,
1558  'parent_id' => 1,
1559  'sha1' => 'rdqbbzs3pkhihgbs8qf2q9jsvheag5z',
1560  'comment' => 'Goat Comment!',
1561  'content' => new WikitextContent( 'Some Content' ),
1562  ]
1563  ];
1564  yield 'Basic array, serialized text' => [
1565  [
1566  'id' => 2,
1567  'page' => 1,
1568  'timestamp' => '20171017114835',
1569  'user_text' => '111.0.1.2',
1570  'user' => 0,
1571  'minor_edit' => false,
1572  'deleted' => 0,
1573  'len' => 46,
1574  'parent_id' => 1,
1575  'sha1' => 'rdqbbzs3pkhihgbs8qf2q9jsvheag5z',
1576  'comment' => 'Goat Comment!',
1577  'text' => ( new WikitextContent( 'Söme Content' ) )->serialize(),
1578  ]
1579  ];
1580  yield 'Basic array, serialized text, utf-8 flags' => [
1581  [
1582  'id' => 2,
1583  'page' => 1,
1584  'timestamp' => '20171017114835',
1585  'user_text' => '111.0.1.2',
1586  'user' => 0,
1587  'minor_edit' => false,
1588  'deleted' => 0,
1589  'len' => 46,
1590  'parent_id' => 1,
1591  'sha1' => 'rdqbbzs3pkhihgbs8qf2q9jsvheag5z',
1592  'comment' => 'Goat Comment!',
1593  'text' => ( new WikitextContent( 'Söme Content' ) )->serialize(),
1594  'flags' => 'utf-8',
1595  ]
1596  ];
1597  yield 'Basic array, with title' => [
1598  [
1599  'title' => Title::newFromText( 'SomeText' ),
1600  'timestamp' => '20171017114835',
1601  'user_text' => '111.0.1.2',
1602  'user' => 0,
1603  'minor_edit' => false,
1604  'deleted' => 0,
1605  'len' => 46,
1606  'parent_id' => 1,
1607  'sha1' => 'rdqbbzs3pkhihgbs8qf2q9jsvheag5z',
1608  'comment' => 'Goat Comment!',
1609  'content' => new WikitextContent( 'Some Content' ),
1610  ]
1611  ];
1612  yield 'Basic array, no user field' => [
1613  [
1614  'id' => 2,
1615  'page' => 1,
1616  'timestamp' => '20171017114835',
1617  'user_text' => '111.0.1.3',
1618  'minor_edit' => false,
1619  'deleted' => 0,
1620  'len' => 46,
1621  'parent_id' => 1,
1622  'sha1' => 'rdqbbzs3pkhihgbs8qf2q9jsvheag5z',
1623  'comment' => 'Goat Comment!',
1624  'content' => new WikitextContent( 'Some Content' ),
1625  ]
1626  ];
1627  }
1628 
1633  public function testNewMutableRevisionFromArray( array $array ) {
1634  $store = MediaWikiServices::getInstance()->getRevisionStore();
1635 
1636  // HACK: if $array['page'] is given, make sure that the page exists
1637  if ( isset( $array['page'] ) ) {
1638  $t = Title::newFromID( $array['page'] );
1639  if ( !$t || !$t->exists() ) {
1640  $t = Title::makeTitle( NS_MAIN, __METHOD__ );
1641  $info = $this->insertPage( $t );
1642  $array['page'] = $info['id'];
1643  }
1644  }
1645 
1646  $result = $store->newMutableRevisionFromArray( $array );
1647 
1648  if ( isset( $array['id'] ) ) {
1649  $this->assertSame( $array['id'], $result->getId() );
1650  }
1651  if ( isset( $array['page'] ) ) {
1652  $this->assertSame( $array['page'], $result->getPageId() );
1653  }
1654  $this->assertSame( $array['timestamp'], $result->getTimestamp() );
1655  $this->assertSame( $array['user_text'], $result->getUser()->getName() );
1656  if ( isset( $array['user'] ) ) {
1657  $this->assertSame( $array['user'], $result->getUser()->getId() );
1658  }
1659  $this->assertSame( (bool)$array['minor_edit'], $result->isMinor() );
1660  $this->assertSame( $array['deleted'], $result->getVisibility() );
1661  $this->assertSame( $array['len'], $result->getSize() );
1662  $this->assertSame( $array['parent_id'], $result->getParentId() );
1663  $this->assertSame( $array['sha1'], $result->getSha1() );
1664  $this->assertSame( $array['comment'], $result->getComment()->text );
1665  if ( isset( $array['content'] ) ) {
1666  foreach ( $array['content'] as $role => $content ) {
1667  $this->assertTrue(
1668  $result->getContent( $role )->equals( $content )
1669  );
1670  }
1671  } elseif ( isset( $array['text'] ) ) {
1672  $this->assertSame( $array['text'],
1673  $result->getSlot( SlotRecord::MAIN )->getContent()->serialize() );
1674  } elseif ( isset( $array['content_format'] ) ) {
1675  $this->assertSame(
1676  $array['content_format'],
1677  $result->getSlot( SlotRecord::MAIN )->getContent()->getDefaultFormat()
1678  );
1679  $this->assertSame( $array['content_model'], $result->getSlot( SlotRecord::MAIN )->getModel() );
1680  }
1681  }
1682 
1688  $cache = new WANObjectCache( [ 'cache' => new HashBagOStuff() ] );
1689  $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
1690  $blobStore = new SqlBlobStore( $lb, $cache );
1691  $blobStore->setLegacyEncoding( 'windows-1252', Language::factory( 'en' ) );
1692 
1693  $factory = $this->getMockBuilder( BlobStoreFactory::class )
1694  ->setMethods( [ 'newBlobStore', 'newSqlBlobStore' ] )
1695  ->disableOriginalConstructor()
1696  ->getMock();
1697  $factory->expects( $this->any() )
1698  ->method( 'newBlobStore' )
1699  ->willReturn( $blobStore );
1700  $factory->expects( $this->any() )
1701  ->method( 'newSqlBlobStore' )
1702  ->willReturn( $blobStore );
1703 
1704  $this->setService( 'BlobStoreFactory', $factory );
1705 
1706  $this->testNewMutableRevisionFromArray( $array );
1707  }
1708 
1716  private function createRevisionStoreCacheRecord( $page, $store ) {
1718  $updater = $page->newPageUpdater( $user );
1719  $updater->setContent( SlotRecord::MAIN, new WikitextContent( __METHOD__ ) );
1720  $summary = CommentStoreComment::newUnsavedComment( __METHOD__ );
1721  $rev = $updater->saveRevision( $summary, EDIT_NEW );
1722  return $store->getKnownCurrentRevision( $page->getTitle(), $rev->getId() );
1723  }
1724 
1730 
1731  $this->overrideMwServices();
1732  $cache = new WANObjectCache( [ 'cache' => new HashBagOStuff() ] );
1733  $this->setService( 'MainWANObjectCache', $cache );
1734 
1735  $store = MediaWikiServices::getInstance()->getRevisionStore();
1736  $page = $this->getNonexistingTestPage();
1737  $rev = $this->createRevisionStoreCacheRecord( $page, $store );
1738 
1739  // Grab the user name
1740  $userNameBefore = $rev->getUser()->getName();
1741 
1742  // Change the user name in the database, "behind the back" of the cache
1743  $newUserName = "Renamed $userNameBefore";
1744  $this->db->update( 'revision',
1745  [ 'rev_user_text' => $newUserName ],
1746  [ 'rev_id' => $rev->getId() ] );
1747  $this->db->update( 'user',
1748  [ 'user_name' => $newUserName ],
1749  [ 'user_id' => $rev->getUser()->getId() ] );
1750  if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW ) {
1751  $this->db->update( 'actor',
1752  [ 'actor_name' => $newUserName ],
1753  [ 'actor_user' => $rev->getUser()->getId() ] );
1754  }
1755 
1756  // Reload the revision and regrab the user name.
1757  $revAfter = $store->getKnownCurrentRevision( $page->getTitle(), $rev->getId() );
1758  $userNameAfter = $revAfter->getUser()->getName();
1759 
1760  // The two user names should be different.
1761  // If they are the same, we are seeing a cached value, which is bad.
1762  $this->assertNotSame( $userNameBefore, $userNameAfter );
1763 
1764  // This is implied by the above assertion, but explicitly check it, for completeness
1765  $this->assertSame( $newUserName, $userNameAfter );
1766  }
1767 
1772  $this->overrideMwServices();
1773  $cache = new WANObjectCache( [ 'cache' => new HashBagOStuff() ] );
1774  $this->setService( 'MainWANObjectCache', $cache );
1775 
1776  $store = MediaWikiServices::getInstance()->getRevisionStore();
1777  $page = $this->getNonexistingTestPage();
1778  $rev = $this->createRevisionStoreCacheRecord( $page, $store );
1779 
1780  // Grab the deleted bitmask
1781  $deletedBefore = $rev->getVisibility();
1782 
1783  // Change the deleted bitmask in the database, "behind the back" of the cache
1784  $this->db->update( 'revision',
1785  [ 'rev_deleted' => RevisionRecord::DELETED_TEXT ],
1786  [ 'rev_id' => $rev->getId() ] );
1787 
1788  // Reload the revision and regrab the visibility flag.
1789  $revAfter = $store->getKnownCurrentRevision( $page->getTitle(), $rev->getId() );
1790  $deletedAfter = $revAfter->getVisibility();
1791 
1792  // The two deleted flags should be different.
1793  // If they are the same, we are seeing a cached value, which is bad.
1794  $this->assertNotSame( $deletedBefore, $deletedAfter );
1795 
1796  // This is implied by the above assertion, but explicitly check it, for completeness
1797  $this->assertSame( RevisionRecord::DELETED_TEXT, $deletedAfter );
1798  }
1799 
1805 
1806  $page = $this->getTestPage();
1807  $text = __METHOD__;
1809  $rev = $page->doEditContent(
1810  new WikitextContent( $text ),
1811  __METHOD__
1812  )->value['revision'];
1813 
1814  $store = MediaWikiServices::getInstance()->getRevisionStore();
1815  $record = $store->newRevisionFromRow(
1816  $this->revisionToRow( $rev ),
1817  [],
1818  $page->getTitle()
1819  );
1820 
1821  // Grab the user name
1822  $userNameBefore = $record->getUser()->getName();
1823 
1824  // Change the user name in the database
1825  $newUserName = "Renamed $userNameBefore";
1826  $this->db->update( 'revision',
1827  [ 'rev_user_text' => $newUserName ],
1828  [ 'rev_id' => $record->getId() ] );
1829  $this->db->update( 'user',
1830  [ 'user_name' => $newUserName ],
1831  [ 'user_id' => $record->getUser()->getId() ] );
1832  if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW ) {
1833  $this->db->update( 'actor',
1834  [ 'actor_name' => $newUserName ],
1835  [ 'actor_user' => $record->getUser()->getId() ] );
1836  }
1837 
1838  // Reload the record, passing $fromCache as true to force fresh info from the db,
1839  // and regrab the user name
1840  $recordAfter = $store->newRevisionFromRow(
1841  $this->revisionToRow( $rev ),
1842  [],
1843  $page->getTitle(),
1844  true
1845  );
1846  $userNameAfter = $recordAfter->getUser()->getName();
1847 
1848  // The two user names should be different.
1849  // If they are the same, we are seeing a cached value, which is bad.
1850  $this->assertNotSame( $userNameBefore, $userNameAfter );
1851 
1852  // This is implied by the above assertion, but explicitly check it, for completeness
1853  $this->assertSame( $newUserName, $userNameAfter );
1854  }
1855 
1860  $page = $this->getTestPage();
1861  $text = __METHOD__;
1863  $rev = $page->doEditContent(
1864  new WikitextContent( $text ),
1865  __METHOD__
1866  )->value['revision'];
1867 
1868  $store = MediaWikiServices::getInstance()->getRevisionStore();
1869  $record = $store->newRevisionFromRow(
1870  $this->revisionToRow( $rev ),
1871  [],
1872  $page->getTitle()
1873  );
1874 
1875  // Grab the deleted bitmask
1876  $deletedBefore = $record->getVisibility();
1877 
1878  // Change the deleted bitmask in the database
1879  $this->db->update( 'revision',
1880  [ 'rev_deleted' => RevisionRecord::DELETED_TEXT ],
1881  [ 'rev_id' => $record->getId() ] );
1882 
1883  // Reload the record, passing $fromCache as true to force fresh info from the db,
1884  // and regrab the deleted bitmask
1885  $recordAfter = $store->newRevisionFromRow(
1886  $this->revisionToRow( $rev ),
1887  [],
1888  $page->getTitle(),
1889  true
1890  );
1891  $deletedAfter = $recordAfter->getVisibility();
1892 
1893  // The two deleted flags should be different, because we modified the database.
1894  $this->assertNotSame( $deletedBefore, $deletedAfter );
1895 
1896  // This is implied by the above assertion, but explicitly check it, for completeness
1897  $this->assertSame( RevisionRecord::DELETED_TEXT, $deletedAfter );
1898  }
1899 
1900 }
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:138
testUserWasLastToEdit_false()
\MediaWiki\Revision\RevisionStore::userWasLastToEdit
Helper class that detects high-contention DB queries via profiling calls.
Service for storing and loading Content objects.
getUserText( $audience=self::FOR_PUBLIC, User $user=null)
Fetch revision&#39;s username if it&#39;s available to the specified audience.
Definition: Revision.php:823
testLoadRevisionFromTitle()
\MediaWiki\Revision\RevisionStore::loadRevisionFromTitle
testGetRcIdIfUnpatrolled_returnsRecentChangesId()
\MediaWiki\Revision\RevisionStore::getRcIdIfUnpatrolled
isMinor()
MCR migration note: this replaces Revision::isMinor.
testNewNullRevision_nonExistingTitle()
\MediaWiki\Revision\RevisionStore::newNullRevision
static newFromID( $id, $flags=0)
Create a new Title from an article ID.
Definition: Title.php:470
ensureMockDatabaseConnection(IDatabase $db)
const NS_MAIN
Definition: Defines.php:64
getRevisionRecord()
Definition: Revision.php:629
getNonexistingTestPage( $title=null)
Returns a WikiPage representing a non-existing page.
getPage()
Get the page ID.
Definition: Revision.php:782
serialize()
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
getTimestamp()
Definition: Revision.php:994
testCountRevisionsByPageId()
\MediaWiki\Revision\RevisionStore::countRevisionsByPageId
int $wgActorTableSchemaMigrationStage
Actor table schema migration stage.
globals will be eliminated from MediaWiki replaced by an application object which would be passed to constructors Whether that would be an convenient solution remains to be but certainly PHP makes such object oriented programming models easier than they were in previous versions For the time being MediaWiki programmers will have to work in an environment with some global context At the time of globals were initialised on startup by MediaWiki of these were configuration which are documented in DefaultSettings php There is no comprehensive documentation for the remaining however some of the most important ones are listed below They are typically initialised either in index php or in Setup php $wgTitle Title object created from the request URL $wgOut OutputPage object for HTTP response $wgUser User object for the user associated with the current request $wgLang Language object selected by user preferences $wgContLang Language object associated with the wiki being viewed $wgParser Parser object Parser extensions register their hooks here $wgRequest WebRequest object
Definition: globals.txt:25
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
testGetRevisionByTimestamp()
\MediaWiki\Revision\RevisionStore::getRevisionByTimestamp
testGetKnownCurrentRevision_userNameChange()
\MediaWiki\Revision\RevisionStore::getKnownCurrentRevision
assertArrayEquals(array $expected, array $actual, $ordered=false, $named=false)
Assert that two arrays are equal.
This code would result in ircNotify being run twice when an article is and once for brion Hooks can return three possible true was required This is the default since MediaWiki *some string
Definition: hooks.txt:175
testGetKnownCurrentRevision_revDelete()
\MediaWiki\Revision\RevisionStore::getKnownCurrentRevision
testGetParentLengths()
\MediaWiki\Revision\RevisionStore::listRevisionSizes
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:23
testInsertRevisionOn_successes(array $revDetails=[])
provideInsertRevisionOn_successes \MediaWiki\Revision\RevisionStore::insertRevisionOn \MediaWiki\Revi...
Exception throw when trying to access undefined fields on an incomplete RevisionRecord.
Value object representing a content slot associated with a page revision.
Definition: SlotRecord.php:39
isDeleted( $field)
MCR migration note: this replaces Revision::isDeleted.
hasSlot( $role)
Returns whether the given slot is defined in this revision.
testGetNextRevision()
\MediaWiki\Revision\RevisionStore::getNextRevision
testNewNullRevision(Title $title, $revDetails, $comment, $minor=false)
provideNewNullRevision \MediaWiki\Revision\RevisionStore::newNullRevision \MediaWiki\Revision\Revisio...
static getInstance()
Returns the global default instance of the top level service locator.
static newUnsavedComment( $comment, array $data=null)
Create a new, unsaved CommentStoreComment.
testNewMutableRevisionFromArray(array $array)
provideNewMutableRevisionFromArray \MediaWiki\Revision\RevisionStore::newMutableRevisionFromArray ...
const DB_MASTER
Definition: defines.php:26
testGetPreviousRevision()
\MediaWiki\Revision\RevisionStore::getPreviousRevision
testInsertRevisionOn_archive()
\MediaWiki\Revision\RevisionStore::insertRevisionOn
getNamespace()
Get the namespace index.
createRevisionStoreCacheRecord( $page, $store)
Creates a new revision for testing caching behavior.
getContent()
Returns the Content of the given slot.
Definition: SlotRecord.php:302
testDomainCheck( $wikiId, $dbName, $dbPrefix)
provideDomainCheck \MediaWiki\Revision\RevisionStore::checkDatabaseWikiId
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1980
testGetNextRevision_bad(RevisionRecord $rev)
provideNonHistoryRevision \MediaWiki\Revision\RevisionStore::getNextRevision
getModel()
Returns the content model.
Definition: SlotRecord.php:561
getFragment()
Get the link fragment (i.e.
Mutable RevisionRecord implementation, for building new revision entries programmatically.
testNewMutableRevisionFromArray_legacyEncoding(array $array)
provideNewMutableRevisionFromArray \MediaWiki\Revision\RevisionStore::newMutableRevisionFromArray ...
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
Definition: hooks.txt:1982
testNewRevisionFromRow_getQueryInfo()
\MediaWiki\Revision\RevisionStore::newRevisionFromRow \MediaWiki\Revision\RevisionStore::getQueryInfo...
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action, or null $user:User who performed the tagging when the tagging is subsequent to the action, or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, whether it is OK to use $contentModel on $title. Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy:boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'ContentSecurityPolicyDefaultSource':Modify the allowed CSP load sources. This affects all directives except for the script directive. If you want to add a script source, see ContentSecurityPolicyScriptSource hook. & $defaultSrc:Array of Content-Security-Policy allowed sources $policyConfig:Current configuration for the Content-Security-Policy header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyDirectives':Modify the content security policy directives. Use this only if ContentSecurityPolicyDefaultSource and ContentSecurityPolicyScriptSource do not meet your needs. & $directives:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyScriptSource':Modify the allowed CSP script sources. Note that you also have to use ContentSecurityPolicyDefaultSource if you want non-script sources to be loaded from whatever you add. & $scriptSrc:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'DeleteUnknownPreferences':Called by the cleanupPreferences.php maintenance script to build a WHERE clause with which to delete preferences that are not known about. This hook is used by extensions that have dynamically-named preferences that should not be deleted in the usual cleanup process. For example, the Gadgets extension creates preferences prefixed with 'gadget-', and so anything with that prefix is excluded from the deletion. &where:An array that will be passed as the $cond parameter to IDatabase::select() to determine what will be deleted from the user_properties table. $db:The IDatabase object, useful for accessing $db->buildLike() etc. 'DifferenceEngineAfterLoadNewText':called in DifferenceEngine::loadNewText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before returning true from this function. $differenceEngine:DifferenceEngine object 'DifferenceEngineLoadTextAfterNewContentIsLoaded':called in DifferenceEngine::loadText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before checking if the variable 's value is null. This hook can be used to inject content into said class member variable. $differenceEngine:DifferenceEngine object 'DifferenceEngineMarkPatrolledLink':Allows extensions to change the "mark as patrolled" link which is shown both on the diff header as well as on the bottom of a page, usually wrapped in a span element which has class="patrollink". $differenceEngine:DifferenceEngine object & $markAsPatrolledLink:The "mark as patrolled" link HTML(string) $rcid:Recent change ID(rc_id) for this change(int) 'DifferenceEngineMarkPatrolledRCID':Allows extensions to possibly change the rcid parameter. For example the rcid might be set to zero due to the user being the same as the performer of the change but an extension might still want to show it under certain conditions. & $rcid:rc_id(int) of the change or 0 $differenceEngine:DifferenceEngine object $change:RecentChange object $user:User object representing the current user 'DifferenceEngineNewHeader':Allows extensions to change the $newHeader variable, which contains information about the new revision, such as the revision 's author, whether the revision was marked as a minor edit or not, etc. $differenceEngine:DifferenceEngine object & $newHeader:The string containing the various #mw-diff-otitle[1-5] divs, which include things like revision author info, revision comment, RevisionDelete link and more $formattedRevisionTools:Array containing revision tools, some of which may have been injected with the DiffRevisionTools hook $nextlink:String containing the link to the next revision(if any) $status
Definition: hooks.txt:1263
static newInherited(SlotRecord $slot)
Constructs a new SlotRecord for a new revision, inheriting the content of the given SlotRecord of a p...
Definition: SlotRecord.php:103
testCountRevisionsByTitle()
\MediaWiki\Revision\RevisionStore::countRevisionsByTitle
getFormat()
Returns the blob serialization format as a MIME type.
Definition: SlotRecord.php:581
static getTestSysop()
Convenience method for getting an immutable admin test user.
getTitle()
Returns the title of the page associated with this entry.
Definition: Revision.php:755
assertSlotCompleteness(RevisionRecord $r, SlotRecord $slot)
getPageAsLinkTarget()
Returns the title of the page this revision is associated with as a LinkTarget object.
getParentId()
Get parent revision ID (the original previous page revision)
Definition: Revision.php:717
getUser( $audience=self::FOR_PUBLIC, User $user=null)
Fetch revision&#39;s user id if it&#39;s available to the specified audience.
Definition: Revision.php:799
getVisibility()
Get the deletion bitfield of the revision.
getSlotRoles()
Returns the slot names (roles) of all slots present in this revision.
insertPage( $pageName, $text='Sample page for unit test.', $namespace=null, User $user=null)
Insert a new page.
testNewRevisionFromRow_userEdit()
\MediaWiki\Revision\RevisionStore::newRevisionFromRow
getDBkey()
Get the main part with underscores.
Definition: Title.php:1001
getId()
Get revision ID.
Definition: Revision.php:638
assertRevisionRecordsEqual(RevisionRecord $r1, RevisionRecord $r2)
testLoadRevisionFromTimestamp()
\MediaWiki\Revision\RevisionStore::loadRevisionFromTimestamp
Service for looking up page revisions.
testNewRevisionFromRow_anonEdit()
\MediaWiki\Revision\RevisionStore::newRevisionFromRow
const SCHEMA_COMPAT_WRITE_NEW
Definition: Defines.php:286
testGetTimestampFromId_notFound()
\MediaWiki\Revision\RevisionStore::getTimestampFromId
static getMutableTestUser( $groups=[])
Convenience method for getting a mutable test user.
$res
Definition: database.txt:21
getContent( $role, $audience=self::FOR_PUBLIC, User $user=null)
Returns the Content of the given slot of this revision.
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
getDBkey()
Get the main part with underscores.
$cache
Definition: mcc.php:33
$params
testInsertRevisionOn_failures(array $revDetails=[], Exception $exception)
provideInsertRevisionOn_failures \MediaWiki\Revision\RevisionStore::insertRevisionOn ...
const EDIT_SUPPRESS_RC
Definition: Defines.php:155
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition: hooks.txt:1982
static getMutableTestUser( $testName, $groups=[])
Get a TestUser object that the caller may modify.
getRevision()
Returns the ID of the revision this slot is associated with.
Definition: SlotRecord.php:396
getComment( $audience=self::FOR_PUBLIC, User $user=null)
Definition: Revision.php:845
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:780
Value object representing a user&#39;s identity.
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:925
static factory( $code)
Get a cached or new language object for a given language code.
Definition: Language.php:215
getNamespace()
Get the namespace index, i.e.
Definition: Title.php:1025
testNewRevisionFromRow_userNameChange()
\MediaWiki\Revision\RevisionStore::newRevisionFromRow
testGetKnownCurrentRevision()
\MediaWiki\Revision\RevisionStore::getKnownCurrentRevision
presenting them properly to the user as errors is done by the caller return true use this to change the list i e etc $rev
Definition: hooks.txt:1766
overrideMwServices(Config $configOverrides=null, array $services=[])
Stashes the global instance of MediaWikiServices, and installs a new one, allowing test cases to over...
A RevisionRecord representing a revision of a deleted page persisted in the archive table...
setMwGlobals( $pairs, $value=null)
Sets a global, maintaining a stashed version of the previous global to be restored in tearDown...
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
assertSelect( $table, $fields, $condition, array $expectedRows, array $options=[], array $join_conds=[])
Asserts that the given database query yields the rows given by $expectedRows.
getContentModel()
Returns the content model for the main slot of this revision.
Definition: Revision.php:955
testNewRevisionFromRow_revDelete()
\MediaWiki\Revision\RevisionStore::newRevisionFromRow
testGetPreviousRevision_bad(RevisionRecord $rev)
provideNonHistoryRevision \MediaWiki\Revision\RevisionStore::getPreviousRevision
setService( $name, $object)
Sets a service, maintaining a stashed version of the previous service to be restored in tearDown...
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:589
testGetRcIdIfUnpatrolled_returnsZeroIfPatrolled()
\MediaWiki\Revision\RevisionStore::getRcIdIfUnpatrolled
testNewRevisionFromArchiveRow_legacyEncoding()
\MediaWiki\Revision\RevisionStore::newRevisionFromArchiveRow
testNewRevisionFromArchiveRow_getArchiveQueryInfo()
\MediaWiki\Revision\RevisionStore::newRevisionFromArchiveRow \MediaWiki\Revision\RevisionStore::getAr...
getVisibility()
Get the deletion bitfield of the revision.
Definition: Revision.php:897
getSlot( $role, $audience=self::FOR_PUBLIC, User $user=null)
Returns meta-data for the given slot.
getId()
Get revision ID.
revisionToRow(Revision $rev, $options=[ 'page', 'user', 'comment'])
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
getRole()
Returns the role of the slot.
Definition: SlotRecord.php:489
Class to handle database/prefix specification for IDatabase domains.
getSha1()
Returns the content size.
Definition: SlotRecord.php:538
testLoadRevisionFromPageId()
\MediaWiki\Revision\RevisionStore::loadRevisionFromPageId
testGetRevisionById()
\MediaWiki\Revision\RevisionStore::getRevisionById
testNewRevisionFromArchiveRow_no_user()
\MediaWiki\Revision\RevisionStore::newRevisionFromArchiveRow
hasRevision()
Whether this slot has revision ID associated.
Definition: SlotRecord.php:480
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
testInsertRevisionOn_blobAddressExists()
\MediaWiki\Revision\RevisionStore::insertRevisionOn
const EDIT_NEW
Definition: Defines.php:152
Overloads the relevant methods of the real ResultsWrapper so it doesn&#39;t go anywhere near an actual da...
getSha1()
Returns the base36 sha1 of this revision.
getSize()
Returns the content size.
Definition: SlotRecord.php:522
$page->newPageUpdater($user) $updater
Definition: pageupdater.txt:63
getTimestamp()
MCR migration note: this replaces Revision::getTimestamp.
getAddress()
Returns the address of this slot&#39;s content.
Definition: SlotRecord.php:499
testUserWasLastToEdit_true()
\MediaWiki\Revision\RevisionStore::userWasLastToEdit
getInterwiki()
The interwiki component of this LinkTarget.
Database $db
Primary database.
testGetRevisionByTitle()
\MediaWiki\Revision\RevisionStore::getRevisionByTitle
getWikiId()
Get the ID of the wiki this revision belongs to.
static newUnsaved( $role, Content $content)
Constructs a new Slot from a Content object for a new revision.
Definition: SlotRecord.php:129
getSize()
Returns the nominal size of this revision, in bogo-bytes.
Page revision base class.
hasAddress()
Whether this slot has an address.
Definition: SlotRecord.php:435
const DB_REPLICA
Definition: defines.php:25
getUser( $audience=self::FOR_PUBLIC, User $user=null)
Fetch revision&#39;s author&#39;s user identity, if it&#39;s available to the specified audience.
testNewRevisionFromRow_no_user()
\MediaWiki\Revision\RevisionStore::newRevisionFromRow
testNewRevisionFromRow_anonEdit_legacyEncoding()
\MediaWiki\Revision\RevisionStore::newRevisionFromRow
testLoadRevisionFromId()
\MediaWiki\Revision\RevisionStore::loadRevisionFromId
Value object representing the set of slots belonging to a revision.
getContentFormat()
Returns the content format for the main slot of this revision.
Definition: Revision.php:970
assertRevisionRecordMatchesRevision(Revision $rev, RevisionRecord $record)
getComment( $audience=self::FOR_PUBLIC, User $user=null)
Fetch revision comment, if it&#39;s available to the specified audience.
const SCHEMA_COMPAT_OLD
Definition: Defines.php:290
$content
Definition: pageupdater.txt:72
getSize()
Returns the length of the text in this revision, or null if unknown.
Definition: Revision.php:726
testGetTimestampFromId_found()
\MediaWiki\Revision\RevisionStore::getTimestampFromId
static getTestUser( $groups=[])
Convenience method for getting an immutable test user.
getParentId()
Get parent revision ID (the original previous page revision).
testGetRecentChange()
\MediaWiki\Revision\RevisionStore::getRecentChange
getSha1()
Returns the base36 sha1 of the content in this revision, or null if unknown.
Definition: Revision.php:739
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1473
getPageId()
Get the page ID.
testGetRevisionByPageId()
\MediaWiki\Revision\RevisionStore::getRevisionByPageId
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:319