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
|
<?php
/**
* Class for DatabaseBlock objects to interact with the database
*
* 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
*
* @file
*/
namespace MediaWiki\Block;
use ActorMigration;
use AutoCommitUpdate;
use CommentStore;
use DeferredUpdates;
use MediaWiki\Config\ServiceOptions;
use MediaWiki\HookContainer\HookContainer;
use MediaWiki\HookContainer\HookRunner;
use MWException;
use Psr\Log\LoggerInterface;
use ReadOnlyMode;
use User;
use Wikimedia\Rdbms\IDatabase;
use Wikimedia\Rdbms\ILoadBalancer;
/**
* @since 1.36
*
* @author DannyS712
*/
class DatabaseBlockStore {
/** @var ServiceOptions */
private $options;
/**
* @internal For use by ServiceWiring
*/
public const CONSTRUCTOR_OPTIONS = [
'PutIPinRC',
'BlockDisablesLogin',
];
/** @var LoggerInterface */
private $logger;
/** @var ActorMigration */
private $actorMigration;
/** @var BlockRestrictionStore */
private $blockRestrictionStore;
/** @var CommentStore */
private $commentStore;
/** @var HookRunner */
private $hookRunner;
/** @var ILoadBalancer */
private $loadBalancer;
/** @var ReadOnlyMode */
private $readOnlyMode;
/**
* @param ServiceOptions $options
* @param LoggerInterface $logger
* @param ActorMigration $actorMigration
* @param BlockRestrictionStore $blockRestrictionStore
* @param CommentStore $commentStore
* @param HookContainer $hookContainer
* @param ILoadBalancer $loadBalancer
* @param ReadOnlyMode $readOnlyMode
*/
public function __construct(
ServiceOptions $options,
LoggerInterface $logger,
ActorMigration $actorMigration,
BlockRestrictionStore $blockRestrictionStore,
CommentStore $commentStore,
HookContainer $hookContainer,
ILoadBalancer $loadBalancer,
ReadOnlyMode $readOnlyMode
) {
$options->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
$this->options = $options;
$this->logger = $logger;
$this->actorMigration = $actorMigration;
$this->blockRestrictionStore = $blockRestrictionStore;
$this->commentStore = $commentStore;
$this->hookRunner = new HookRunner( $hookContainer );
$this->loadBalancer = $loadBalancer;
$this->readOnlyMode = $readOnlyMode;
}
/**
* Delete expired blocks from the ipblocks table
*
* @internal only public for use in DatabaseBlock
*/
public function purgeExpiredBlocks() {
if ( $this->readOnlyMode->isReadOnly() ) {
return;
}
$dbw = $this->loadBalancer->getConnectionRef( DB_MASTER );
$blockRestrictionStore = $this->blockRestrictionStore;
DeferredUpdates::addUpdate( new AutoCommitUpdate(
$dbw,
__METHOD__,
function ( IDatabase $dbw, $fname ) use ( $blockRestrictionStore ) {
$ids = $dbw->selectFieldValues(
'ipblocks',
'ipb_id',
[ 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
$fname
);
if ( $ids ) {
$blockRestrictionStore->deleteByBlockId( $ids );
$dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], $fname );
}
}
) );
}
/**
* Insert a block into the block table. Will fail if there is a conflicting
* block (same name and options) already in the database.
*
* @param DatabaseBlock $block
* @param IDatabase|null $database Database to use if not the same as the one in the load balancer
* @return bool|array False on failure, assoc array on success:
* ('id' => block ID, 'autoIds' => array of autoblock IDs)
* @throws MWException
*/
public function insertBlock(
DatabaseBlock $block,
IDatabase $database = null
) {
if ( !$block->getBlocker() || $block->getBlocker()->getName() === '' ) {
throw new MWException( 'Cannot insert a block without a blocker set' );
}
$this->logger->debug( 'Inserting block; timestamp ' . $block->getTimestamp() );
// TODO T258866 - consider passing the database
$this->purgeExpiredBlocks();
$dbw = $database ?: $this->loadBalancer->getConnectionRef( DB_MASTER );
$row = $this->getArrayForDatabaseBlock( $block, $dbw );
$dbw->insert( 'ipblocks', $row, __METHOD__, [ 'IGNORE' ] );
$affected = $dbw->affectedRows();
if ( $affected ) {
$block->setId( $dbw->insertId() );
if ( $block->getRawRestrictions() ) {
$this->blockRestrictionStore->insert( $block->getRawRestrictions() );
}
}
// Don't collide with expired blocks.
// Do this after trying to insert to avoid locking.
if ( !$affected ) {
// T96428: The ipb_address index uses a prefix on a field, so
// use a standard SELECT + DELETE to avoid annoying gap locks.
$ids = $dbw->selectFieldValues(
'ipblocks',
'ipb_id',
[
'ipb_address' => $row['ipb_address'],
'ipb_user' => $row['ipb_user'],
'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() )
],
__METHOD__
);
if ( $ids ) {
$dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], __METHOD__ );
$this->blockRestrictionStore->deleteByBlockId( $ids );
$dbw->insert( 'ipblocks', $row, __METHOD__, [ 'IGNORE' ] );
$affected = $dbw->affectedRows();
$block->setId( $dbw->insertId() );
if ( $block->getRawRestrictions() ) {
$this->blockRestrictionStore->insert( $block->getRawRestrictions() );
}
}
}
if ( $affected ) {
$autoBlockIds = $this->doRetroactiveAutoblock( $block );
if ( $this->options->get( 'BlockDisablesLogin' ) ) {
$target = $block->getTarget();
if ( $target instanceof User ) {
// Change user login token to force them to be logged out.
$target->setToken();
$target->saveSettings();
}
}
return [ 'id' => $block->getId(), 'autoIds' => $autoBlockIds ];
}
return false;
}
/**
* Update a block in the DB with new parameters.
* The ID field needs to be loaded first.
*
* @param DatabaseBlock $block
* @return bool|array False on failure, array on success:
* ('id' => block ID, 'autoIds' => array of autoblock IDs)
*/
public function updateBlock( DatabaseBlock $block ) {
$this->logger->debug( 'Updating block; timestamp ' . $block->getTimestamp() );
$dbw = $this->loadBalancer->getConnectionRef( DB_MASTER );
$row = $this->getArrayForDatabaseBlock( $block, $dbw );
$dbw->startAtomic( __METHOD__ );
$result = $dbw->update(
'ipblocks',
$row,
[ 'ipb_id' => $block->getId() ],
__METHOD__
);
// Only update the restrictions if they have been modified.
$restrictions = $block->getRawRestrictions();
if ( $restrictions !== null ) {
// An empty array should remove all of the restrictions.
if ( empty( $restrictions ) ) {
$success = $this->blockRestrictionStore->deleteByBlockId( $block->getId() );
} else {
$success = $this->blockRestrictionStore->update( $restrictions );
}
// Update the result. The first false is the result, otherwise, true.
$result = $result && $success;
}
if ( $block->isAutoblocking() ) {
// update corresponding autoblock(s) (T50813)
$dbw->update(
'ipblocks',
$this->getArrayForAutoblockUpdate( $block ),
[ 'ipb_parent_block_id' => $block->getId() ],
__METHOD__
);
// Only update the restrictions if they have been modified.
if ( $restrictions !== null ) {
$this->blockRestrictionStore->updateByParentBlockId(
$block->getId(),
$restrictions
);
}
} else {
// autoblock no longer required, delete corresponding autoblock(s)
$this->blockRestrictionStore->deleteByParentBlockId( $block->getId() );
$dbw->delete(
'ipblocks',
[ 'ipb_parent_block_id' => $block->getId() ],
__METHOD__
);
}
$dbw->endAtomic( __METHOD__ );
if ( $result ) {
$autoBlockIds = $this->doRetroactiveAutoblock( $block );
return [ 'id' => $block->getId(), 'autoIds' => $autoBlockIds ];
}
return false;
}
/**
* Delete a DatabaseBlock from the database
*
* @param DatabaseBlock $block
* @return bool whether it was deleted
* @throws MWException
*/
public function deleteBlock( DatabaseBlock $block ) : bool {
if ( $this->readOnlyMode->isReadOnly() ) {
return false;
}
$blockId = $block->getId();
if ( !$blockId ) {
throw new MWException(
__METHOD__ . " requires that a block id be set\n"
);
}
$dbw = $this->loadBalancer->getConnectionRef( DB_MASTER );
$this->blockRestrictionStore->deleteByParentBlockId( $blockId );
$dbw->delete(
'ipblocks',
[ 'ipb_parent_block_id' => $blockId ],
__METHOD__
);
$this->blockRestrictionStore->deleteByBlockId( $blockId );
$dbw->delete(
'ipblocks',
[ 'ipb_id' => $blockId ],
__METHOD__
);
return $dbw->affectedRows() > 0;
}
/**
* Get an array suitable for passing to $dbw->insert() or $dbw->update()
*
* @param DatabaseBlock $block
* @param IDatabase $dbw
* @return array
*/
private function getArrayForDatabaseBlock(
DatabaseBlock $block,
IDatabase $dbw
) : array {
$expiry = $dbw->encodeExpiry( $block->getExpiry() );
$target = $block->getTarget();
$forcedTargetId = $block->getForcedTargetId();
if ( $forcedTargetId ) {
$userId = $forcedTargetId;
} elseif ( $target instanceof User ) {
$userId = $target->getId();
} else {
$userId = 0;
}
$blockArray = [
'ipb_address' => (string)$target,
'ipb_user' => $userId,
'ipb_timestamp' => $dbw->timestamp( $block->getTimestamp() ),
'ipb_auto' => $block->getType() === AbstractBlock::TYPE_AUTO,
'ipb_anon_only' => !$block->isHardblock(),
'ipb_create_account' => $block->isCreateAccountBlocked(),
'ipb_enable_autoblock' => $block->isAutoblocking(),
'ipb_expiry' => $expiry,
'ipb_range_start' => $block->getRangeStart(),
'ipb_range_end' => $block->getRangeEnd(),
'ipb_deleted' => intval( $block->getHideName() ), // typecast required for SQLite
'ipb_block_email' => $block->isEmailBlocked(),
'ipb_allow_usertalk' => $block->isUsertalkEditAllowed(),
'ipb_parent_block_id' => $block->getParentBlockId(),
'ipb_sitewide' => $block->isSitewide(),
];
$commentArray = $this->commentStore->insert(
$dbw,
'ipb_reason',
$block->getReasonComment()
);
$actorArray = $this->actorMigration->getInsertValues(
$dbw,
'ipb_by',
$block->getBlocker()
);
$combinedArray = $blockArray + $commentArray + $actorArray;
return $combinedArray;
}
/**
* Get an array suitable for autoblock updates
*
* @param DatabaseBlock $block
* @return array
*/
private function getArrayForAutoblockUpdate( DatabaseBlock $block ) : array {
$blockArray = [
'ipb_create_account' => $block->isCreateAccountBlocked(),
'ipb_deleted' => (int)$block->getHideName(), // typecast required for SQLite
'ipb_allow_usertalk' => $block->isUsertalkEditAllowed(),
'ipb_sitewide' => $block->isSitewide(),
];
$dbw = $this->loadBalancer->getConnectionRef( DB_MASTER );
$commentArray = $this->commentStore->insert(
$dbw,
'ipb_reason',
$block->getReasonComment()
);
$actorArray = $this->actorMigration->getInsertValues(
$dbw,
'ipb_by',
$block->getBlocker()
);
$combinedArray = $blockArray + $commentArray + $actorArray;
return $combinedArray;
}
/**
* Handles retroactively autoblocking the last IP used by the user (if it is a user)
* blocked by an auto block.
*
* @param DatabaseBlock $block
* @return array IDs of retroactive autoblocks made
*/
private function doRetroactiveAutoblock( DatabaseBlock $block ) : array {
$autoBlockIds = [];
// If autoblock is enabled, autoblock the LAST IP(s) used
if ( $block->isAutoblocking() && $block->getType() == AbstractBlock::TYPE_USER ) {
$this->logger->debug(
'Doing retroactive autoblocks for ' . $block->getTarget()
);
$hookAutoBlocked = [];
$continue = $this->hookRunner->onPerformRetroactiveAutoblock(
$block,
$hookAutoBlocked
);
if ( $continue ) {
$coreAutoBlocked = $this->performRetroactiveAutoblock( $block );
$autoBlockIds = array_merge( $hookAutoBlocked, $coreAutoBlocked );
} else {
$autoBlockIds = $hookAutoBlocked;
}
}
return $autoBlockIds;
}
/**
* Actually retroactively autoblocks the last IP used by the user (if it is a user)
* blocked by this block. This will use the recentchanges table.
*
* @param DatabaseBlock $block
* @return array
*/
private function performRetroactiveAutoblock( DatabaseBlock $block ) : array {
if ( !$this->options->get( 'PutIPinRC' ) ) {
// No IPs in the recent changes table to autoblock
return [];
}
list( $target, $type ) = $block->getTargetAndType();
if ( $type !== AbstractBlock::TYPE_USER ) {
// Autoblocks only apply to users
return [];
}
$dbr = $this->loadBalancer->getConnectionRef( DB_REPLICA );
$rcQuery = $this->actorMigration->getWhere( $dbr, 'rc_user', $target, false );
$options = [
'ORDER BY' => 'rc_timestamp DESC',
'LIMIT' => 1,
];
$res = $dbr->select(
[ 'recentchanges' ] + $rcQuery['tables'],
[ 'rc_ip' ],
$rcQuery['conds'],
__METHOD__,
$options,
$rcQuery['joins']
);
if ( !$res->numRows() ) {
$this->logger->debug( 'No IP found to retroactively autoblock' );
return [];
}
$blockIds = [];
foreach ( $res as $row ) {
if ( $row->rc_ip ) {
$id = $block->doAutoblock( $row->rc_ip );
if ( $id ) {
$blockIds[] = $id;
}
}
}
return $blockIds;
}
}
|