MediaWiki REL1_32
RevisionStoreDbTestBase.php
Go to the documentation of this file.
1<?php
2
4
7use Exception;
9use InvalidArgumentException;
22use PHPUnit_Framework_MockObject_MockObject;
35
41
46
50 private $testPage;
51
55 abstract protected function getMcrMigrationStage();
56
60 protected function getContentHandlerUseDB() {
61 return true;
62 }
63
67 abstract protected function getMcrTablesToReset();
68
69 public function setUp() {
70 parent::setUp();
71 $this->tablesUsed[] = 'archive';
72 $this->tablesUsed[] = 'page';
73 $this->tablesUsed[] = 'revision';
74 $this->tablesUsed[] = 'comment';
75
76 $this->tablesUsed += $this->getMcrTablesToReset();
77
78 $this->setMwGlobals( [
79 'wgMultiContentRevisionSchemaMigrationStage' => $this->getMcrMigrationStage(),
80 'wgContentHandlerUseDB' => $this->getContentHandlerUseDB(),
81 'wgCommentTableSchemaMigrationStage' => MIGRATION_OLD,
82 'wgActorTableSchemaMigrationStage' => SCHEMA_COMPAT_OLD,
83 ] );
84
85 $this->overrideMwServices();
86 }
87
88 protected function addCoreDBData() {
89 // Blank out. This would fail with a modified schema, and we don't need it.
90 }
91
95 protected function getTestPageTitle() {
96 if ( $this->testPageTitle ) {
98 }
99
100 $this->testPageTitle = Title::newFromText( 'UTPage-' . __CLASS__ );
102 }
106 protected function getTestPage() {
107 if ( $this->testPage ) {
108 return $this->testPage;
109 }
110
111 $title = $this->getTestPageTitle();
112 $this->testPage = WikiPage::factory( $title );
113
114 if ( !$this->testPage->exists() ) {
115 // Make sure we don't write to the live db.
117
118 $user = static::getTestSysop()->getUser();
119
120 $this->testPage->doEditContent(
121 new WikitextContent( 'UTContent-' . __CLASS__ ),
122 'UTPageSummary-' . __CLASS__,
124 false,
125 $user
126 );
127 }
128
129 return $this->testPage;
130 }
131
135 private function getLoadBalancerMock( array $server ) {
136 $domain = new DatabaseDomain( $server['dbname'], null, $server['tablePrefix'] );
137
138 $lb = $this->getMockBuilder( LoadBalancer::class )
139 ->setMethods( [ 'reallyOpenConnection' ] )
140 ->setConstructorArgs( [
141 [ 'servers' => [ $server ], 'localDomain' => $domain ]
142 ] )
143 ->getMock();
144
145 $lb->method( 'reallyOpenConnection' )->willReturnCallback(
146 function ( array $server, $dbNameOverride ) {
147 return $this->getDatabaseMock( $server );
148 }
149 );
150
151 return $lb;
152 }
153
157 private function getDatabaseMock( array $params ) {
158 $db = $this->getMockBuilder( DatabaseSqlite::class )
159 ->setMethods( [ 'select', 'doQuery', 'open', 'closeConnection', 'isOpen' ] )
160 ->setConstructorArgs( [ $params ] )
161 ->getMock();
162
163 $db->method( 'select' )->willReturn( new FakeResultWrapper( [] ) );
164 $db->method( 'isOpen' )->willReturn( true );
165
166 return $db;
167 }
168
169 public function provideDomainCheck() {
170 yield [ false, 'test', '' ];
171 yield [ 'test', 'test', '' ];
172
173 yield [ false, 'test', 'foo_' ];
174 yield [ 'test-foo_', 'test', 'foo_' ];
175
176 yield [ false, 'dash-test', '' ];
177 yield [ 'dash-test', 'dash-test', '' ];
178
179 yield [ false, 'underscore_test', 'foo_' ];
180 yield [ 'underscore_test-foo_', 'underscore_test', 'foo_' ];
181 }
182
187 public function testDomainCheck( $wikiId, $dbName, $dbPrefix ) {
188 $this->setMwGlobals(
189 [
190 'wgDBname' => $dbName,
191 'wgDBprefix' => $dbPrefix,
192 ]
193 );
194
195 $loadBalancer = $this->getLoadBalancerMock(
196 [
197 'host' => '*dummy*',
198 'dbDirectory' => '*dummy*',
199 'user' => 'test',
200 'password' => 'test',
201 'flags' => 0,
202 'variables' => [],
203 'schema' => '',
204 'cliMode' => true,
205 'agent' => '',
206 'load' => 100,
207 'profiler' => null,
208 'trxProfiler' => new TransactionProfiler(),
209 'connLogger' => new \Psr\Log\NullLogger(),
210 'queryLogger' => new \Psr\Log\NullLogger(),
211 'errorLogger' => function () {
212 },
213 'deprecationLogger' => function () {
214 },
215 'type' => 'test',
216 'dbname' => $dbName,
217 'tablePrefix' => $dbPrefix,
218 ]
219 );
220 $db = $loadBalancer->getConnection( DB_REPLICA );
221
223 $blobStore = $this->getMockBuilder( SqlBlobStore::class )
224 ->disableOriginalConstructor()
225 ->getMock();
226
227 $store = new RevisionStore(
228 $loadBalancer,
229 $blobStore,
230 new WANObjectCache( [ 'cache' => new HashBagOStuff() ] ),
231 MediaWikiServices::getInstance()->getCommentStore(),
232 MediaWikiServices::getInstance()->getContentModelStore(),
233 MediaWikiServices::getInstance()->getSlotRoleStore(),
234 $this->getMcrMigrationStage(),
235 MediaWikiServices::getInstance()->getActorMigration(),
236 $wikiId
237 );
238
239 $count = $store->countRevisionsByPageId( $db, 0 );
240
241 // Dummy check to make PhpUnit happy. We are really only interested in
242 // countRevisionsByPageId not failing due to the DB domain check.
243 $this->assertSame( 0, $count );
244 }
245
246 protected function assertLinkTargetsEqual( LinkTarget $l1, LinkTarget $l2 ) {
247 $this->assertEquals( $l1->getDBkey(), $l2->getDBkey() );
248 $this->assertEquals( $l1->getNamespace(), $l2->getNamespace() );
249 $this->assertEquals( $l1->getFragment(), $l2->getFragment() );
250 $this->assertEquals( $l1->getInterwiki(), $l2->getInterwiki() );
251 }
252
254 $this->assertEquals(
255 $r1->getPageAsLinkTarget()->getNamespace(),
256 $r2->getPageAsLinkTarget()->getNamespace()
257 );
258
259 $this->assertEquals(
260 $r1->getPageAsLinkTarget()->getText(),
261 $r2->getPageAsLinkTarget()->getText()
262 );
263
264 if ( $r1->getParentId() ) {
265 $this->assertEquals( $r1->getParentId(), $r2->getParentId() );
266 }
267
268 $this->assertEquals( $r1->getUser()->getName(), $r2->getUser()->getName() );
269 $this->assertEquals( $r1->getUser()->getId(), $r2->getUser()->getId() );
270 $this->assertEquals( $r1->getComment(), $r2->getComment() );
271 $this->assertEquals( $r1->getTimestamp(), $r2->getTimestamp() );
272 $this->assertEquals( $r1->getVisibility(), $r2->getVisibility() );
273 $this->assertEquals( $r1->getSha1(), $r2->getSha1() );
274 $this->assertEquals( $r1->getSize(), $r2->getSize() );
275 $this->assertEquals( $r1->getPageId(), $r2->getPageId() );
276 $this->assertArrayEquals( $r1->getSlotRoles(), $r2->getSlotRoles() );
277 $this->assertEquals( $r1->getWikiId(), $r2->getWikiId() );
278 $this->assertEquals( $r1->isMinor(), $r2->isMinor() );
279 foreach ( $r1->getSlotRoles() as $role ) {
280 $this->assertSlotRecordsEqual( $r1->getSlot( $role ), $r2->getSlot( $role ) );
281 $this->assertTrue( $r1->getContent( $role )->equals( $r2->getContent( $role ) ) );
282 }
283 foreach ( [
284 RevisionRecord::DELETED_TEXT,
285 RevisionRecord::DELETED_COMMENT,
286 RevisionRecord::DELETED_USER,
287 RevisionRecord::DELETED_RESTRICTED,
288 ] as $field ) {
289 $this->assertEquals( $r1->isDeleted( $field ), $r2->isDeleted( $field ) );
290 }
291 }
292
293 protected function assertSlotRecordsEqual( SlotRecord $s1, SlotRecord $s2 ) {
294 $this->assertSame( $s1->getRole(), $s2->getRole() );
295 $this->assertSame( $s1->getModel(), $s2->getModel() );
296 $this->assertSame( $s1->getFormat(), $s2->getFormat() );
297 $this->assertSame( $s1->getSha1(), $s2->getSha1() );
298 $this->assertSame( $s1->getSize(), $s2->getSize() );
299 $this->assertTrue( $s1->getContent()->equals( $s2->getContent() ) );
300
301 $s1->hasRevision() ? $this->assertSame( $s1->getRevision(), $s2->getRevision() ) : null;
302 $s1->hasAddress() ? $this->assertSame( $s1->hasAddress(), $s2->hasAddress() ) : null;
303 }
304
306 $this->assertTrue( $r->hasSlot( SlotRecord::MAIN ) );
307 $this->assertInstanceOf( SlotRecord::class, $r->getSlot( SlotRecord::MAIN ) );
308 $this->assertInstanceOf( Content::class, $r->getContent( SlotRecord::MAIN ) );
309
310 foreach ( $r->getSlotRoles() as $role ) {
311 $this->assertSlotCompleteness( $r, $r->getSlot( $role ) );
312 }
313 }
314
315 protected function assertSlotCompleteness( RevisionRecord $r, SlotRecord $slot ) {
316 $this->assertTrue( $slot->hasAddress() );
317 $this->assertSame( $r->getId(), $slot->getRevision() );
318
319 $this->assertInstanceOf( Content::class, $slot->getContent() );
320 }
321
327 private function getRevisionRecordFromDetailsArray( $details = [] ) {
328 // Convert some values that can't be provided by dataProviders
329 if ( isset( $details['user'] ) && $details['user'] === true ) {
330 $details['user'] = $this->getTestUser()->getUser();
331 }
332 if ( isset( $details['page'] ) && $details['page'] === true ) {
333 $details['page'] = $this->getTestPage()->getId();
334 }
335 if ( isset( $details['parent'] ) && $details['parent'] === true ) {
336 $details['parent'] = $this->getTestPage()->getLatest();
337 }
338
339 // Create the RevisionRecord with any available data
341 isset( $details['slot'] ) ? $rev->setSlot( $details['slot'] ) : null;
342 isset( $details['parent'] ) ? $rev->setParentId( $details['parent'] ) : null;
343 isset( $details['page'] ) ? $rev->setPageId( $details['page'] ) : null;
344 isset( $details['size'] ) ? $rev->setSize( $details['size'] ) : null;
345 isset( $details['sha1'] ) ? $rev->setSha1( $details['sha1'] ) : null;
346 isset( $details['comment'] ) ? $rev->setComment( $details['comment'] ) : null;
347 isset( $details['timestamp'] ) ? $rev->setTimestamp( $details['timestamp'] ) : null;
348 isset( $details['minor'] ) ? $rev->setMinorEdit( $details['minor'] ) : null;
349 isset( $details['user'] ) ? $rev->setUser( $details['user'] ) : null;
350 isset( $details['visibility'] ) ? $rev->setVisibility( $details['visibility'] ) : null;
351 isset( $details['id'] ) ? $rev->setId( $details['id'] ) : null;
352
353 if ( isset( $details['content'] ) ) {
354 foreach ( $details['content'] as $role => $content ) {
355 $rev->setContent( $role, $content );
356 }
357 }
358
359 return $rev;
360 }
361
363 yield 'Bare minimum revision insertion' => [
364 [
365 'slot' => SlotRecord::newUnsaved( SlotRecord::MAIN, new WikitextContent( 'Chicken' ) ),
366 'page' => true,
367 'comment' => $this->getRandomCommentStoreComment(),
368 'timestamp' => '20171117010101',
369 'user' => true,
370 ],
371 ];
372 yield 'Detailed revision insertion' => [
373 [
374 'slot' => SlotRecord::newUnsaved( SlotRecord::MAIN, new WikitextContent( 'Chicken' ) ),
375 'parent' => true,
376 'page' => true,
377 'comment' => $this->getRandomCommentStoreComment(),
378 'timestamp' => '20171117010101',
379 'user' => true,
380 'minor' => true,
381 'visibility' => RevisionRecord::DELETED_RESTRICTED,
382 ],
383 ];
384 }
385
386 protected function getRandomCommentStoreComment() {
387 return CommentStoreComment::newUnsavedComment( __METHOD__ . '.' . rand( 0, 1000 ) );
388 }
389
397 array $revDetails = []
398 ) {
399 $title = $this->getTestPageTitle();
400 $rev = $this->getRevisionRecordFromDetailsArray( $revDetails );
401
402 $this->overrideMwServices();
403 $store = MediaWikiServices::getInstance()->getRevisionStore();
404 $return = $store->insertRevisionOn( $rev, wfGetDB( DB_MASTER ) );
405
406 // is the new revision correct?
407 $this->assertRevisionCompleteness( $return );
408 $this->assertLinkTargetsEqual( $title, $return->getPageAsLinkTarget() );
409 $this->assertRevisionRecordsEqual( $rev, $return );
410
411 // can we load it from the store?
412 $loaded = $store->getRevisionById( $return->getId() );
413 $this->assertRevisionCompleteness( $loaded );
414 $this->assertRevisionRecordsEqual( $return, $loaded );
415
416 // can we find it directly in the database?
417 $this->assertRevisionExistsInDatabase( $return );
418 }
419
421 $row = $this->revisionToRow( new Revision( $rev ), [] );
422
423 // unset nulled fields
424 unset( $row->rev_content_model );
425 unset( $row->rev_content_format );
426
427 // unset fake fields
428 unset( $row->rev_comment_text );
429 unset( $row->rev_comment_data );
430 unset( $row->rev_comment_cid );
431 unset( $row->rev_comment_id );
432
433 $store = MediaWikiServices::getInstance()->getRevisionStore();
434 $queryInfo = $store->getQueryInfo( [ 'user' ] );
435
436 $row = get_object_vars( $row );
437 $this->assertSelect(
438 $queryInfo['tables'],
439 array_keys( $row ),
440 [ 'rev_id' => $rev->getId() ],
441 [ array_values( $row ) ],
442 [],
443 $queryInfo['joins']
444 );
445 }
446
451 protected function assertSameSlotContent( SlotRecord $a, SlotRecord $b ) {
452 // Assert that the same blob address has been used.
453 $this->assertSame( $a->getAddress(), $b->getAddress() );
454 }
455
460 $title = $this->getTestPageTitle();
461 $revDetails = [
462 'slot' => SlotRecord::newUnsaved( SlotRecord::MAIN, new WikitextContent( 'Chicken' ) ),
463 'parent' => true,
464 'comment' => $this->getRandomCommentStoreComment(),
465 'timestamp' => '20171117010101',
466 'user' => true,
467 ];
468
469 $this->overrideMwServices();
470 $store = MediaWikiServices::getInstance()->getRevisionStore();
471
472 // Insert the first revision
473 $revOne = $this->getRevisionRecordFromDetailsArray( $revDetails );
474 $firstReturn = $store->insertRevisionOn( $revOne, wfGetDB( DB_MASTER ) );
475 $this->assertLinkTargetsEqual( $title, $firstReturn->getPageAsLinkTarget() );
476 $this->assertRevisionRecordsEqual( $revOne, $firstReturn );
477
478 // Insert a second revision inheriting the same blob address
479 $revDetails['slot'] = SlotRecord::newInherited( $firstReturn->getSlot( SlotRecord::MAIN ) );
480 $revTwo = $this->getRevisionRecordFromDetailsArray( $revDetails );
481 $secondReturn = $store->insertRevisionOn( $revTwo, wfGetDB( DB_MASTER ) );
482 $this->assertLinkTargetsEqual( $title, $secondReturn->getPageAsLinkTarget() );
483 $this->assertRevisionRecordsEqual( $revTwo, $secondReturn );
484
485 $firstMainSlot = $firstReturn->getSlot( SlotRecord::MAIN );
486 $secondMainSlot = $secondReturn->getSlot( SlotRecord::MAIN );
487
488 $this->assertSameSlotContent( $firstMainSlot, $secondMainSlot );
489
490 // And that different revisions have been created.
491 $this->assertNotSame( $firstReturn->getId(), $secondReturn->getId() );
492
493 // Make sure the slot rows reference the correct revision
494 $this->assertSame( $firstReturn->getId(), $firstMainSlot->getRevision() );
495 $this->assertSame( $secondReturn->getId(), $secondMainSlot->getRevision() );
496 }
497
499 yield 'no slot' => [
500 [
501 'comment' => $this->getRandomCommentStoreComment(),
502 'timestamp' => '20171117010101',
503 'user' => true,
504 ],
505 new InvalidArgumentException( 'main slot must be provided' )
506 ];
507 yield 'no main slot' => [
508 [
509 'slot' => SlotRecord::newUnsaved( 'aux', new WikitextContent( 'Turkey' ) ),
510 'comment' => $this->getRandomCommentStoreComment(),
511 'timestamp' => '20171117010101',
512 'user' => true,
513 ],
514 new InvalidArgumentException( 'main slot must be provided' )
515 ];
516 yield 'no timestamp' => [
517 [
518 'slot' => SlotRecord::newUnsaved( SlotRecord::MAIN, new WikitextContent( 'Chicken' ) ),
519 'comment' => $this->getRandomCommentStoreComment(),
520 'user' => true,
521 ],
522 new IncompleteRevisionException( 'timestamp field must not be NULL!' )
523 ];
524 yield 'no comment' => [
525 [
526 'slot' => SlotRecord::newUnsaved( SlotRecord::MAIN, new WikitextContent( 'Chicken' ) ),
527 'timestamp' => '20171117010101',
528 'user' => true,
529 ],
530 new IncompleteRevisionException( 'comment must not be NULL!' )
531 ];
532 yield 'no user' => [
533 [
534 'slot' => SlotRecord::newUnsaved( SlotRecord::MAIN, new WikitextContent( 'Chicken' ) ),
535 'comment' => $this->getRandomCommentStoreComment(),
536 'timestamp' => '20171117010101',
537 ],
538 new IncompleteRevisionException( 'user must not be NULL!' )
539 ];
540 }
541
547 array $revDetails = [],
548 Exception $exception
549 ) {
550 $rev = $this->getRevisionRecordFromDetailsArray( $revDetails );
551
552 $store = MediaWikiServices::getInstance()->getRevisionStore();
553
554 $this->setExpectedException(
555 get_class( $exception ),
556 $exception->getMessage(),
557 $exception->getCode()
558 );
559 $store->insertRevisionOn( $rev, wfGetDB( DB_MASTER ) );
560 }
561
562 public function provideNewNullRevision() {
563 yield [
564 Title::newFromText( 'UTPage_notAutoCreated' ),
565 [ 'content' => [ 'main' => new WikitextContent( 'Flubber1' ) ] ],
566 CommentStoreComment::newUnsavedComment( __METHOD__ . ' comment1' ),
567 true,
568 ];
569 yield [
570 Title::newFromText( 'UTPage_notAutoCreated' ),
571 [ 'content' => [ 'main' => new WikitextContent( 'Flubber2' ) ] ],
572 CommentStoreComment::newUnsavedComment( __METHOD__ . ' comment2', [ 'a' => 1 ] ),
573 false,
574 ];
575 }
576
582 public function testNewNullRevision( Title $title, $revDetails, $comment, $minor = false ) {
583 $this->overrideMwServices();
584
585 $user = TestUserRegistry::getMutableTestUser( __METHOD__ )->getUser();
586 $page = WikiPage::factory( $title );
587
588 if ( !$page->exists() ) {
589 $page->doEditContent( new WikitextContent( __METHOD__ ), __METHOD__, EDIT_NEW );
590 }
591
592 $revDetails['page'] = $page->getId();
593 $revDetails['timestamp'] = wfTimestampNow();
594 $revDetails['comment'] = CommentStoreComment::newUnsavedComment( 'Base' );
595 $revDetails['user'] = $user;
596
597 $baseRev = $this->getRevisionRecordFromDetailsArray( $revDetails );
598 $store = MediaWikiServices::getInstance()->getRevisionStore();
599
600 $dbw = wfGetDB( DB_MASTER );
601 $baseRev = $store->insertRevisionOn( $baseRev, $dbw );
602 $page->updateRevisionOn( $dbw, new Revision( $baseRev ), $page->getLatest() );
603
604 $record = $store->newNullRevision(
606 $title,
607 $comment,
608 $minor,
609 $user
610 );
611
612 $this->assertEquals( $title->getNamespace(), $record->getPageAsLinkTarget()->getNamespace() );
613 $this->assertEquals( $title->getDBkey(), $record->getPageAsLinkTarget()->getDBkey() );
614 $this->assertEquals( $comment, $record->getComment() );
615 $this->assertEquals( $minor, $record->isMinor() );
616 $this->assertEquals( $user->getName(), $record->getUser()->getName() );
617 $this->assertEquals( $baseRev->getId(), $record->getParentId() );
618
619 $this->assertArrayEquals(
620 $baseRev->getSlotRoles(),
621 $record->getSlotRoles()
622 );
623
624 foreach ( $baseRev->getSlotRoles() as $role ) {
625 $parentSlot = $baseRev->getSlot( $role );
626 $slot = $record->getSlot( $role );
627
628 $this->assertTrue( $slot->isInherited(), 'isInherited' );
629 $this->assertSame( $parentSlot->getOrigin(), $slot->getOrigin(), 'getOrigin' );
630 $this->assertSameSlotContent( $parentSlot, $slot );
631 }
632 }
633
638 $store = MediaWikiServices::getInstance()->getRevisionStore();
639 $record = $store->newNullRevision(
641 Title::newFromText( __METHOD__ . '.iDontExist!' ),
642 CommentStoreComment::newUnsavedComment( __METHOD__ . ' comment' ),
643 false,
644 TestUserRegistry::getMutableTestUser( __METHOD__ )->getUser()
645 );
646 $this->assertNull( $record );
647 }
648
653 $page = $this->getTestPage();
654 $status = $page->doEditContent( new WikitextContent( __METHOD__ ), __METHOD__ );
656 $rev = $status->value['revision'];
657
658 $store = MediaWikiServices::getInstance()->getRevisionStore();
659 $revisionRecord = $store->getRevisionById( $rev->getId() );
660 $result = $store->getRcIdIfUnpatrolled( $revisionRecord );
661
662 $this->assertGreaterThan( 0, $result );
663 $this->assertSame(
664 $store->getRecentChange( $revisionRecord )->getAttribute( 'rc_id' ),
665 $result
666 );
667 }
668
673 // This assumes that sysops are auto patrolled
674 $sysop = $this->getTestSysop()->getUser();
675 $page = $this->getTestPage();
676 $status = $page->doEditContent(
677 new WikitextContent( __METHOD__ ),
678 __METHOD__,
679 0,
680 false,
681 $sysop
682 );
684 $rev = $status->value['revision'];
685
686 $store = MediaWikiServices::getInstance()->getRevisionStore();
687 $revisionRecord = $store->getRevisionById( $rev->getId() );
688 $result = $store->getRcIdIfUnpatrolled( $revisionRecord );
689
690 $this->assertSame( 0, $result );
691 }
692
696 public function testGetRecentChange() {
697 $page = $this->getTestPage();
698 $content = new WikitextContent( __METHOD__ );
699 $status = $page->doEditContent( $content, __METHOD__ );
701 $rev = $status->value['revision'];
702
703 $store = MediaWikiServices::getInstance()->getRevisionStore();
704 $revRecord = $store->getRevisionById( $rev->getId() );
705 $recentChange = $store->getRecentChange( $revRecord );
706
707 $this->assertEquals( $rev->getId(), $recentChange->getAttribute( 'rc_this_oldid' ) );
708 $this->assertEquals( $rev->getRecentChange(), $recentChange );
709 }
710
714 public function testGetRevisionById() {
715 $page = $this->getTestPage();
716 $content = new WikitextContent( __METHOD__ );
717 $status = $page->doEditContent( $content, __METHOD__ );
719 $rev = $status->value['revision'];
720
721 $store = MediaWikiServices::getInstance()->getRevisionStore();
722 $revRecord = $store->getRevisionById( $rev->getId() );
723
724 $this->assertSame( $rev->getId(), $revRecord->getId() );
725 $this->assertTrue( $revRecord->getSlot( SlotRecord::MAIN )->getContent()->equals( $content ) );
726 $this->assertSame( __METHOD__, $revRecord->getComment()->text );
727 }
728
732 public function testGetRevisionByTitle() {
733 $page = $this->getTestPage();
734 $content = new WikitextContent( __METHOD__ );
735 $status = $page->doEditContent( $content, __METHOD__ );
737 $rev = $status->value['revision'];
738
739 $store = MediaWikiServices::getInstance()->getRevisionStore();
740 $revRecord = $store->getRevisionByTitle( $page->getTitle() );
741
742 $this->assertSame( $rev->getId(), $revRecord->getId() );
743 $this->assertTrue( $revRecord->getSlot( SlotRecord::MAIN )->getContent()->equals( $content ) );
744 $this->assertSame( __METHOD__, $revRecord->getComment()->text );
745 }
746
750 public function testGetRevisionByPageId() {
751 $page = $this->getTestPage();
752 $content = new WikitextContent( __METHOD__ );
753 $status = $page->doEditContent( $content, __METHOD__ );
755 $rev = $status->value['revision'];
756
757 $store = MediaWikiServices::getInstance()->getRevisionStore();
758 $revRecord = $store->getRevisionByPageId( $page->getId() );
759
760 $this->assertSame( $rev->getId(), $revRecord->getId() );
761 $this->assertTrue( $revRecord->getSlot( SlotRecord::MAIN )->getContent()->equals( $content ) );
762 $this->assertSame( __METHOD__, $revRecord->getComment()->text );
763 }
764
768 public function testGetRevisionByTimestamp() {
769 // Make sure there is 1 second between the last revision and the rev we create...
770 // Otherwise we might not get the correct revision and the test may fail...
771 // :(
772 $page = $this->getTestPage();
773 sleep( 1 );
774 $content = new WikitextContent( __METHOD__ );
775 $status = $page->doEditContent( $content, __METHOD__ );
777 $rev = $status->value['revision'];
778
779 $store = MediaWikiServices::getInstance()->getRevisionStore();
780 $revRecord = $store->getRevisionByTimestamp(
781 $page->getTitle(),
782 $rev->getTimestamp()
783 );
784
785 $this->assertSame( $rev->getId(), $revRecord->getId() );
786 $this->assertTrue( $revRecord->getSlot( SlotRecord::MAIN )->getContent()->equals( $content ) );
787 $this->assertSame( __METHOD__, $revRecord->getComment()->text );
788 }
789
790 protected function revisionToRow( Revision $rev, $options = [ 'page', 'user', 'comment' ] ) {
791 // XXX: the WikiPage object loads another RevisionRecord from the database. Not great.
792 $page = WikiPage::factory( $rev->getTitle() );
793
794 $fields = [
795 'rev_id' => (string)$rev->getId(),
796 'rev_page' => (string)$rev->getPage(),
797 'rev_timestamp' => $this->db->timestamp( $rev->getTimestamp() ),
798 'rev_user_text' => (string)$rev->getUserText(),
799 'rev_user' => (string)$rev->getUser(),
800 'rev_minor_edit' => $rev->isMinor() ? '1' : '0',
801 'rev_deleted' => (string)$rev->getVisibility(),
802 'rev_len' => (string)$rev->getSize(),
803 'rev_parent_id' => (string)$rev->getParentId(),
804 'rev_sha1' => (string)$rev->getSha1(),
805 ];
806
807 if ( in_array( 'page', $options ) ) {
808 $fields += [
809 'page_namespace' => (string)$page->getTitle()->getNamespace(),
810 'page_title' => $page->getTitle()->getDBkey(),
811 'page_id' => (string)$page->getId(),
812 'page_latest' => (string)$page->getLatest(),
813 'page_is_redirect' => $page->isRedirect() ? '1' : '0',
814 'page_len' => (string)$page->getContent()->getSize(),
815 ];
816 }
817
818 if ( in_array( 'user', $options ) ) {
819 $fields += [
820 'user_name' => (string)$rev->getUserText(),
821 ];
822 }
823
824 if ( in_array( 'comment', $options ) ) {
825 $fields += [
826 'rev_comment_text' => $rev->getComment(),
827 'rev_comment_data' => null,
828 'rev_comment_cid' => null,
829 ];
830 }
831
832 if ( $rev->getId() ) {
833 $fields += [
834 'rev_id' => (string)$rev->getId(),
835 ];
836 }
837
838 return (object)$fields;
839 }
840
843 RevisionRecord $record
844 ) {
845 $this->assertSame( $rev->getId(), $record->getId() );
846 $this->assertSame( $rev->getPage(), $record->getPageId() );
847 $this->assertSame( $rev->getTimestamp(), $record->getTimestamp() );
848 $this->assertSame( $rev->getUserText(), $record->getUser()->getName() );
849 $this->assertSame( $rev->getUser(), $record->getUser()->getId() );
850 $this->assertSame( $rev->isMinor(), $record->isMinor() );
851 $this->assertSame( $rev->getVisibility(), $record->getVisibility() );
852 $this->assertSame( $rev->getSize(), $record->getSize() );
857 $expectedParent = $rev->getParentId();
858 if ( $expectedParent === null ) {
859 $expectedParent = 0;
860 }
861 $this->assertSame( $expectedParent, $record->getParentId() );
862 $this->assertSame( $rev->getSha1(), $record->getSha1() );
863 $this->assertSame( $rev->getComment(), $record->getComment()->text );
864 $this->assertSame( $rev->getContentFormat(),
865 $record->getContent( SlotRecord::MAIN )->getDefaultFormat() );
866 $this->assertSame( $rev->getContentModel(), $record->getContent( SlotRecord::MAIN )->getModel() );
867 $this->assertLinkTargetsEqual( $rev->getTitle(), $record->getPageAsLinkTarget() );
868
869 $revRec = $rev->getRevisionRecord();
870 $revMain = $revRec->getSlot( SlotRecord::MAIN );
871 $recMain = $record->getSlot( SlotRecord::MAIN );
872
873 $this->assertSame( $revMain->hasOrigin(), $recMain->hasOrigin(), 'hasOrigin' );
874 $this->assertSame( $revMain->hasAddress(), $recMain->hasAddress(), 'hasAddress' );
875 $this->assertSame( $revMain->hasContentId(), $recMain->hasContentId(), 'hasContentId' );
876
877 if ( $revMain->hasOrigin() ) {
878 $this->assertSame( $revMain->getOrigin(), $recMain->getOrigin(), 'getOrigin' );
879 }
880
881 if ( $revMain->hasAddress() ) {
882 $this->assertSame( $revMain->getAddress(), $recMain->getAddress(), 'getAddress' );
883 }
884
885 if ( $revMain->hasContentId() ) {
886 $this->assertSame( $revMain->getContentId(), $recMain->getContentId(), 'getContentId' );
887 }
888 }
889
895 $page = $this->getTestPage();
896 $text = __METHOD__ . 'a-ä';
898 $rev = $page->doEditContent(
899 new WikitextContent( $text ),
900 __METHOD__ . 'a'
901 )->value['revision'];
902
903 $store = MediaWikiServices::getInstance()->getRevisionStore();
904 $info = $store->getQueryInfo();
905 $row = $this->db->selectRow(
906 $info['tables'],
907 $info['fields'],
908 [ 'rev_id' => $rev->getId() ],
909 __METHOD__,
910 [],
911 $info['joins']
912 );
913 $record = $store->newRevisionFromRow(
914 $row,
915 [],
916 $page->getTitle()
917 );
918 $this->assertRevisionRecordMatchesRevision( $rev, $record );
919 $this->assertSame( $text, $rev->getContent()->serialize() );
920 }
921
926 $page = $this->getTestPage();
927 $text = __METHOD__ . 'a-ä';
929 $rev = $page->doEditContent(
930 new WikitextContent( $text ),
931 __METHOD__ . 'a'
932 )->value['revision'];
933
934 $store = MediaWikiServices::getInstance()->getRevisionStore();
935 $record = $store->newRevisionFromRow(
936 $this->revisionToRow( $rev ),
937 [],
938 $page->getTitle()
939 );
940 $this->assertRevisionRecordMatchesRevision( $rev, $record );
941 $this->assertSame( $text, $rev->getContent()->serialize() );
942 }
943
948 $this->setMwGlobals( 'wgLegacyEncoding', 'windows-1252' );
949 $this->overrideMwServices();
950 $page = $this->getTestPage();
951 $text = __METHOD__ . 'a-ä';
953 $rev = $page->doEditContent(
954 new WikitextContent( $text ),
955 __METHOD__ . 'a'
956 )->value['revision'];
957
958 $store = MediaWikiServices::getInstance()->getRevisionStore();
959 $record = $store->newRevisionFromRow(
960 $this->revisionToRow( $rev ),
961 [],
962 $page->getTitle()
963 );
964 $this->assertRevisionRecordMatchesRevision( $rev, $record );
965 $this->assertSame( $text, $rev->getContent()->serialize() );
966 }
967
972 $page = $this->getTestPage();
973 $text = __METHOD__ . 'b-ä';
975 $rev = $page->doEditContent(
976 new WikitextContent( $text ),
977 __METHOD__ . 'b',
978 0,
979 false,
980 $this->getTestUser()->getUser()
981 )->value['revision'];
982
983 $store = MediaWikiServices::getInstance()->getRevisionStore();
984 $record = $store->newRevisionFromRow(
985 $this->revisionToRow( $rev ),
986 [],
987 $page->getTitle()
988 );
989 $this->assertRevisionRecordMatchesRevision( $rev, $record );
990 $this->assertSame( $text, $rev->getContent()->serialize() );
991 }
992
998 $store = MediaWikiServices::getInstance()->getRevisionStore();
999 $title = Title::newFromText( __METHOD__ );
1000 $text = __METHOD__ . '-bä';
1001 $page = WikiPage::factory( $title );
1003 $orig = $page->doEditContent( new WikitextContent( $text ), __METHOD__ )
1004 ->value['revision'];
1005 $page->doDeleteArticle( __METHOD__ );
1006
1007 $db = wfGetDB( DB_MASTER );
1008 $arQuery = $store->getArchiveQueryInfo();
1009 $res = $db->select(
1010 $arQuery['tables'], $arQuery['fields'], [ 'ar_rev_id' => $orig->getId() ],
1011 __METHOD__, [], $arQuery['joins']
1012 );
1013 $this->assertTrue( is_object( $res ), 'query failed' );
1014
1015 $row = $res->fetchObject();
1016 $res->free();
1017 $record = $store->newRevisionFromArchiveRow( $row );
1018
1019 $this->assertRevisionRecordMatchesRevision( $orig, $record );
1020 $this->assertSame( $text, $record->getContent( SlotRecord::MAIN )->serialize() );
1021 }
1022
1027 $this->setMwGlobals( 'wgLegacyEncoding', 'windows-1252' );
1028 $this->overrideMwServices();
1029 $store = MediaWikiServices::getInstance()->getRevisionStore();
1030 $title = Title::newFromText( __METHOD__ );
1031 $text = __METHOD__ . '-bä';
1032 $page = WikiPage::factory( $title );
1034 $orig = $page->doEditContent( new WikitextContent( $text ), __METHOD__ )
1035 ->value['revision'];
1036 $page->doDeleteArticle( __METHOD__ );
1037
1038 $db = wfGetDB( DB_MASTER );
1039 $arQuery = $store->getArchiveQueryInfo();
1040 $res = $db->select(
1041 $arQuery['tables'], $arQuery['fields'], [ 'ar_rev_id' => $orig->getId() ],
1042 __METHOD__, [], $arQuery['joins']
1043 );
1044 $this->assertTrue( is_object( $res ), 'query failed' );
1045
1046 $row = $res->fetchObject();
1047 $res->free();
1048 $record = $store->newRevisionFromArchiveRow( $row );
1049
1050 $this->assertRevisionRecordMatchesRevision( $orig, $record );
1051 $this->assertSame( $text, $record->getContent( SlotRecord::MAIN )->serialize() );
1052 }
1053
1058 $store = MediaWikiServices::getInstance()->getRevisionStore();
1059
1060 $row = (object)[
1061 'ar_id' => '1',
1062 'ar_page_id' => '2',
1063 'ar_namespace' => '0',
1064 'ar_title' => 'Something',
1065 'ar_rev_id' => '2',
1066 'ar_text_id' => '47',
1067 'ar_timestamp' => '20180528192356',
1068 'ar_minor_edit' => '0',
1069 'ar_deleted' => '0',
1070 'ar_len' => '78',
1071 'ar_parent_id' => '0',
1072 'ar_sha1' => 'deadbeef',
1073 'ar_comment_text' => 'whatever',
1074 'ar_comment_data' => null,
1075 'ar_comment_cid' => null,
1076 'ar_user' => '0',
1077 'ar_user_text' => '', // this is the important bit
1078 'ar_actor' => null,
1079 'ar_content_format' => null,
1080 'ar_content_model' => null,
1081 ];
1082
1083 \Wikimedia\suppressWarnings();
1084 $record = $store->newRevisionFromArchiveRow( $row );
1085 \Wikimedia\suppressWarnings( true );
1086
1087 $this->assertInstanceOf( RevisionRecord::class, $record );
1088 $this->assertInstanceOf( UserIdentityValue::class, $record->getUser() );
1089 $this->assertSame( 'Unknown user', $record->getUser()->getName() );
1090 }
1091
1096 $store = MediaWikiServices::getInstance()->getRevisionStore();
1097 $title = Title::newFromText( __METHOD__ );
1098
1099 $row = (object)[
1100 'rev_id' => '2',
1101 'rev_page' => '2',
1102 'page_namespace' => '0',
1103 'page_title' => $title->getText(),
1104 'rev_text_id' => '47',
1105 'rev_timestamp' => '20180528192356',
1106 'rev_minor_edit' => '0',
1107 'rev_deleted' => '0',
1108 'rev_len' => '78',
1109 'rev_parent_id' => '0',
1110 'rev_sha1' => 'deadbeef',
1111 'rev_comment_text' => 'whatever',
1112 'rev_comment_data' => null,
1113 'rev_comment_cid' => null,
1114 'rev_user' => '0',
1115 'rev_user_text' => '', // this is the important bit
1116 'rev_actor' => null,
1117 'rev_content_format' => null,
1118 'rev_content_model' => null,
1119 ];
1120
1121 \Wikimedia\suppressWarnings();
1122 $record = $store->newRevisionFromRow( $row, 0, $title );
1123 \Wikimedia\suppressWarnings( true );
1124
1125 $this->assertNotNull( $record );
1126 $this->assertNotNull( $record->getUser() );
1127 $this->assertNotEmpty( $record->getUser()->getName() );
1128 }
1129
1134 // This is a round trip test for deletion and undeletion of a
1135 // revision row via the archive table.
1136
1137 $store = MediaWikiServices::getInstance()->getRevisionStore();
1138 $title = Title::newFromText( __METHOD__ );
1139
1140 $page = WikiPage::factory( $title );
1142 $page->doEditContent( new WikitextContent( "First" ), __METHOD__ . '-first' );
1143 $origRev = $page->doEditContent( new WikitextContent( "Foo" ), __METHOD__ )
1144 ->value['revision'];
1145 $orig = $origRev->getRevisionRecord();
1146 $page->doDeleteArticle( __METHOD__ );
1147
1148 // re-create page, so we can later load revisions for it
1149 $page->doEditContent( new WikitextContent( 'Two' ), __METHOD__ );
1150
1151 $db = wfGetDB( DB_MASTER );
1152 $arQuery = $store->getArchiveQueryInfo();
1153 $row = $db->selectRow(
1154 $arQuery['tables'], $arQuery['fields'], [ 'ar_rev_id' => $orig->getId() ],
1155 __METHOD__, [], $arQuery['joins']
1156 );
1157
1158 $this->assertNotFalse( $row, 'query failed' );
1159
1160 $record = $store->newRevisionFromArchiveRow(
1161 $row,
1162 0,
1163 $title,
1164 [ 'page_id' => $title->getArticleID() ]
1165 );
1166
1167 $restored = $store->insertRevisionOn( $record, $db );
1168
1169 // is the new revision correct?
1170 $this->assertRevisionCompleteness( $restored );
1171 $this->assertRevisionRecordsEqual( $record, $restored );
1172
1173 // does the new revision use the original slot?
1174 $recMain = $record->getSlot( SlotRecord::MAIN );
1175 $restMain = $restored->getSlot( SlotRecord::MAIN );
1176 $this->assertSame( $recMain->getAddress(), $restMain->getAddress() );
1177 $this->assertSame( $recMain->getContentId(), $restMain->getContentId() );
1178 $this->assertSame( $recMain->getOrigin(), $restMain->getOrigin() );
1179 $this->assertSame( 'Foo', $restMain->getContent()->serialize() );
1180
1181 // can we load it from the store?
1182 $loaded = $store->getRevisionById( $restored->getId() );
1183 $this->assertNotNull( $loaded );
1184 $this->assertRevisionCompleteness( $loaded );
1185 $this->assertRevisionRecordsEqual( $restored, $loaded );
1186
1187 // can we find it directly in the database?
1188 $this->assertRevisionExistsInDatabase( $restored );
1189 }
1190
1194 public function testLoadRevisionFromId() {
1195 $title = Title::newFromText( __METHOD__ );
1196 $page = WikiPage::factory( $title );
1198 $rev = $page->doEditContent( new WikitextContent( __METHOD__ ), __METHOD__ )
1199 ->value['revision'];
1200
1201 $store = MediaWikiServices::getInstance()->getRevisionStore();
1202 $result = $store->loadRevisionFromId( wfGetDB( DB_MASTER ), $rev->getId() );
1204 }
1205
1209 public function testLoadRevisionFromPageId() {
1210 $title = Title::newFromText( __METHOD__ );
1211 $page = WikiPage::factory( $title );
1213 $rev = $page->doEditContent( new WikitextContent( __METHOD__ ), __METHOD__ )
1214 ->value['revision'];
1215
1216 $store = MediaWikiServices::getInstance()->getRevisionStore();
1217 $result = $store->loadRevisionFromPageId( wfGetDB( DB_MASTER ), $page->getId() );
1219 }
1220
1224 public function testLoadRevisionFromTitle() {
1225 $title = Title::newFromText( __METHOD__ );
1226 $page = WikiPage::factory( $title );
1228 $rev = $page->doEditContent( new WikitextContent( __METHOD__ ), __METHOD__ )
1229 ->value['revision'];
1230
1231 $store = MediaWikiServices::getInstance()->getRevisionStore();
1232 $result = $store->loadRevisionFromTitle( wfGetDB( DB_MASTER ), $title );
1234 }
1235
1240 $title = Title::newFromText( __METHOD__ );
1241 $page = WikiPage::factory( $title );
1243 $revOne = $page->doEditContent( new WikitextContent( __METHOD__ ), __METHOD__ )
1244 ->value['revision'];
1245 // Sleep to ensure different timestamps... )(evil)
1246 sleep( 1 );
1248 $revTwo = $page->doEditContent( new WikitextContent( __METHOD__ . 'a' ), '' )
1249 ->value['revision'];
1250
1251 $store = MediaWikiServices::getInstance()->getRevisionStore();
1252 $this->assertNull(
1253 $store->loadRevisionFromTimestamp( wfGetDB( DB_MASTER ), $title, '20150101010101' )
1254 );
1255 $this->assertSame(
1256 $revOne->getId(),
1257 $store->loadRevisionFromTimestamp(
1258 wfGetDB( DB_MASTER ),
1259 $title,
1260 $revOne->getTimestamp()
1261 )->getId()
1262 );
1263 $this->assertSame(
1264 $revTwo->getId(),
1265 $store->loadRevisionFromTimestamp(
1266 wfGetDB( DB_MASTER ),
1267 $title,
1268 $revTwo->getTimestamp()
1269 )->getId()
1270 );
1271 }
1272
1276 public function testGetParentLengths() {
1277 $page = WikiPage::factory( Title::newFromText( __METHOD__ ) );
1279 $revOne = $page->doEditContent(
1280 new WikitextContent( __METHOD__ ), __METHOD__
1281 )->value['revision'];
1283 $revTwo = $page->doEditContent(
1284 new WikitextContent( __METHOD__ . '2' ), __METHOD__
1285 )->value['revision'];
1286
1287 $store = MediaWikiServices::getInstance()->getRevisionStore();
1288 $this->assertSame(
1289 [
1290 $revOne->getId() => strlen( __METHOD__ ),
1291 ],
1292 $store->listRevisionSizes(
1293 wfGetDB( DB_MASTER ),
1294 [ $revOne->getId() ]
1295 )
1296 );
1297 $this->assertSame(
1298 [
1299 $revOne->getId() => strlen( __METHOD__ ),
1300 $revTwo->getId() => strlen( __METHOD__ ) + 1,
1301 ],
1302 $store->listRevisionSizes(
1303 wfGetDB( DB_MASTER ),
1304 [ $revOne->getId(), $revTwo->getId() ]
1305 )
1306 );
1307 }
1308
1312 public function testGetPreviousRevision() {
1313 $page = WikiPage::factory( Title::newFromText( __METHOD__ ) );
1315 $revOne = $page->doEditContent(
1316 new WikitextContent( __METHOD__ ), __METHOD__
1317 )->value['revision'];
1319 $revTwo = $page->doEditContent(
1320 new WikitextContent( __METHOD__ . '2' ), __METHOD__
1321 )->value['revision'];
1322
1323 $store = MediaWikiServices::getInstance()->getRevisionStore();
1324 $this->assertNull(
1325 $store->getPreviousRevision( $store->getRevisionById( $revOne->getId() ) )
1326 );
1327 $this->assertSame(
1328 $revOne->getId(),
1329 $store->getPreviousRevision( $store->getRevisionById( $revTwo->getId() ) )->getId()
1330 );
1331 }
1332
1336 public function testGetNextRevision() {
1337 $page = WikiPage::factory( Title::newFromText( __METHOD__ ) );
1339 $revOne = $page->doEditContent(
1340 new WikitextContent( __METHOD__ ), __METHOD__
1341 )->value['revision'];
1343 $revTwo = $page->doEditContent(
1344 new WikitextContent( __METHOD__ . '2' ), __METHOD__
1345 )->value['revision'];
1346
1347 $store = MediaWikiServices::getInstance()->getRevisionStore();
1348 $this->assertSame(
1349 $revTwo->getId(),
1350 $store->getNextRevision( $store->getRevisionById( $revOne->getId() ) )->getId()
1351 );
1352 $this->assertNull(
1353 $store->getNextRevision( $store->getRevisionById( $revTwo->getId() ) )
1354 );
1355 }
1356
1361 $page = $this->getTestPage();
1363 $rev = $page->doEditContent( new WikitextContent( __METHOD__ ), __METHOD__ )
1364 ->value['revision'];
1365
1366 $store = MediaWikiServices::getInstance()->getRevisionStore();
1367 $result = $store->getTimestampFromId(
1368 $page->getTitle(),
1369 $rev->getId()
1370 );
1371
1372 $this->assertSame( $rev->getTimestamp(), $result );
1373 }
1374
1379 $page = $this->getTestPage();
1381 $rev = $page->doEditContent( new WikitextContent( __METHOD__ ), __METHOD__ )
1382 ->value['revision'];
1383
1384 $store = MediaWikiServices::getInstance()->getRevisionStore();
1385 $result = $store->getTimestampFromId(
1386 $page->getTitle(),
1387 $rev->getId() + 1
1388 );
1389
1390 $this->assertFalse( $result );
1391 }
1392
1396 public function testCountRevisionsByPageId() {
1397 $store = MediaWikiServices::getInstance()->getRevisionStore();
1398 $page = WikiPage::factory( Title::newFromText( __METHOD__ ) );
1399
1400 $this->assertSame(
1401 0,
1402 $store->countRevisionsByPageId( wfGetDB( DB_MASTER ), $page->getId() )
1403 );
1404 $page->doEditContent( new WikitextContent( 'a' ), 'a' );
1405 $this->assertSame(
1406 1,
1407 $store->countRevisionsByPageId( wfGetDB( DB_MASTER ), $page->getId() )
1408 );
1409 $page->doEditContent( new WikitextContent( 'b' ), 'b' );
1410 $this->assertSame(
1411 2,
1412 $store->countRevisionsByPageId( wfGetDB( DB_MASTER ), $page->getId() )
1413 );
1414 }
1415
1419 public function testCountRevisionsByTitle() {
1420 $store = MediaWikiServices::getInstance()->getRevisionStore();
1421 $page = WikiPage::factory( Title::newFromText( __METHOD__ ) );
1422
1423 $this->assertSame(
1424 0,
1425 $store->countRevisionsByTitle( wfGetDB( DB_MASTER ), $page->getTitle() )
1426 );
1427 $page->doEditContent( new WikitextContent( 'a' ), 'a' );
1428 $this->assertSame(
1429 1,
1430 $store->countRevisionsByTitle( wfGetDB( DB_MASTER ), $page->getTitle() )
1431 );
1432 $page->doEditContent( new WikitextContent( 'b' ), 'b' );
1433 $this->assertSame(
1434 2,
1435 $store->countRevisionsByTitle( wfGetDB( DB_MASTER ), $page->getTitle() )
1436 );
1437 }
1438
1443 $sysop = $this->getTestSysop()->getUser();
1444 $page = $this->getTestPage();
1445 $page->doEditContent( new WikitextContent( __METHOD__ ), __METHOD__ );
1446
1447 $store = MediaWikiServices::getInstance()->getRevisionStore();
1448 $result = $store->userWasLastToEdit(
1449 wfGetDB( DB_MASTER ),
1450 $page->getId(),
1451 $sysop->getId(),
1452 '20160101010101'
1453 );
1454 $this->assertFalse( $result );
1455 }
1456
1460 public function testUserWasLastToEdit_true() {
1461 $startTime = wfTimestampNow();
1462 $sysop = $this->getTestSysop()->getUser();
1463 $page = $this->getTestPage();
1464 $page->doEditContent(
1465 new WikitextContent( __METHOD__ ),
1466 __METHOD__,
1467 0,
1468 false,
1469 $sysop
1470 );
1471
1472 $store = MediaWikiServices::getInstance()->getRevisionStore();
1473 $result = $store->userWasLastToEdit(
1474 wfGetDB( DB_MASTER ),
1475 $page->getId(),
1476 $sysop->getId(),
1477 $startTime
1478 );
1479 $this->assertTrue( $result );
1480 }
1481
1486 $page = $this->getTestPage();
1488 $rev = $page->doEditContent(
1489 new WikitextContent( __METHOD__ . 'b' ),
1490 __METHOD__ . 'b',
1491 0,
1492 false,
1493 $this->getTestUser()->getUser()
1494 )->value['revision'];
1495
1496 $store = MediaWikiServices::getInstance()->getRevisionStore();
1497 $record = $store->getKnownCurrentRevision(
1498 $page->getTitle(),
1499 $rev->getId()
1500 );
1501
1502 $this->assertRevisionRecordMatchesRevision( $rev, $record );
1503 }
1504
1506 yield 'Basic array, content object' => [
1507 [
1508 'id' => 2,
1509 'page' => 1,
1510 'timestamp' => '20171017114835',
1511 'user_text' => '111.0.1.2',
1512 'user' => 0,
1513 'minor_edit' => false,
1514 'deleted' => 0,
1515 'len' => 46,
1516 'parent_id' => 1,
1517 'sha1' => 'rdqbbzs3pkhihgbs8qf2q9jsvheag5z',
1518 'comment' => 'Goat Comment!',
1519 'content' => new WikitextContent( 'Some Content' ),
1520 ]
1521 ];
1522 yield 'Basic array, serialized text' => [
1523 [
1524 'id' => 2,
1525 'page' => 1,
1526 'timestamp' => '20171017114835',
1527 'user_text' => '111.0.1.2',
1528 'user' => 0,
1529 'minor_edit' => false,
1530 'deleted' => 0,
1531 'len' => 46,
1532 'parent_id' => 1,
1533 'sha1' => 'rdqbbzs3pkhihgbs8qf2q9jsvheag5z',
1534 'comment' => 'Goat Comment!',
1535 'text' => ( new WikitextContent( 'Söme Content' ) )->serialize(),
1536 ]
1537 ];
1538 yield 'Basic array, serialized text, utf-8 flags' => [
1539 [
1540 'id' => 2,
1541 'page' => 1,
1542 'timestamp' => '20171017114835',
1543 'user_text' => '111.0.1.2',
1544 'user' => 0,
1545 'minor_edit' => false,
1546 'deleted' => 0,
1547 'len' => 46,
1548 'parent_id' => 1,
1549 'sha1' => 'rdqbbzs3pkhihgbs8qf2q9jsvheag5z',
1550 'comment' => 'Goat Comment!',
1551 'text' => ( new WikitextContent( 'Söme Content' ) )->serialize(),
1552 'flags' => 'utf-8',
1553 ]
1554 ];
1555 yield 'Basic array, with title' => [
1556 [
1557 'title' => Title::newFromText( 'SomeText' ),
1558 'timestamp' => '20171017114835',
1559 'user_text' => '111.0.1.2',
1560 'user' => 0,
1561 'minor_edit' => false,
1562 'deleted' => 0,
1563 'len' => 46,
1564 'parent_id' => 1,
1565 'sha1' => 'rdqbbzs3pkhihgbs8qf2q9jsvheag5z',
1566 'comment' => 'Goat Comment!',
1567 'content' => new WikitextContent( 'Some Content' ),
1568 ]
1569 ];
1570 yield 'Basic array, no user field' => [
1571 [
1572 'id' => 2,
1573 'page' => 1,
1574 'timestamp' => '20171017114835',
1575 'user_text' => '111.0.1.3',
1576 'minor_edit' => false,
1577 'deleted' => 0,
1578 'len' => 46,
1579 'parent_id' => 1,
1580 'sha1' => 'rdqbbzs3pkhihgbs8qf2q9jsvheag5z',
1581 'comment' => 'Goat Comment!',
1582 'content' => new WikitextContent( 'Some Content' ),
1583 ]
1584 ];
1585 }
1586
1591 public function testNewMutableRevisionFromArray( array $array ) {
1592 $store = MediaWikiServices::getInstance()->getRevisionStore();
1593
1594 // HACK: if $array['page'] is given, make sure that the page exists
1595 if ( isset( $array['page'] ) ) {
1596 $t = Title::newFromID( $array['page'] );
1597 if ( !$t || !$t->exists() ) {
1598 $t = Title::makeTitle( NS_MAIN, __METHOD__ );
1599 $info = $this->insertPage( $t );
1600 $array['page'] = $info['id'];
1601 }
1602 }
1603
1604 $result = $store->newMutableRevisionFromArray( $array );
1605
1606 if ( isset( $array['id'] ) ) {
1607 $this->assertSame( $array['id'], $result->getId() );
1608 }
1609 if ( isset( $array['page'] ) ) {
1610 $this->assertSame( $array['page'], $result->getPageId() );
1611 }
1612 $this->assertSame( $array['timestamp'], $result->getTimestamp() );
1613 $this->assertSame( $array['user_text'], $result->getUser()->getName() );
1614 if ( isset( $array['user'] ) ) {
1615 $this->assertSame( $array['user'], $result->getUser()->getId() );
1616 }
1617 $this->assertSame( (bool)$array['minor_edit'], $result->isMinor() );
1618 $this->assertSame( $array['deleted'], $result->getVisibility() );
1619 $this->assertSame( $array['len'], $result->getSize() );
1620 $this->assertSame( $array['parent_id'], $result->getParentId() );
1621 $this->assertSame( $array['sha1'], $result->getSha1() );
1622 $this->assertSame( $array['comment'], $result->getComment()->text );
1623 if ( isset( $array['content'] ) ) {
1624 foreach ( $array['content'] as $role => $content ) {
1625 $this->assertTrue(
1626 $result->getContent( $role )->equals( $content )
1627 );
1628 }
1629 } elseif ( isset( $array['text'] ) ) {
1630 $this->assertSame( $array['text'],
1631 $result->getSlot( SlotRecord::MAIN )->getContent()->serialize() );
1632 } elseif ( isset( $array['content_format'] ) ) {
1633 $this->assertSame(
1634 $array['content_format'],
1635 $result->getSlot( SlotRecord::MAIN )->getContent()->getDefaultFormat()
1636 );
1637 $this->assertSame( $array['content_model'], $result->getSlot( SlotRecord::MAIN )->getModel() );
1638 }
1639 }
1640
1646 $cache = new WANObjectCache( [ 'cache' => new HashBagOStuff() ] );
1647 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
1648 $blobStore = new SqlBlobStore( $lb, $cache );
1649 $blobStore->setLegacyEncoding( 'windows-1252', Language::factory( 'en' ) );
1650
1651 $factory = $this->getMockBuilder( BlobStoreFactory::class )
1652 ->setMethods( [ 'newBlobStore', 'newSqlBlobStore' ] )
1653 ->disableOriginalConstructor()
1654 ->getMock();
1655 $factory->expects( $this->any() )
1656 ->method( 'newBlobStore' )
1657 ->willReturn( $blobStore );
1658 $factory->expects( $this->any() )
1659 ->method( 'newSqlBlobStore' )
1660 ->willReturn( $blobStore );
1661
1662 $this->setService( 'BlobStoreFactory', $factory );
1663
1664 $this->testNewMutableRevisionFromArray( $array );
1665 }
1666
1667}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
serialize()
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
CommentStoreComment represents a comment stored by CommentStore.
Simple store for keeping values in an associative array for the current process.
Internationalisation code.
Definition Language.php:35
Database $db
Primary database.
static getTestSysop()
Convenience method for getting an immutable admin test user.
overrideMwServices(Config $configOverrides=null, array $services=[])
Stashes the global instance of MediaWikiServices, and installs a new one, allowing test cases to over...
setMwGlobals( $pairs, $value=null)
Sets a global, maintaining a stashed version of the previous global to be restored in tearDown.
ensureMockDatabaseConnection(IDatabase $db)
setService( $name, $object)
Sets a service, maintaining a stashed version of the previous service to be restored in tearDown.
insertPage( $pageName, $text='Sample page for unit test.', $namespace=null, User $user=null)
Insert a new page.
static getTestUser( $groups=[])
Convenience method for getting an immutable test user.
assertSelect( $table, $fields, $condition, array $expectedRows, array $options=[], array $join_conds=[])
Asserts that the given database query yields the rows given by $expectedRows.
assertArrayEquals(array $expected, array $actual, $ordered=false, $named=false)
Assert that two arrays are equal.
MediaWikiServices is the service locator for the application scope of MediaWiki.
static getInstance()
Returns the global default instance of the top level service locator.
Exception throw when trying to access undefined fields on an incomplete RevisionRecord.
Mutable RevisionRecord implementation, for building new revision entries programmatically.
Page revision base class.
getParentId()
Get parent revision ID (the original previous page revision).
getWikiId()
Get the ID of the wiki this revision belongs to.
getSize()
Returns the nominal size of this revision, in bogo-bytes.
getComment( $audience=self::FOR_PUBLIC, User $user=null)
Fetch revision comment, if it's available to the specified audience.
getSlotRoles()
Returns the slot names (roles) of all slots present in this revision.
getVisibility()
Get the deletion bitfield of the revision.
getContent( $role, $audience=self::FOR_PUBLIC, User $user=null)
Returns the Content of the given slot of this revision.
getTimestamp()
MCR migration note: this replaces Revision::getTimestamp.
hasSlot( $role)
Returns whether the given slot is defined in this revision.
getSlot( $role, $audience=self::FOR_PUBLIC, User $user=null)
Returns meta-data for the given slot.
getSha1()
Returns the base36 sha1 of this revision.
isMinor()
MCR migration note: this replaces Revision::isMinor.
getPageAsLinkTarget()
Returns the title of the page this revision is associated with as a LinkTarget object.
getUser( $audience=self::FOR_PUBLIC, User $user=null)
Fetch revision's author's user identity, if it's available to the specified audience.
isDeleted( $field)
MCR migration note: this replaces Revision::isDeleted.
Service for looking up page revisions.
Value object representing a content slot associated with a page revision.
getContent()
Returns the Content of the given slot.
getRole()
Returns the role of the slot.
hasAddress()
Whether this slot has an address.
getSha1()
Returns the content size.
getSize()
Returns the content size.
getAddress()
Returns the address of this slot's content.
hasRevision()
Whether this slot has revision ID associated.
getModel()
Returns the content model.
getRevision()
Returns the ID of the revision this slot is associated with.
getFormat()
Returns the blob serialization format as a MIME type.
Service for instantiating BlobStores.
Service for storing and loading Content objects.
testCountRevisionsByPageId()
\MediaWiki\Revision\RevisionStore::countRevisionsByPageId
testGetNextRevision()
\MediaWiki\Revision\RevisionStore::getNextRevision
testNewRevisionFromArchiveRow_getArchiveQueryInfo()
\MediaWiki\Revision\RevisionStore::newRevisionFromArchiveRow \MediaWiki\Revision\RevisionStore::getAr...
testNewRevisionFromRow_anonEdit_legacyEncoding()
\MediaWiki\Revision\RevisionStore::newRevisionFromRow
testNewNullRevision(Title $title, $revDetails, $comment, $minor=false)
provideNewNullRevision \MediaWiki\Revision\RevisionStore::newNullRevision \MediaWiki\Revision\Revisio...
testLoadRevisionFromPageId()
\MediaWiki\Revision\RevisionStore::loadRevisionFromPageId
testNewRevisionFromArchiveRow_legacyEncoding()
\MediaWiki\Revision\RevisionStore::newRevisionFromArchiveRow
testCountRevisionsByTitle()
\MediaWiki\Revision\RevisionStore::countRevisionsByTitle
testGetRevisionByPageId()
\MediaWiki\Revision\RevisionStore::getRevisionByPageId
testGetRcIdIfUnpatrolled_returnsZeroIfPatrolled()
\MediaWiki\Revision\RevisionStore::getRcIdIfUnpatrolled
testGetRevisionByTimestamp()
\MediaWiki\Revision\RevisionStore::getRevisionByTimestamp
testGetParentLengths()
\MediaWiki\Revision\RevisionStore::listRevisionSizes
testGetRcIdIfUnpatrolled_returnsRecentChangesId()
\MediaWiki\Revision\RevisionStore::getRcIdIfUnpatrolled
testNewMutableRevisionFromArray(array $array)
provideNewMutableRevisionFromArray \MediaWiki\Revision\RevisionStore::newMutableRevisionFromArray
testDomainCheck( $wikiId, $dbName, $dbPrefix)
provideDomainCheck \MediaWiki\Revision\RevisionStore::checkDatabaseWikiId
testInsertRevisionOn_successes(array $revDetails=[])
provideInsertRevisionOn_successes \MediaWiki\Revision\RevisionStore::insertRevisionOn \MediaWiki\Revi...
assertRevisionRecordMatchesRevision(Revision $rev, RevisionRecord $record)
testLoadRevisionFromTitle()
\MediaWiki\Revision\RevisionStore::loadRevisionFromTitle
assertSlotCompleteness(RevisionRecord $r, SlotRecord $slot)
testGetRecentChange()
\MediaWiki\Revision\RevisionStore::getRecentChange
testUserWasLastToEdit_true()
\MediaWiki\Revision\RevisionStore::userWasLastToEdit
testInsertRevisionOn_failures(array $revDetails=[], Exception $exception)
provideInsertRevisionOn_failures \MediaWiki\Revision\RevisionStore::insertRevisionOn
testInsertRevisionOn_archive()
\MediaWiki\Revision\RevisionStore::insertRevisionOn
testInsertRevisionOn_blobAddressExists()
\MediaWiki\Revision\RevisionStore::insertRevisionOn
testNewNullRevision_nonExistingTitle()
\MediaWiki\Revision\RevisionStore::newNullRevision
testGetRevisionById()
\MediaWiki\Revision\RevisionStore::getRevisionById
testLoadRevisionFromId()
\MediaWiki\Revision\RevisionStore::loadRevisionFromId
testGetTimestampFromId_notFound()
\MediaWiki\Revision\RevisionStore::getTimestampFromId
testLoadRevisionFromTimestamp()
\MediaWiki\Revision\RevisionStore::loadRevisionFromTimestamp
testNewRevisionFromRow_anonEdit()
\MediaWiki\Revision\RevisionStore::newRevisionFromRow
testNewRevisionFromArchiveRow_no_user()
\MediaWiki\Revision\RevisionStore::newRevisionFromArchiveRow
revisionToRow(Revision $rev, $options=[ 'page', 'user', 'comment'])
testNewRevisionFromRow_getQueryInfo()
\MediaWiki\Revision\RevisionStore::newRevisionFromRow \MediaWiki\Revision\RevisionStore::getQueryInfo
testNewMutableRevisionFromArray_legacyEncoding(array $array)
provideNewMutableRevisionFromArray \MediaWiki\Revision\RevisionStore::newMutableRevisionFromArray
testNewRevisionFromRow_no_user()
\MediaWiki\Revision\RevisionStore::newRevisionFromRow
testGetTimestampFromId_found()
\MediaWiki\Revision\RevisionStore::getTimestampFromId
testNewRevisionFromRow_userEdit()
\MediaWiki\Revision\RevisionStore::newRevisionFromRow
testUserWasLastToEdit_false()
\MediaWiki\Revision\RevisionStore::userWasLastToEdit
assertRevisionRecordsEqual(RevisionRecord $r1, RevisionRecord $r2)
testGetKnownCurrentRevision()
\MediaWiki\Revision\RevisionStore::getKnownCurrentRevision
testGetPreviousRevision()
\MediaWiki\Revision\RevisionStore::getPreviousRevision
testGetRevisionByTitle()
\MediaWiki\Revision\RevisionStore::getRevisionByTitle
Value object representing a user's identity.
getTitle()
Returns the title of the page associated with this entry.
Definition Revision.php:763
static getMutableTestUser( $testName, $groups=[])
Get a TestUser object that the caller may modify.
Represents a title within MediaWiki.
Definition Title.php:39
Multi-datacenter aware caching interface.
Class representing a MediaWiki article and history.
Definition WikiPage.php:44
Class to handle database/prefix specification for IDatabase domains.
Relational database abstraction object.
Definition Database.php:48
selectRow( $table, $vars, $conds, $fname=__METHOD__, $options=[], $join_conds=[])
Single row SELECT wrapper.
select( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Execute a SELECT query constructed using the various parameters provided.
Overloads the relevant methods of the real ResultsWrapper so it doesn't go anywhere near an actual da...
Database connection, tracking, load balancing, and transaction manager for a cluster.
Helper class that detects high-contention DB queries via profiling calls.
Content object for wiki text pages.
$res
Definition database.txt:21
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
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:62
const SCHEMA_COMPAT_OLD
Definition Defines.php:290
const NS_MAIN
Definition Defines.php:64
const EDIT_SUPPRESS_RC
Definition Defines.php:155
const MIGRATION_OLD
Definition Defines.php:315
const EDIT_NEW
Definition Defines.php:152
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. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\d*-\d*)") will be honored when streaming the file. '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. 'LanguageGetMagic':DEPRECATED since 1.16! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) '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 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) '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:2042
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:181
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 'DatabaseOraclePostInit':Called after initialising an Oracle database $db:the DatabaseOracle object '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:1305
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:2050
namespace and then decline to actually register it file or subcat img or subcat $title
Definition hooks.txt:994
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:1818
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
Definition hooks.txt:247
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:37
Base interface for content objects.
Definition Content.php:34
getInterwiki()
The interwiki component of this LinkTarget.
getFragment()
Get the link fragment (i.e.
getNamespace()
Get the namespace index.
getDBkey()
Get the main part with underscores.
$cache
Definition mcc.php:33
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))
$content
const DB_REPLICA
Definition defines.php:25
const DB_MASTER
Definition defines.php:26
$params