/
RevisionStore.php
3409 lines (3108 loc) 路 106 KB
/
RevisionStore.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* http://www.gnu.org/copyleft/gpl.html
*
* Attribution notice: when this file was created, much of its content was taken
* from the Revision.php file as present in release 1.30. Refer to the history
* of that file for original authorship (that file was removed entirely in 1.37,
* but its history can still be found in prior versions of MediaWiki).
*
* @file
*/
namespace MediaWiki\Revision;
use BagOStuff;
use Content;
use DBAccessObjectUtils;
use FallbackContent;
use IDBAccessObject;
use InvalidArgumentException;
use LogicException;
use MediaWiki\CommentStore\CommentStore;
use MediaWiki\CommentStore\CommentStoreComment;
use MediaWiki\Content\IContentHandlerFactory;
use MediaWiki\DAO\WikiAwareEntity;
use MediaWiki\HookContainer\HookContainer;
use MediaWiki\HookContainer\HookRunner;
use MediaWiki\Linker\LinkTarget;
use MediaWiki\Page\LegacyArticleIdAccess;
use MediaWiki\Page\PageIdentity;
use MediaWiki\Page\PageIdentityValue;
use MediaWiki\Page\PageStore;
use MediaWiki\Permissions\Authority;
use MediaWiki\Storage\BadBlobException;
use MediaWiki\Storage\BlobAccessException;
use MediaWiki\Storage\BlobStore;
use MediaWiki\Storage\NameTableAccessException;
use MediaWiki\Storage\NameTableStore;
use MediaWiki\Storage\RevisionSlotsUpdate;
use MediaWiki\Storage\SqlBlobStore;
use MediaWiki\Title\Title;
use MediaWiki\Title\TitleFactory;
use MediaWiki\User\ActorMigration;
use MediaWiki\User\ActorStore;
use MediaWiki\User\UserIdentity;
use MWException;
use MWTimestamp;
use MWUnknownContentModelException;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use RecentChange;
use RuntimeException;
use StatusValue;
use stdClass;
use Traversable;
use WANObjectCache;
use Wikimedia\Assert\Assert;
use Wikimedia\IPUtils;
use Wikimedia\Rdbms\Database;
use Wikimedia\Rdbms\DBConnRef;
use Wikimedia\Rdbms\IDatabase;
use Wikimedia\Rdbms\ILoadBalancer;
use Wikimedia\Rdbms\IReadableDatabase;
use Wikimedia\Rdbms\IResultWrapper;
use Wikimedia\Rdbms\Platform\ISQLPlatform;
/**
* Service for looking up page revisions.
*
* @since 1.31
* @since 1.32 Renamed from MediaWiki\Storage\RevisionStore
*
* @note This was written to act as a drop-in replacement for the corresponding
* static methods in the old Revision class (which was later removed in 1.37).
*/
class RevisionStore
implements IDBAccessObject, RevisionFactory, RevisionLookup, LoggerAwareInterface {
use LegacyArticleIdAccess;
public const ROW_CACHE_KEY = 'revision-row-1.29';
public const ORDER_OLDEST_TO_NEWEST = 'ASC';
public const ORDER_NEWEST_TO_OLDEST = 'DESC';
// Constants for get(...)Between methods
public const INCLUDE_OLD = 'include_old';
public const INCLUDE_NEW = 'include_new';
public const INCLUDE_BOTH = 'include_both';
/**
* @var SqlBlobStore
*/
private $blobStore;
/**
* @var false|string
*/
private $wikiId;
/**
* @var ILoadBalancer
*/
private $loadBalancer;
/**
* @var WANObjectCache
*/
private $cache;
/**
* @var BagOStuff
*/
private $localCache;
/**
* @var CommentStore
*/
private $commentStore;
/**
* @var ActorMigration
*/
private $actorMigration;
/** @var ActorStore */
private $actorStore;
/**
* @var LoggerInterface
*/
private $logger;
/**
* @var NameTableStore
*/
private $contentModelStore;
/**
* @var NameTableStore
*/
private $slotRoleStore;
/** @var SlotRoleRegistry */
private $slotRoleRegistry;
/** @var IContentHandlerFactory */
private $contentHandlerFactory;
/** @var HookRunner */
private $hookRunner;
/** @var PageStore */
private $pageStore;
/** @var TitleFactory */
private $titleFactory;
/**
* @param ILoadBalancer $loadBalancer
* @param SqlBlobStore $blobStore
* @param WANObjectCache $cache A cache for caching revision rows. This can be the local
* wiki's default instance even if $wikiId refers to a different wiki, since
* makeGlobalKey() is used to constructed a key that allows cached revision rows from
* the same database to be re-used between wikis. For example, enwiki and frwiki will
* use the same cache keys for revision rows from the wikidatawiki database, regardless
* of the cache's default key space.
* @param BagOStuff $localCache Another layer of cache, best to use APCu here.
* @param CommentStore $commentStore
* @param NameTableStore $contentModelStore
* @param NameTableStore $slotRoleStore
* @param SlotRoleRegistry $slotRoleRegistry
* @param ActorMigration $actorMigration
* @param ActorStore $actorStore
* @param IContentHandlerFactory $contentHandlerFactory
* @param PageStore $pageStore
* @param TitleFactory $titleFactory
* @param HookContainer $hookContainer
* @param false|string $wikiId Relevant wiki id or WikiAwareEntity::LOCAL for the current one
*
* @todo $blobStore should be allowed to be any BlobStore!
*
*/
public function __construct(
ILoadBalancer $loadBalancer,
SqlBlobStore $blobStore,
WANObjectCache $cache,
BagOStuff $localCache,
CommentStore $commentStore,
NameTableStore $contentModelStore,
NameTableStore $slotRoleStore,
SlotRoleRegistry $slotRoleRegistry,
ActorMigration $actorMigration,
ActorStore $actorStore,
IContentHandlerFactory $contentHandlerFactory,
PageStore $pageStore,
TitleFactory $titleFactory,
HookContainer $hookContainer,
$wikiId = WikiAwareEntity::LOCAL
) {
Assert::parameterType( [ 'string', 'false' ], $wikiId, '$wikiId' );
$this->loadBalancer = $loadBalancer;
$this->blobStore = $blobStore;
$this->cache = $cache;
$this->localCache = $localCache;
$this->commentStore = $commentStore;
$this->contentModelStore = $contentModelStore;
$this->slotRoleStore = $slotRoleStore;
$this->slotRoleRegistry = $slotRoleRegistry;
$this->actorMigration = $actorMigration;
$this->actorStore = $actorStore;
$this->wikiId = $wikiId;
$this->logger = new NullLogger();
$this->contentHandlerFactory = $contentHandlerFactory;
$this->pageStore = $pageStore;
$this->titleFactory = $titleFactory;
$this->hookRunner = new HookRunner( $hookContainer );
}
public function setLogger( LoggerInterface $logger ) {
$this->logger = $logger;
}
/**
* @return bool Whether the store is read-only
*/
public function isReadOnly() {
return $this->blobStore->isReadOnly();
}
/**
* Get the ID of the wiki this revision belongs to.
*
* @return string|false The wiki's logical name, of false to indicate the local wiki.
*/
public function getWikiId() {
return $this->wikiId;
}
/**
* @param int $queryFlags a bit field composed of READ_XXX flags
*
* @return DBConnRef
*/
private function getDBConnectionRefForQueryFlags( $queryFlags ) {
[ $mode, ] = DBAccessObjectUtils::getDBOptions( $queryFlags );
return $this->getDBConnectionRef( $mode );
}
/**
* @param int $mode DB_PRIMARY or DB_REPLICA
* @param string|array $groups
* @return DBConnRef
*/
private function getDBConnectionRef( $mode, $groups = [] ) {
return $this->loadBalancer->getConnectionRef( $mode, $groups, $this->wikiId );
}
/**
* Determines the page Title based on the available information.
*
* MCR migration note: this corresponded to Revision::getTitle
*
* @deprecated since 1.36, Use RevisionRecord::getPage() instead.
* @note The resulting Title object will be misleading if the RevisionStore is not
* for the local wiki.
*
* @param int|null $pageId
* @param int|null $revId
* @param int $queryFlags
*
* @return Title
* @throws RevisionAccessException
*/
public function getTitle( $pageId, $revId, $queryFlags = self::READ_NORMAL ) {
// TODO: Hard-deprecate this once getPage() returns a PageRecord. T195069
if ( $this->wikiId !== WikiAwareEntity::LOCAL ) {
wfDeprecatedMsg( 'Using a Title object to refer to a page on another site.', '1.36' );
}
$page = $this->getPage( $pageId, $revId, $queryFlags );
return $this->titleFactory->newFromPageIdentity( $page );
}
/**
* Determines the page based on the available information.
*
* @param int|null $pageId
* @param int|null $revId
* @param int $queryFlags
*
* @return PageIdentity
* @throws RevisionAccessException
*/
private function getPage( ?int $pageId, ?int $revId, int $queryFlags = self::READ_NORMAL ) {
if ( !$pageId && !$revId ) {
throw new InvalidArgumentException( '$pageId and $revId cannot both be 0 or null' );
}
// This method recalls itself with READ_LATEST if READ_NORMAL doesn't get us a Title
// So ignore READ_LATEST_IMMUTABLE flags and handle the fallback logic in this method
if ( DBAccessObjectUtils::hasFlags( $queryFlags, self::READ_LATEST_IMMUTABLE ) ) {
$queryFlags = self::READ_NORMAL;
}
// Loading by ID is best
if ( $pageId !== null && $pageId > 0 ) {
$page = $this->pageStore->getPageById( $pageId, $queryFlags );
if ( $page ) {
return $this->wrapPage( $page );
}
}
// rev_id is defined as NOT NULL, but this revision may not yet have been inserted.
if ( $revId !== null && $revId > 0 ) {
$pageQuery = $this->pageStore->newSelectQueryBuilder( $queryFlags )
->join( 'revision', null, 'page_id=rev_page' )
->conds( [ 'rev_id' => $revId ] )
->caller( __METHOD__ );
$page = $pageQuery->fetchPageRecord();
if ( $page ) {
return $this->wrapPage( $page );
}
}
// If we still don't have a title, fallback to primary DB if that wasn't already happening.
if ( $queryFlags === self::READ_NORMAL ) {
$title = $this->getPage( $pageId, $revId, self::READ_LATEST );
if ( $title ) {
$this->logger->info(
__METHOD__ . ' fell back to READ_LATEST and got a Title.',
[ 'exception' => new RuntimeException() ]
);
return $title;
}
}
throw new RevisionAccessException(
'Could not determine title for page ID {page_id} and revision ID {rev_id}',
[
'page_id' => $pageId,
'rev_id' => $revId,
]
);
}
/**
* @param PageIdentity $page
*
* @return PageIdentity
*/
private function wrapPage( PageIdentity $page ): PageIdentity {
if ( $this->wikiId === WikiAwareEntity::LOCAL ) {
// NOTE: since there is still a lot of code that needs a full Title,
// and uses Title::castFromPageIdentity() to get one, it's beneficial
// to create a Title right away if we can, so we don't have to convert
// over and over later on.
// When there is less need to convert to Title, this special case can
// be removed.
return $this->titleFactory->newFromPageIdentity( $page );
} else {
return $page;
}
}
/**
* @param mixed $value
* @param string $name
*
* @throws IncompleteRevisionException if $value is null
* @return mixed $value, if $value is not null
*/
private function failOnNull( $value, $name ) {
if ( $value === null ) {
throw new IncompleteRevisionException(
"$name must not be " . var_export( $value, true ) . "!"
);
}
return $value;
}
/**
* @param mixed $value
* @param string $name
*
* @throws IncompleteRevisionException if $value is empty
* @return mixed $value, if $value is not null
*/
private function failOnEmpty( $value, $name ) {
if ( $value === null || $value === 0 || $value === '' ) {
throw new IncompleteRevisionException(
"$name must not be " . var_export( $value, true ) . "!"
);
}
return $value;
}
/**
* Insert a new revision into the database, returning the new revision record
* on success and dies horribly on failure.
*
* MCR migration note: this replaced Revision::insertOn
*
* @param RevisionRecord $rev
* @param IDatabase $dbw (primary connection)
*
* @return RevisionRecord the new revision record.
*/
public function insertRevisionOn( RevisionRecord $rev, IDatabase $dbw ) {
// TODO: pass in a DBTransactionContext instead of a database connection.
$this->checkDatabaseDomain( $dbw );
$slotRoles = $rev->getSlotRoles();
// Make sure the main slot is always provided throughout migration
if ( !in_array( SlotRecord::MAIN, $slotRoles ) ) {
throw new IncompleteRevisionException(
'main slot must be provided'
);
}
// Checks
$this->failOnNull( $rev->getSize(), 'size field' );
$this->failOnEmpty( $rev->getSha1(), 'sha1 field' );
$this->failOnEmpty( $rev->getTimestamp(), 'timestamp field' );
$comment = $this->failOnNull( $rev->getComment( RevisionRecord::RAW ), 'comment' );
$user = $this->failOnNull( $rev->getUser( RevisionRecord::RAW ), 'user' );
$this->failOnNull( $user->getId(), 'user field' );
$this->failOnEmpty( $user->getName(), 'user_text field' );
if ( !$rev->isReadyForInsertion() ) {
// This is here for future-proofing. At the time this check being added, it
// was redundant to the individual checks above.
throw new IncompleteRevisionException( 'Revision is incomplete' );
}
if ( $slotRoles == [ SlotRecord::MAIN ] ) {
// T239717: If the main slot is the only slot, make sure the revision's nominal size
// and hash match the main slot's nominal size and hash.
$mainSlot = $rev->getSlot( SlotRecord::MAIN, RevisionRecord::RAW );
Assert::precondition(
$mainSlot->getSize() === $rev->getSize(),
'The revisions\'s size must match the main slot\'s size (see T239717)'
);
Assert::precondition(
$mainSlot->getSha1() === $rev->getSha1(),
'The revisions\'s SHA1 hash must match the main slot\'s SHA1 hash (see T239717)'
);
}
$pageId = $this->failOnEmpty( $rev->getPageId( $this->wikiId ), 'rev_page field' ); // check this early
$parentId = $rev->getParentId() ?? $this->getPreviousRevisionId( $dbw, $rev );
/** @var RevisionRecord $rev */
$rev = $dbw->doAtomicSection(
__METHOD__,
function ( IDatabase $dbw, $fname ) use (
$rev,
$user,
$comment,
$pageId,
$parentId
) {
return $this->insertRevisionInternal(
$rev,
$dbw,
$user,
$comment,
$rev->getPage(),
$pageId,
$parentId
);
}
);
Assert::postcondition( $rev->getId( $this->wikiId ) > 0, 'revision must have an ID' );
Assert::postcondition( $rev->getPageId( $this->wikiId ) > 0, 'revision must have a page ID' );
Assert::postcondition(
$rev->getComment( RevisionRecord::RAW ) !== null,
'revision must have a comment'
);
Assert::postcondition(
$rev->getUser( RevisionRecord::RAW ) !== null,
'revision must have a user'
);
// Trigger exception if the main slot is missing.
// Technically, this could go away after MCR migration: while
// calling code may require a main slot to exist, RevisionStore
// really should not know or care about that requirement.
$rev->getSlot( SlotRecord::MAIN, RevisionRecord::RAW );
foreach ( $slotRoles as $role ) {
$slot = $rev->getSlot( $role, RevisionRecord::RAW );
Assert::postcondition(
$slot->getContent() !== null,
$role . ' slot must have content'
);
Assert::postcondition(
$slot->hasRevision(),
$role . ' slot must have a revision associated'
);
}
$this->hookRunner->onRevisionRecordInserted( $rev );
return $rev;
}
/**
* Update derived slots in an existing revision into the database, returning the modified
* slots on success.
*
* @param RevisionRecord $revision After this method returns, the $revision object will be
* obsolete in that it does not have the new slots.
* @param RevisionSlotsUpdate $revisionSlotsUpdate
* @param IDatabase $dbw (primary connection)
*
* @return SlotRecord[] the new slot records.
* @internal
*/
public function updateSlotsOn(
RevisionRecord $revision,
RevisionSlotsUpdate $revisionSlotsUpdate,
IDatabase $dbw
): array {
$this->checkDatabaseDomain( $dbw );
// Make sure all modified and removed slots are derived slots
foreach ( $revisionSlotsUpdate->getModifiedRoles() as $role ) {
Assert::precondition(
$this->slotRoleRegistry->getRoleHandler( $role )->isDerived(),
'Trying to modify a slot that is not derived'
);
}
foreach ( $revisionSlotsUpdate->getRemovedRoles() as $role ) {
$isDerived = $this->slotRoleRegistry->getRoleHandler( $role )->isDerived();
Assert::precondition(
$isDerived,
'Trying to remove a slot that is not derived'
);
throw new LogicException( 'Removing derived slots is not yet implemented. See T277394.' );
}
/** @var SlotRecord[] $slotRecords */
$slotRecords = $dbw->doAtomicSection(
__METHOD__,
function ( IDatabase $dbw, $fname ) use (
$revision,
$revisionSlotsUpdate
) {
return $this->updateSlotsInternal(
$revision,
$revisionSlotsUpdate,
$dbw
);
}
);
foreach ( $slotRecords as $role => $slot ) {
Assert::postcondition(
$slot->getContent() !== null,
$role . ' slot must have content'
);
Assert::postcondition(
$slot->hasRevision(),
$role . ' slot must have a revision associated'
);
}
return $slotRecords;
}
/**
* @param RevisionRecord $revision
* @param RevisionSlotsUpdate $revisionSlotsUpdate
* @param IDatabase $dbw
* @return SlotRecord[]
*/
private function updateSlotsInternal(
RevisionRecord $revision,
RevisionSlotsUpdate $revisionSlotsUpdate,
IDatabase $dbw
): array {
$page = $revision->getPage();
$revId = $revision->getId( $this->wikiId );
$blobHints = [
BlobStore::PAGE_HINT => $page->getId( $this->wikiId ),
BlobStore::REVISION_HINT => $revId,
BlobStore::PARENT_HINT => $revision->getParentId( $this->wikiId ),
];
$newSlots = [];
foreach ( $revisionSlotsUpdate->getModifiedRoles() as $role ) {
$slot = $revisionSlotsUpdate->getModifiedSlot( $role );
$newSlots[$role] = $this->insertSlotOn( $dbw, $revId, $slot, $page, $blobHints );
}
return $newSlots;
}
private function insertRevisionInternal(
RevisionRecord $rev,
IDatabase $dbw,
UserIdentity $user,
CommentStoreComment $comment,
PageIdentity $page,
$pageId,
$parentId
) {
$slotRoles = $rev->getSlotRoles();
$revisionRow = $this->insertRevisionRowOn(
$dbw,
$rev,
$parentId
);
$revisionId = $revisionRow['rev_id'];
$blobHints = [
BlobStore::PAGE_HINT => $pageId,
BlobStore::REVISION_HINT => $revisionId,
BlobStore::PARENT_HINT => $parentId,
];
$newSlots = [];
foreach ( $slotRoles as $role ) {
$slot = $rev->getSlot( $role, RevisionRecord::RAW );
// If the SlotRecord already has a revision ID set, this means it already exists
// in the database, and should already belong to the current revision.
// However, a slot may already have a revision, but no content ID, if the slot
// is emulated based on the archive table, because we are in SCHEMA_COMPAT_READ_OLD
// mode, and the respective archive row was not yet migrated to the new schema.
// In that case, a new slot row (and content row) must be inserted even during
// undeletion.
if ( $slot->hasRevision() && $slot->hasContentId() ) {
// TODO: properly abort transaction if the assertion fails!
Assert::parameter(
$slot->getRevision() === $revisionId,
'slot role ' . $slot->getRole(),
'Existing slot should belong to revision '
. $revisionId . ', but belongs to revision ' . $slot->getRevision() . '!'
);
// Slot exists, nothing to do, move along.
// This happens when restoring archived revisions.
$newSlots[$role] = $slot;
} else {
$newSlots[$role] = $this->insertSlotOn( $dbw, $revisionId, $slot, $page, $blobHints );
}
}
$this->insertIpChangesRow( $dbw, $user, $rev, $revisionId );
$rev = new RevisionStoreRecord(
$page,
$user,
$comment,
(object)$revisionRow,
new RevisionSlots( $newSlots ),
$this->wikiId
);
return $rev;
}
/**
* @param IDatabase $dbw
* @param int $revisionId
* @param SlotRecord $protoSlot
* @param PageIdentity $page
* @param array $blobHints See the BlobStore::XXX_HINT constants
* @return SlotRecord
*/
private function insertSlotOn(
IDatabase $dbw,
$revisionId,
SlotRecord $protoSlot,
PageIdentity $page,
array $blobHints = []
) {
if ( $protoSlot->hasAddress() ) {
$blobAddress = $protoSlot->getAddress();
} else {
$blobAddress = $this->storeContentBlob( $protoSlot, $page, $blobHints );
}
if ( $protoSlot->hasContentId() ) {
$contentId = $protoSlot->getContentId();
} else {
$contentId = $this->insertContentRowOn( $protoSlot, $dbw, $blobAddress );
}
$this->insertSlotRowOn( $protoSlot, $dbw, $revisionId, $contentId );
return SlotRecord::newSaved(
$revisionId,
$contentId,
$blobAddress,
$protoSlot
);
}
/**
* Insert IP revision into ip_changes for use when querying for a range.
* @param IDatabase $dbw
* @param UserIdentity $user
* @param RevisionRecord $rev
* @param int $revisionId
*/
private function insertIpChangesRow(
IDatabase $dbw,
UserIdentity $user,
RevisionRecord $rev,
$revisionId
) {
if ( !$user->isRegistered() && IPUtils::isValid( $user->getName() ) ) {
$ipcRow = [
'ipc_rev_id' => $revisionId,
'ipc_rev_timestamp' => $dbw->timestamp( $rev->getTimestamp() ),
'ipc_hex' => IPUtils::toHex( $user->getName() ),
];
$dbw->insert( 'ip_changes', $ipcRow, __METHOD__ );
}
}
/**
* @param IDatabase $dbw
* @param RevisionRecord $rev
* @param int $parentId
*
* @return array a revision table row
*
* @throws MWException
* @throws MWUnknownContentModelException
*/
private function insertRevisionRowOn(
IDatabase $dbw,
RevisionRecord $rev,
$parentId
) {
$revisionRow = $this->getBaseRevisionRow( $dbw, $rev, $parentId );
$revisionRow += $this->commentStore->insert(
$dbw,
'rev_comment',
$rev->getComment( RevisionRecord::RAW )
);
[ $actorFields, $actorCallback ] =
$this->actorMigration->getInsertValuesWithTempTable(
$dbw,
'rev_user',
$rev->getUser( RevisionRecord::RAW )
);
$revisionRow += $actorFields;
$dbw->insert( 'revision', $revisionRow, __METHOD__ );
if ( !isset( $revisionRow['rev_id'] ) ) {
// only if auto-increment was used
$revisionRow['rev_id'] = intval( $dbw->insertId() );
if ( $dbw->getType() === 'mysql' ) {
// (T202032) MySQL until 8.0 and MariaDB until some version after 10.1.34 don't save the
// auto-increment value to disk, so on server restart it might reuse IDs from deleted
// revisions. We can fix that with an insert with an explicit rev_id value, if necessary.
$maxRevId = intval( $dbw->selectField( 'archive', 'MAX(ar_rev_id)', '', __METHOD__ ) );
$table = 'archive';
$maxRevId2 = intval( $dbw->selectField( 'slots', 'MAX(slot_revision_id)', '', __METHOD__ ) );
if ( $maxRevId2 >= $maxRevId ) {
$maxRevId = $maxRevId2;
$table = 'slots';
}
if ( $maxRevId >= $revisionRow['rev_id'] ) {
$this->logger->debug(
'__METHOD__: Inserted revision {revid} but {table} has revisions up to {maxrevid}.'
. ' Trying to fix it.',
[
'revid' => $revisionRow['rev_id'],
'table' => $table,
'maxrevid' => $maxRevId,
]
);
if ( !$dbw->lock( 'fix-for-T202032', __METHOD__ ) ) {
throw new MWException( 'Failed to get database lock for T202032' );
}
$fname = __METHOD__;
$dbw->onTransactionResolution(
static function ( $trigger, IDatabase $dbw ) use ( $fname ) {
$dbw->unlock( 'fix-for-T202032', $fname );
},
__METHOD__
);
$dbw->newDeleteQueryBuilder()
->delete( 'revision' )
->where( [ 'rev_id' => $revisionRow['rev_id'] ] )
->caller( __METHOD__ )->execute();
// The locking here is mostly to make MySQL bypass the REPEATABLE-READ transaction
// isolation (weird MySQL "feature"). It does seem to block concurrent auto-incrementing
// inserts too, though, at least on MariaDB 10.1.29.
//
// Don't try to lock `revision` in this way, it'll deadlock if there are concurrent
// transactions in this code path thanks to the row lock from the original ->insert() above.
//
// And we have to use raw SQL to bypass the "aggregation used with a locking SELECT" warning
// that's for non-MySQL DBs.
$row1 = $dbw->query(
$dbw->selectSQLText( 'archive', [ 'v' => "MAX(ar_rev_id)" ], '', __METHOD__ ) . ' FOR UPDATE',
__METHOD__
)->fetchObject();
$row2 = $dbw->query(
$dbw->selectSQLText( 'slots', [ 'v' => "MAX(slot_revision_id)" ], '', __METHOD__ )
. ' FOR UPDATE',
__METHOD__
)->fetchObject();
$maxRevId = max(
$maxRevId,
$row1 ? intval( $row1->v ) : 0,
$row2 ? intval( $row2->v ) : 0
);
// If we don't have SCHEMA_COMPAT_WRITE_NEW, all except the first of any concurrent
// transactions will throw a duplicate key error here. It doesn't seem worth trying
// to avoid that.
$revisionRow['rev_id'] = $maxRevId + 1;
$dbw->insert( 'revision', $revisionRow, __METHOD__ );
}
}
}
$actorCallback( $revisionRow['rev_id'], $revisionRow );
return $revisionRow;
}
/**
* @param IDatabase $dbw
* @param RevisionRecord $rev
* @param int $parentId
*
* @return array a revision table row
*/
private function getBaseRevisionRow(
IDatabase $dbw,
RevisionRecord $rev,
$parentId
) {
// Record the edit in revisions
$revisionRow = [
'rev_page' => $rev->getPageId( $this->wikiId ),
'rev_parent_id' => $parentId,
'rev_minor_edit' => $rev->isMinor() ? 1 : 0,
'rev_timestamp' => $dbw->timestamp( $rev->getTimestamp() ),
'rev_deleted' => $rev->getVisibility(),
'rev_len' => $rev->getSize(),
'rev_sha1' => $rev->getSha1(),
];
if ( $rev->getId( $this->wikiId ) !== null ) {
// Needed to restore revisions with their original ID
$revisionRow['rev_id'] = $rev->getId( $this->wikiId );
}
return $revisionRow;
}
/**
* @param SlotRecord $slot
* @param PageIdentity $page
* @param array $blobHints See the BlobStore::XXX_HINT constants
*
* @throws MWException
* @return string the blob address
*/
private function storeContentBlob(
SlotRecord $slot,
PageIdentity $page,
array $blobHints = []
) {
$content = $slot->getContent();
$format = $content->getDefaultFormat();
$model = $content->getModel();
$this->checkContent( $content, $page, $slot->getRole() );
return $this->blobStore->storeBlob(
$content->serialize( $format ),
// These hints "leak" some information from the higher abstraction layer to
// low level storage to allow for optimization.
array_merge(
$blobHints,
[
BlobStore::DESIGNATION_HINT => 'page-content',
BlobStore::ROLE_HINT => $slot->getRole(),
BlobStore::SHA1_HINT => $slot->getSha1(),
BlobStore::MODEL_HINT => $model,
BlobStore::FORMAT_HINT => $format,
]
)
);
}
/**
* @param SlotRecord $slot
* @param IDatabase $dbw
* @param int $revisionId
* @param int $contentId
*/
private function insertSlotRowOn( SlotRecord $slot, IDatabase $dbw, $revisionId, $contentId ) {
$slotRow = [
'slot_revision_id' => $revisionId,
'slot_role_id' => $this->slotRoleStore->acquireId( $slot->getRole() ),
'slot_content_id' => $contentId,
// If the slot has a specific origin use that ID, otherwise use the ID of the revision
// that we just inserted.
'slot_origin' => $slot->hasOrigin() ? $slot->getOrigin() : $revisionId,
];
$dbw->insert( 'slots', $slotRow, __METHOD__ );
}
/**
* @param SlotRecord $slot
* @param IDatabase $dbw
* @param string $blobAddress
* @return int content row ID
*/
private function insertContentRowOn( SlotRecord $slot, IDatabase $dbw, $blobAddress ) {
$contentRow = [
'content_size' => $slot->getSize(),
'content_sha1' => $slot->getSha1(),
'content_model' => $this->contentModelStore->acquireId( $slot->getModel() ),
'content_address' => $blobAddress,
];
$dbw->insert( 'content', $contentRow, __METHOD__ );
return intval( $dbw->insertId() );
}
/**
* MCR migration note: this corresponded to Revision::checkContentModel
*
* @param Content $content
* @param PageIdentity $page
* @param string $role
*
* @throws MWException
* @throws MWUnknownContentModelException
*/
private function checkContent( Content $content, PageIdentity $page, string $role ) {
// Note: may return null for revisions that have not yet been inserted
$model = $content->getModel();
$format = $content->getDefaultFormat();
$handler = $content->getContentHandler();
if ( !$handler->isSupportedFormat( $format ) ) {
throw new MWException(
"Can't use format $format with content model $model on $page role $role"
);
}
if ( !$content->isValid() ) {
throw new MWException(
"New content for $page role $role is not valid! Content model is $model"
);
}
}
/**
* Create a new null-revision for insertion into a page's
* history. This will not re-save the text, but simply refer