Merge "Type hint against LinkTarget in WatchedItemStore"
[lhc/web/wiklou.git] / includes / block / DatabaseBlock.php
1 <?php
2 /**
3 * Class for blocks stored in the database.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 namespace MediaWiki\Block;
24
25 use ActorMigration;
26 use AutoCommitUpdate;
27 use BadMethodCallException;
28 use CommentStore;
29 use DeferredUpdates;
30 use Hooks;
31 use Html;
32 use IContextSource;
33 use IP;
34 use MediaWiki\Block\Restriction\NamespaceRestriction;
35 use MediaWiki\Block\Restriction\PageRestriction;
36 use MediaWiki\Block\Restriction\Restriction;
37 use MediaWiki\MediaWikiServices;
38 use MWException;
39 use RequestContext;
40 use stdClass;
41 use Title;
42 use User;
43 use WebResponse;
44 use Wikimedia\Rdbms\Database;
45 use Wikimedia\Rdbms\IDatabase;
46
47 /**
48 * A DatabaseBlock (unlike a SystemBlock) is stored in the database, may
49 * give rise to autoblocks and may be tracked with cookies. Such blocks
50 * are more customizable than system blocks: they may be hardblocks, and
51 * they may be sitewide or partial.
52 *
53 * @since 1.34 Renamed from Block.
54 */
55 class DatabaseBlock extends AbstractBlock {
56 /** @var bool */
57 public $mAuto;
58
59 /** @var int */
60 public $mParentBlockId;
61
62 /** @var int */
63 private $mId;
64
65 /** @var bool */
66 private $mFromMaster;
67
68 /** @var int Hack for foreign blocking (CentralAuth) */
69 private $forcedTargetID;
70
71 /** @var bool */
72 private $isHardblock;
73
74 /** @var bool */
75 private $isAutoblocking;
76
77 /** @var Restriction[] */
78 private $restrictions;
79
80 /**
81 * Create a new block with specified option parameters on a user, IP or IP range.
82 *
83 * @param array $options Parameters of the block:
84 * user int Override target user ID (for foreign users)
85 * auto bool Is this an automatic block?
86 * expiry string Timestamp of expiration of the block or 'infinity'
87 * anonOnly bool Only disallow anonymous actions
88 * createAccount bool Disallow creation of new accounts
89 * enableAutoblock bool Enable automatic blocking
90 * hideName bool Hide the target user name
91 * blockEmail bool Disallow sending emails
92 * allowUsertalk bool Allow the target to edit its own talk page
93 * sitewide bool Disallow editing all pages and all contribution
94 * actions, except those specifically allowed by
95 * other block flags
96 *
97 * @since 1.26 $options array
98 */
99 public function __construct( array $options = [] ) {
100 parent::__construct( $options );
101
102 $defaults = [
103 'user' => null,
104 'auto' => false,
105 'expiry' => '',
106 'anonOnly' => false,
107 'createAccount' => false,
108 'enableAutoblock' => false,
109 'hideName' => false,
110 'blockEmail' => false,
111 'allowUsertalk' => false,
112 'sitewide' => true,
113 ];
114
115 $options += $defaults;
116
117 if ( $this->target instanceof User && $options['user'] ) {
118 # Needed for foreign users
119 $this->forcedTargetID = $options['user'];
120 }
121
122 $this->setExpiry( wfGetDB( DB_REPLICA )->decodeExpiry( $options['expiry'] ) );
123
124 # Boolean settings
125 $this->mAuto = (bool)$options['auto'];
126 $this->setHideName( (bool)$options['hideName'] );
127 $this->isHardblock( !$options['anonOnly'] );
128 $this->isAutoblocking( (bool)$options['enableAutoblock'] );
129 $this->isSitewide( (bool)$options['sitewide'] );
130 $this->isEmailBlocked( (bool)$options['blockEmail'] );
131 $this->isCreateAccountBlocked( (bool)$options['createAccount'] );
132 $this->isUsertalkEditAllowed( (bool)$options['allowUsertalk'] );
133
134 $this->mFromMaster = false;
135 }
136
137 /**
138 * Load a block from the block id.
139 *
140 * @param int $id id to search for
141 * @return DatabaseBlock|null
142 */
143 public static function newFromID( $id ) {
144 $dbr = wfGetDB( DB_REPLICA );
145 $blockQuery = self::getQueryInfo();
146 $res = $dbr->selectRow(
147 $blockQuery['tables'],
148 $blockQuery['fields'],
149 [ 'ipb_id' => $id ],
150 __METHOD__,
151 [],
152 $blockQuery['joins']
153 );
154 if ( $res ) {
155 return self::newFromRow( $res );
156 } else {
157 return null;
158 }
159 }
160
161 /**
162 * Return the list of ipblocks fields that should be selected to create
163 * a new block.
164 * @deprecated since 1.31, use self::getQueryInfo() instead.
165 * @return array
166 */
167 public static function selectFields() {
168 global $wgActorTableSchemaMigrationStage;
169
170 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW ) {
171 // If code is using this instead of self::getQueryInfo(), there's a
172 // decent chance it's going to try to directly access
173 // $row->ipb_by or $row->ipb_by_text and we can't give it
174 // useful values here once those aren't being used anymore.
175 throw new BadMethodCallException(
176 'Cannot use ' . __METHOD__
177 . ' when $wgActorTableSchemaMigrationStage has SCHEMA_COMPAT_READ_NEW'
178 );
179 }
180
181 wfDeprecated( __METHOD__, '1.31' );
182 return [
183 'ipb_id',
184 'ipb_address',
185 'ipb_by',
186 'ipb_by_text',
187 'ipb_by_actor' => 'NULL',
188 'ipb_timestamp',
189 'ipb_auto',
190 'ipb_anon_only',
191 'ipb_create_account',
192 'ipb_enable_autoblock',
193 'ipb_expiry',
194 'ipb_deleted',
195 'ipb_block_email',
196 'ipb_allow_usertalk',
197 'ipb_parent_block_id',
198 'ipb_sitewide',
199 ] + CommentStore::getStore()->getFields( 'ipb_reason' );
200 }
201
202 /**
203 * Return the tables, fields, and join conditions to be selected to create
204 * a new block object.
205 * @since 1.31
206 * @return array With three keys:
207 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
208 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
209 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
210 */
211 public static function getQueryInfo() {
212 $commentQuery = CommentStore::getStore()->getJoin( 'ipb_reason' );
213 $actorQuery = ActorMigration::newMigration()->getJoin( 'ipb_by' );
214 return [
215 'tables' => [ 'ipblocks' ] + $commentQuery['tables'] + $actorQuery['tables'],
216 'fields' => [
217 'ipb_id',
218 'ipb_address',
219 'ipb_timestamp',
220 'ipb_auto',
221 'ipb_anon_only',
222 'ipb_create_account',
223 'ipb_enable_autoblock',
224 'ipb_expiry',
225 'ipb_deleted',
226 'ipb_block_email',
227 'ipb_allow_usertalk',
228 'ipb_parent_block_id',
229 'ipb_sitewide',
230 ] + $commentQuery['fields'] + $actorQuery['fields'],
231 'joins' => $commentQuery['joins'] + $actorQuery['joins'],
232 ];
233 }
234
235 /**
236 * Check if two blocks are effectively equal. Doesn't check irrelevant things like
237 * the blocking user or the block timestamp, only things which affect the blocked user
238 *
239 * @param DatabaseBlock $block
240 * @return bool
241 */
242 public function equals( DatabaseBlock $block ) {
243 return (
244 (string)$this->target == (string)$block->target
245 && $this->type == $block->type
246 && $this->mAuto == $block->mAuto
247 && $this->isHardblock() == $block->isHardblock()
248 && $this->isCreateAccountBlocked() == $block->isCreateAccountBlocked()
249 && $this->getExpiry() == $block->getExpiry()
250 && $this->isAutoblocking() == $block->isAutoblocking()
251 && $this->getHideName() == $block->getHideName()
252 && $this->isEmailBlocked() == $block->isEmailBlocked()
253 && $this->isUsertalkEditAllowed() == $block->isUsertalkEditAllowed()
254 && $this->getReason() == $block->getReason()
255 && $this->isSitewide() == $block->isSitewide()
256 // DatabaseBlock::getRestrictions() may perform a database query, so
257 // keep it at the end.
258 && $this->getBlockRestrictionStore()->equals(
259 $this->getRestrictions(), $block->getRestrictions()
260 )
261 );
262 }
263
264 /**
265 * Load blocks from the database which target the specific target exactly, or which cover the
266 * vague target.
267 *
268 * @param User|string|null $specificTarget
269 * @param int|null $specificType
270 * @param bool $fromMaster
271 * @param User|string|null $vagueTarget Also search for blocks affecting this target. Doesn't
272 * make any sense to use TYPE_AUTO / TYPE_ID here. Leave blank to skip IP lookups.
273 * @throws MWException
274 * @return DatabaseBlock[] Any relevant blocks
275 */
276 protected static function newLoad(
277 $specificTarget,
278 $specificType,
279 $fromMaster,
280 $vagueTarget = null
281 ) {
282 $db = wfGetDB( $fromMaster ? DB_MASTER : DB_REPLICA );
283
284 if ( $specificType !== null ) {
285 $conds = [
286 'ipb_address' => [ (string)$specificTarget ],
287 ];
288 } else {
289 $conds = [ 'ipb_address' => [] ];
290 }
291
292 # Be aware that the != '' check is explicit, since empty values will be
293 # passed by some callers (T31116)
294 if ( $vagueTarget != '' ) {
295 list( $target, $type ) = self::parseTarget( $vagueTarget );
296 switch ( $type ) {
297 case self::TYPE_USER:
298 # Slightly weird, but who are we to argue?
299 $conds['ipb_address'][] = (string)$target;
300 break;
301
302 case self::TYPE_IP:
303 $conds['ipb_address'][] = (string)$target;
304 $conds[] = self::getRangeCond( IP::toHex( $target ) );
305 $conds = $db->makeList( $conds, LIST_OR );
306 break;
307
308 case self::TYPE_RANGE:
309 list( $start, $end ) = IP::parseRange( $target );
310 $conds['ipb_address'][] = (string)$target;
311 $conds[] = self::getRangeCond( $start, $end );
312 $conds = $db->makeList( $conds, LIST_OR );
313 break;
314
315 default:
316 throw new MWException( "Tried to load block with invalid type" );
317 }
318 }
319
320 $blockQuery = self::getQueryInfo();
321 $res = $db->select(
322 $blockQuery['tables'], $blockQuery['fields'], $conds, __METHOD__, [], $blockQuery['joins']
323 );
324
325 $blocks = [];
326 $blockIds = [];
327 $autoBlocks = [];
328 foreach ( $res as $row ) {
329 $block = self::newFromRow( $row );
330
331 # Don't use expired blocks
332 if ( $block->isExpired() ) {
333 continue;
334 }
335
336 # Don't use anon only blocks on users
337 if ( $specificType == self::TYPE_USER && !$block->isHardblock() ) {
338 continue;
339 }
340
341 // Check for duplicate autoblocks
342 if ( $block->getType() === self::TYPE_AUTO ) {
343 $autoBlocks[] = $block;
344 } else {
345 $blocks[] = $block;
346 $blockIds[] = $block->getId();
347 }
348 }
349
350 // Only add autoblocks that aren't duplicates
351 foreach ( $autoBlocks as $block ) {
352 if ( !in_array( $block->mParentBlockId, $blockIds ) ) {
353 $blocks[] = $block;
354 }
355 }
356
357 return $blocks;
358 }
359
360 /**
361 * Choose the most specific block from some combination of user, IP and IP range
362 * blocks. Decreasing order of specificity: user > IP > narrower IP range > wider IP
363 * range. A range that encompasses one IP address is ranked equally to a singe IP.
364 *
365 * Note that DatabaseBlock::chooseBlocks chooses blocks in a different way.
366 *
367 * This is refactored out from DatabaseBlock::newLoad.
368 *
369 * @param DatabaseBlock[] $blocks These should not include autoblocks or ID blocks
370 * @return DatabaseBlock|null The block with the most specific target
371 */
372 protected static function chooseMostSpecificBlock( array $blocks ) {
373 if ( count( $blocks ) === 1 ) {
374 return $blocks[0];
375 }
376
377 # This result could contain a block on the user, a block on the IP, and a russian-doll
378 # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
379 $bestBlock = null;
380
381 # Lower will be better
382 $bestBlockScore = 100;
383 foreach ( $blocks as $block ) {
384 if ( $block->getType() == self::TYPE_RANGE ) {
385 # This is the number of bits that are allowed to vary in the block, give
386 # or take some floating point errors
387 $target = $block->getTarget();
388 $max = IP::isIPv6( $target ) ? 128 : 32;
389 list( $network, $bits ) = IP::parseCIDR( $target );
390 $size = $max - $bits;
391
392 # Rank a range block covering a single IP equally with a single-IP block
393 $score = self::TYPE_RANGE - 1 + ( $size / $max );
394
395 } else {
396 $score = $block->getType();
397 }
398
399 if ( $score < $bestBlockScore ) {
400 $bestBlockScore = $score;
401 $bestBlock = $block;
402 }
403 }
404
405 return $bestBlock;
406 }
407
408 /**
409 * Get a set of SQL conditions which will select rangeblocks encompassing a given range
410 * @param string $start Hexadecimal IP representation
411 * @param string|null $end Hexadecimal IP representation, or null to use $start = $end
412 * @return string
413 */
414 public static function getRangeCond( $start, $end = null ) {
415 if ( $end === null ) {
416 $end = $start;
417 }
418 # Per T16634, we want to include relevant active rangeblocks; for
419 # rangeblocks, we want to include larger ranges which enclose the given
420 # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
421 # so we can improve performance by filtering on a LIKE clause
422 $chunk = self::getIpFragment( $start );
423 $dbr = wfGetDB( DB_REPLICA );
424 $like = $dbr->buildLike( $chunk, $dbr->anyString() );
425
426 # Fairly hard to make a malicious SQL statement out of hex characters,
427 # but stranger things have happened...
428 $safeStart = $dbr->addQuotes( $start );
429 $safeEnd = $dbr->addQuotes( $end );
430
431 return $dbr->makeList(
432 [
433 "ipb_range_start $like",
434 "ipb_range_start <= $safeStart",
435 "ipb_range_end >= $safeEnd",
436 ],
437 LIST_AND
438 );
439 }
440
441 /**
442 * Get the component of an IP address which is certain to be the same between an IP
443 * address and a rangeblock containing that IP address.
444 * @param string $hex Hexadecimal IP representation
445 * @return string
446 */
447 protected static function getIpFragment( $hex ) {
448 global $wgBlockCIDRLimit;
449 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
450 return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
451 } else {
452 return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
453 }
454 }
455
456 /**
457 * Given a database row from the ipblocks table, initialize
458 * member variables
459 * @param stdClass $row A row from the ipblocks table
460 */
461 protected function initFromRow( $row ) {
462 $this->setTarget( $row->ipb_address );
463 $this->setBlocker( User::newFromAnyId(
464 $row->ipb_by, $row->ipb_by_text, $row->ipb_by_actor ?? null
465 ) );
466
467 $this->setTimestamp( wfTimestamp( TS_MW, $row->ipb_timestamp ) );
468 $this->mAuto = $row->ipb_auto;
469 $this->setHideName( $row->ipb_deleted );
470 $this->mId = (int)$row->ipb_id;
471 $this->mParentBlockId = $row->ipb_parent_block_id;
472
473 // I wish I didn't have to do this
474 $db = wfGetDB( DB_REPLICA );
475 $this->setExpiry( $db->decodeExpiry( $row->ipb_expiry ) );
476 $this->setReason(
477 CommentStore::getStore()
478 // Legacy because $row may have come from self::selectFields()
479 ->getCommentLegacy( $db, 'ipb_reason', $row )->text
480 );
481
482 $this->isHardblock( !$row->ipb_anon_only );
483 $this->isAutoblocking( $row->ipb_enable_autoblock );
484 $this->isSitewide( (bool)$row->ipb_sitewide );
485
486 $this->isCreateAccountBlocked( $row->ipb_create_account );
487 $this->isEmailBlocked( $row->ipb_block_email );
488 $this->isUsertalkEditAllowed( $row->ipb_allow_usertalk );
489 }
490
491 /**
492 * Create a new DatabaseBlock object from a database row
493 * @param stdClass $row Row from the ipblocks table
494 * @return DatabaseBlock
495 */
496 public static function newFromRow( $row ) {
497 $block = new DatabaseBlock;
498 $block->initFromRow( $row );
499 return $block;
500 }
501
502 /**
503 * Delete the row from the IP blocks table.
504 *
505 * @throws MWException
506 * @return bool
507 */
508 public function delete() {
509 if ( wfReadOnly() ) {
510 return false;
511 }
512
513 if ( !$this->getId() ) {
514 throw new MWException(
515 __METHOD__ . " requires that the mId member be filled\n"
516 );
517 }
518
519 $dbw = wfGetDB( DB_MASTER );
520
521 $this->getBlockRestrictionStore()->deleteByParentBlockId( $this->getId() );
522 $dbw->delete( 'ipblocks', [ 'ipb_parent_block_id' => $this->getId() ], __METHOD__ );
523
524 $this->getBlockRestrictionStore()->deleteByBlockId( $this->getId() );
525 $dbw->delete( 'ipblocks', [ 'ipb_id' => $this->getId() ], __METHOD__ );
526
527 return $dbw->affectedRows() > 0;
528 }
529
530 /**
531 * Insert a block into the block table. Will fail if there is a conflicting
532 * block (same name and options) already in the database.
533 *
534 * @param IDatabase|null $dbw If you have one available
535 * @return bool|array False on failure, assoc array on success:
536 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
537 */
538 public function insert( IDatabase $dbw = null ) {
539 global $wgBlockDisablesLogin;
540
541 if ( !$this->getBlocker() || $this->getBlocker()->getName() === '' ) {
542 throw new MWException( 'Cannot insert a block without a blocker set' );
543 }
544
545 wfDebug( __METHOD__ . "; timestamp {$this->mTimestamp}\n" );
546
547 if ( $dbw === null ) {
548 $dbw = wfGetDB( DB_MASTER );
549 }
550
551 self::purgeExpired();
552
553 $row = $this->getDatabaseArray( $dbw );
554
555 $dbw->insert( 'ipblocks', $row, __METHOD__, [ 'IGNORE' ] );
556 $affected = $dbw->affectedRows();
557 if ( $affected ) {
558 $this->setId( $dbw->insertId() );
559 if ( $this->restrictions ) {
560 $this->getBlockRestrictionStore()->insert( $this->restrictions );
561 }
562 }
563
564 # Don't collide with expired blocks.
565 # Do this after trying to insert to avoid locking.
566 if ( !$affected ) {
567 # T96428: The ipb_address index uses a prefix on a field, so
568 # use a standard SELECT + DELETE to avoid annoying gap locks.
569 $ids = $dbw->selectFieldValues( 'ipblocks',
570 'ipb_id',
571 [
572 'ipb_address' => $row['ipb_address'],
573 'ipb_user' => $row['ipb_user'],
574 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() )
575 ],
576 __METHOD__
577 );
578 if ( $ids ) {
579 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], __METHOD__ );
580 $this->getBlockRestrictionStore()->deleteByBlockId( $ids );
581 $dbw->insert( 'ipblocks', $row, __METHOD__, [ 'IGNORE' ] );
582 $affected = $dbw->affectedRows();
583 $this->setId( $dbw->insertId() );
584 if ( $this->restrictions ) {
585 $this->getBlockRestrictionStore()->insert( $this->restrictions );
586 }
587 }
588 }
589
590 if ( $affected ) {
591 $auto_ipd_ids = $this->doRetroactiveAutoblock();
592
593 if ( $wgBlockDisablesLogin && $this->target instanceof User ) {
594 // Change user login token to force them to be logged out.
595 $this->target->setToken();
596 $this->target->saveSettings();
597 }
598
599 return [ 'id' => $this->mId, 'autoIds' => $auto_ipd_ids ];
600 }
601
602 return false;
603 }
604
605 /**
606 * Update a block in the DB with new parameters.
607 * The ID field needs to be loaded first.
608 *
609 * @return bool|array False on failure, array on success:
610 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
611 */
612 public function update() {
613 wfDebug( __METHOD__ . "; timestamp {$this->mTimestamp}\n" );
614 $dbw = wfGetDB( DB_MASTER );
615
616 $dbw->startAtomic( __METHOD__ );
617
618 $result = $dbw->update(
619 'ipblocks',
620 $this->getDatabaseArray( $dbw ),
621 [ 'ipb_id' => $this->getId() ],
622 __METHOD__
623 );
624
625 // Only update the restrictions if they have been modified.
626 if ( $this->restrictions !== null ) {
627 // An empty array should remove all of the restrictions.
628 if ( empty( $this->restrictions ) ) {
629 $success = $this->getBlockRestrictionStore()->deleteByBlockId( $this->getId() );
630 } else {
631 $success = $this->getBlockRestrictionStore()->update( $this->restrictions );
632 }
633 // Update the result. The first false is the result, otherwise, true.
634 $result = $result && $success;
635 }
636
637 if ( $this->isAutoblocking() ) {
638 // update corresponding autoblock(s) (T50813)
639 $dbw->update(
640 'ipblocks',
641 $this->getAutoblockUpdateArray( $dbw ),
642 [ 'ipb_parent_block_id' => $this->getId() ],
643 __METHOD__
644 );
645
646 // Only update the restrictions if they have been modified.
647 if ( $this->restrictions !== null ) {
648 $this->getBlockRestrictionStore()->updateByParentBlockId( $this->getId(), $this->restrictions );
649 }
650 } else {
651 // autoblock no longer required, delete corresponding autoblock(s)
652 $this->getBlockRestrictionStore()->deleteByParentBlockId( $this->getId() );
653 $dbw->delete(
654 'ipblocks',
655 [ 'ipb_parent_block_id' => $this->getId() ],
656 __METHOD__
657 );
658 }
659
660 $dbw->endAtomic( __METHOD__ );
661
662 if ( $result ) {
663 $auto_ipd_ids = $this->doRetroactiveAutoblock();
664 return [ 'id' => $this->mId, 'autoIds' => $auto_ipd_ids ];
665 }
666
667 return $result;
668 }
669
670 /**
671 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
672 * @param IDatabase $dbw
673 * @return array
674 */
675 protected function getDatabaseArray( IDatabase $dbw ) {
676 $expiry = $dbw->encodeExpiry( $this->getExpiry() );
677
678 if ( $this->forcedTargetID ) {
679 $uid = $this->forcedTargetID;
680 } else {
681 $uid = $this->target instanceof User ? $this->target->getId() : 0;
682 }
683
684 $a = [
685 'ipb_address' => (string)$this->target,
686 'ipb_user' => $uid,
687 'ipb_timestamp' => $dbw->timestamp( $this->getTimestamp() ),
688 'ipb_auto' => $this->mAuto,
689 'ipb_anon_only' => !$this->isHardblock(),
690 'ipb_create_account' => $this->isCreateAccountBlocked(),
691 'ipb_enable_autoblock' => $this->isAutoblocking(),
692 'ipb_expiry' => $expiry,
693 'ipb_range_start' => $this->getRangeStart(),
694 'ipb_range_end' => $this->getRangeEnd(),
695 'ipb_deleted' => intval( $this->getHideName() ), // typecast required for SQLite
696 'ipb_block_email' => $this->isEmailBlocked(),
697 'ipb_allow_usertalk' => $this->isUsertalkEditAllowed(),
698 'ipb_parent_block_id' => $this->mParentBlockId,
699 'ipb_sitewide' => $this->isSitewide(),
700 ] + CommentStore::getStore()->insert( $dbw, 'ipb_reason', $this->getReason() )
701 + ActorMigration::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
702
703 return $a;
704 }
705
706 /**
707 * @param IDatabase $dbw
708 * @return array
709 */
710 protected function getAutoblockUpdateArray( IDatabase $dbw ) {
711 return [
712 'ipb_create_account' => $this->isCreateAccountBlocked(),
713 'ipb_deleted' => (int)$this->getHideName(), // typecast required for SQLite
714 'ipb_allow_usertalk' => $this->isUsertalkEditAllowed(),
715 'ipb_sitewide' => $this->isSitewide(),
716 ] + CommentStore::getStore()->insert( $dbw, 'ipb_reason', $this->getReason() )
717 + ActorMigration::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
718 }
719
720 /**
721 * Retroactively autoblocks the last IP used by the user (if it is a user)
722 * blocked by this block.
723 *
724 * @return array IDs of retroactive autoblocks made
725 */
726 protected function doRetroactiveAutoblock() {
727 $blockIds = [];
728 # If autoblock is enabled, autoblock the LAST IP(s) used
729 if ( $this->isAutoblocking() && $this->getType() == self::TYPE_USER ) {
730 wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
731
732 $continue = Hooks::run(
733 'PerformRetroactiveAutoblock', [ $this, &$blockIds ] );
734
735 if ( $continue ) {
736 self::defaultRetroactiveAutoblock( $this, $blockIds );
737 }
738 }
739 return $blockIds;
740 }
741
742 /**
743 * Retroactively autoblocks the last IP used by the user (if it is a user)
744 * blocked by this block. This will use the recentchanges table.
745 *
746 * @param DatabaseBlock $block
747 * @param array &$blockIds
748 */
749 protected static function defaultRetroactiveAutoblock( DatabaseBlock $block, array &$blockIds ) {
750 global $wgPutIPinRC;
751
752 // No IPs are in recentchanges table, so nothing to select
753 if ( !$wgPutIPinRC ) {
754 return;
755 }
756
757 // Autoblocks only apply to TYPE_USER
758 if ( $block->getType() !== self::TYPE_USER ) {
759 return;
760 }
761 $target = $block->getTarget(); // TYPE_USER => always a User object
762
763 $dbr = wfGetDB( DB_REPLICA );
764 $rcQuery = ActorMigration::newMigration()->getWhere( $dbr, 'rc_user', $target, false );
765
766 $options = [ 'ORDER BY' => 'rc_timestamp DESC' ];
767
768 // Just the last IP used.
769 $options['LIMIT'] = 1;
770
771 $res = $dbr->select(
772 [ 'recentchanges' ] + $rcQuery['tables'],
773 [ 'rc_ip' ],
774 $rcQuery['conds'],
775 __METHOD__,
776 $options,
777 $rcQuery['joins']
778 );
779
780 if ( !$res->numRows() ) {
781 # No results, don't autoblock anything
782 wfDebug( "No IP found to retroactively autoblock\n" );
783 } else {
784 foreach ( $res as $row ) {
785 if ( $row->rc_ip ) {
786 $id = $block->doAutoblock( $row->rc_ip );
787 if ( $id ) {
788 $blockIds[] = $id;
789 }
790 }
791 }
792 }
793 }
794
795 /**
796 * Checks whether a given IP is on the autoblock whitelist.
797 * TODO: this probably belongs somewhere else, but not sure where...
798 *
799 * @param string $ip The IP to check
800 * @return bool
801 */
802 public static function isWhitelistedFromAutoblocks( $ip ) {
803 // Try to get the autoblock_whitelist from the cache, as it's faster
804 // than getting the msg raw and explode()'ing it.
805 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
806 $lines = $cache->getWithSetCallback(
807 $cache->makeKey( 'ip-autoblock', 'whitelist' ),
808 $cache::TTL_DAY,
809 function ( $curValue, &$ttl, array &$setOpts ) {
810 $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
811
812 return explode( "\n",
813 wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
814 }
815 );
816
817 wfDebug( "Checking the autoblock whitelist..\n" );
818
819 foreach ( $lines as $line ) {
820 # List items only
821 if ( substr( $line, 0, 1 ) !== '*' ) {
822 continue;
823 }
824
825 $wlEntry = substr( $line, 1 );
826 $wlEntry = trim( $wlEntry );
827
828 wfDebug( "Checking $ip against $wlEntry..." );
829
830 # Is the IP in this range?
831 if ( IP::isInRange( $ip, $wlEntry ) ) {
832 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
833 return true;
834 } else {
835 wfDebug( " No match\n" );
836 }
837 }
838
839 return false;
840 }
841
842 /**
843 * Autoblocks the given IP, referring to this block.
844 *
845 * @param string $autoblockIP The IP to autoblock.
846 * @return int|bool ID if an autoblock was inserted, false if not.
847 */
848 public function doAutoblock( $autoblockIP ) {
849 # If autoblocks are disabled, go away.
850 if ( !$this->isAutoblocking() ) {
851 return false;
852 }
853
854 # Check for presence on the autoblock whitelist.
855 if ( self::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
856 return false;
857 }
858
859 // Avoid PHP 7.1 warning of passing $this by reference
860 $block = $this;
861 # Allow hooks to cancel the autoblock.
862 if ( !Hooks::run( 'AbortAutoblock', [ $autoblockIP, &$block ] ) ) {
863 wfDebug( "Autoblock aborted by hook.\n" );
864 return false;
865 }
866
867 # It's okay to autoblock. Go ahead and insert/update the block...
868
869 # Do not add a *new* block if the IP is already blocked.
870 $ipblock = self::newFromTarget( $autoblockIP );
871 if ( $ipblock ) {
872 # Check if the block is an autoblock and would exceed the user block
873 # if renewed. If so, do nothing, otherwise prolong the block time...
874 if ( $ipblock->mAuto && // @todo Why not compare $ipblock->mExpiry?
875 $this->getExpiry() > self::getAutoblockExpiry( $ipblock->getTimestamp() )
876 ) {
877 # Reset block timestamp to now and its expiry to
878 # $wgAutoblockExpiry in the future
879 $ipblock->updateTimestamp();
880 }
881 return false;
882 }
883
884 # Make a new block object with the desired properties.
885 $autoblock = new DatabaseBlock;
886 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
887 $autoblock->setTarget( $autoblockIP );
888 $autoblock->setBlocker( $this->getBlocker() );
889 $autoblock->setReason(
890 wfMessage( 'autoblocker', $this->getTarget(), $this->getReason() )
891 ->inContentLanguage()->plain()
892 );
893 $timestamp = wfTimestampNow();
894 $autoblock->setTimestamp( $timestamp );
895 $autoblock->mAuto = 1;
896 $autoblock->isCreateAccountBlocked( $this->isCreateAccountBlocked() );
897 # Continue suppressing the name if needed
898 $autoblock->setHideName( $this->getHideName() );
899 $autoblock->isUsertalkEditAllowed( $this->isUsertalkEditAllowed() );
900 $autoblock->mParentBlockId = $this->mId;
901 $autoblock->isSitewide( $this->isSitewide() );
902 $autoblock->setRestrictions( $this->getRestrictions() );
903
904 if ( $this->getExpiry() == 'infinity' ) {
905 # Original block was indefinite, start an autoblock now
906 $autoblock->setExpiry( self::getAutoblockExpiry( $timestamp ) );
907 } else {
908 # If the user is already blocked with an expiry date, we don't
909 # want to pile on top of that.
910 $autoblock->setExpiry( min( $this->getExpiry(), self::getAutoblockExpiry( $timestamp ) ) );
911 }
912
913 # Insert the block...
914 $status = $autoblock->insert();
915 return $status
916 ? $status['id']
917 : false;
918 }
919
920 /**
921 * Check if a block has expired. Delete it if it is.
922 * @return bool
923 */
924 public function deleteIfExpired() {
925 if ( $this->isExpired() ) {
926 wfDebug( __METHOD__ . " -- deleting\n" );
927 $this->delete();
928 $retVal = true;
929 } else {
930 wfDebug( __METHOD__ . " -- not expired\n" );
931 $retVal = false;
932 }
933
934 return $retVal;
935 }
936
937 /**
938 * Has the block expired?
939 * @return bool
940 */
941 public function isExpired() {
942 $timestamp = wfTimestampNow();
943 wfDebug( __METHOD__ . " checking current " . $timestamp . " vs $this->mExpiry\n" );
944
945 if ( !$this->getExpiry() ) {
946 return false;
947 } else {
948 return $timestamp > $this->getExpiry();
949 }
950 }
951
952 /**
953 * Is the block address valid (i.e. not a null string?)
954 *
955 * @deprecated since 1.33 No longer needed in core.
956 * @return bool
957 */
958 public function isValid() {
959 wfDeprecated( __METHOD__, '1.33' );
960 return $this->getTarget() != null;
961 }
962
963 /**
964 * Update the timestamp on autoblocks.
965 */
966 public function updateTimestamp() {
967 if ( $this->mAuto ) {
968 $this->setTimestamp( wfTimestamp() );
969 $this->setExpiry( self::getAutoblockExpiry( $this->getTimestamp() ) );
970
971 $dbw = wfGetDB( DB_MASTER );
972 $dbw->update( 'ipblocks',
973 [ /* SET */
974 'ipb_timestamp' => $dbw->timestamp( $this->getTimestamp() ),
975 'ipb_expiry' => $dbw->timestamp( $this->getExpiry() ),
976 ],
977 [ /* WHERE */
978 'ipb_id' => $this->getId(),
979 ],
980 __METHOD__
981 );
982 }
983 }
984
985 /**
986 * Get the IP address at the start of the range in Hex form
987 * @throws MWException
988 * @return string IP in Hex form
989 */
990 public function getRangeStart() {
991 switch ( $this->type ) {
992 case self::TYPE_USER:
993 return '';
994 case self::TYPE_IP:
995 return IP::toHex( $this->target );
996 case self::TYPE_RANGE:
997 list( $start, /*...*/ ) = IP::parseRange( $this->target );
998 return $start;
999 default:
1000 throw new MWException( "Block with invalid type" );
1001 }
1002 }
1003
1004 /**
1005 * Get the IP address at the end of the range in Hex form
1006 * @throws MWException
1007 * @return string IP in Hex form
1008 */
1009 public function getRangeEnd() {
1010 switch ( $this->type ) {
1011 case self::TYPE_USER:
1012 return '';
1013 case self::TYPE_IP:
1014 return IP::toHex( $this->target );
1015 case self::TYPE_RANGE:
1016 list( /*...*/, $end ) = IP::parseRange( $this->target );
1017 return $end;
1018 default:
1019 throw new MWException( "Block with invalid type" );
1020 }
1021 }
1022
1023 /**
1024 * @inheritDoc
1025 */
1026 public function getId() {
1027 return $this->mId;
1028 }
1029
1030 /**
1031 * Set the block ID
1032 *
1033 * @param int $blockId
1034 * @return self
1035 */
1036 private function setId( $blockId ) {
1037 $this->mId = (int)$blockId;
1038
1039 if ( is_array( $this->restrictions ) ) {
1040 $this->restrictions = $this->getBlockRestrictionStore()->setBlockId(
1041 $blockId, $this->restrictions
1042 );
1043 }
1044
1045 return $this;
1046 }
1047
1048 /**
1049 * @since 1.34
1050 * @return int|null If this is an autoblock, ID of the parent block; otherwise null
1051 */
1052 public function getParentBlockId() {
1053 return $this->mParentBlockId;
1054 }
1055
1056 /**
1057 * Get/set a flag determining whether the master is used for reads
1058 *
1059 * @param bool|null $x
1060 * @return bool
1061 */
1062 public function fromMaster( $x = null ) {
1063 return wfSetVar( $this->mFromMaster, $x );
1064 }
1065
1066 /**
1067 * Get/set whether the block is a hardblock (affects logged-in users on a given IP/range)
1068 * @param bool|null $x
1069 * @return bool
1070 */
1071 public function isHardblock( $x = null ) {
1072 wfSetVar( $this->isHardblock, $x );
1073
1074 # You can't *not* hardblock a user
1075 return $this->getType() == self::TYPE_USER
1076 ? true
1077 : $this->isHardblock;
1078 }
1079
1080 /**
1081 * @param null|bool $x
1082 * @return bool
1083 */
1084 public function isAutoblocking( $x = null ) {
1085 wfSetVar( $this->isAutoblocking, $x );
1086
1087 # You can't put an autoblock on an IP or range as we don't have any history to
1088 # look over to get more IPs from
1089 return $this->getType() == self::TYPE_USER
1090 ? $this->isAutoblocking
1091 : false;
1092 }
1093
1094 /**
1095 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
1096 * @return string Text is escaped
1097 */
1098 public function getRedactedName() {
1099 if ( $this->mAuto ) {
1100 return Html::element(
1101 'span',
1102 [ 'class' => 'mw-autoblockid' ],
1103 wfMessage( 'autoblockid', $this->mId )->text()
1104 );
1105 } else {
1106 return htmlspecialchars( $this->getTarget() );
1107 }
1108 }
1109
1110 /**
1111 * Get a timestamp of the expiry for autoblocks
1112 *
1113 * @param string|int $timestamp
1114 * @return string
1115 */
1116 public static function getAutoblockExpiry( $timestamp ) {
1117 global $wgAutoblockExpiry;
1118
1119 return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry );
1120 }
1121
1122 /**
1123 * Purge expired blocks from the ipblocks table
1124 */
1125 public static function purgeExpired() {
1126 if ( wfReadOnly() ) {
1127 return;
1128 }
1129
1130 DeferredUpdates::addUpdate( new AutoCommitUpdate(
1131 wfGetDB( DB_MASTER ),
1132 __METHOD__,
1133 function ( IDatabase $dbw, $fname ) {
1134 $ids = $dbw->selectFieldValues( 'ipblocks',
1135 'ipb_id',
1136 [ 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
1137 $fname
1138 );
1139 if ( $ids ) {
1140 $blockRestrictionStore = MediaWikiServices::getInstance()->getBlockRestrictionStore();
1141 $blockRestrictionStore->deleteByBlockId( $ids );
1142
1143 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], $fname );
1144 }
1145 }
1146 ) );
1147 }
1148
1149 /**
1150 * Given a target and the target's type, get an existing block object if possible.
1151 * @param string|User|int $specificTarget A block target, which may be one of several types:
1152 * * A user to block, in which case $target will be a User
1153 * * An IP to block, in which case $target will be a User generated by using
1154 * User::newFromName( $ip, false ) to turn off name validation
1155 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
1156 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
1157 * usernames
1158 * Calling this with a user, IP address or range will not select autoblocks, and will
1159 * only select a block where the targets match exactly (so looking for blocks on
1160 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
1161 * @param string|User|int|null $vagueTarget As above, but we will search for *any* block which
1162 * affects that target (so for an IP address, get ranges containing that IP; and also
1163 * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
1164 * @param bool $fromMaster Whether to use the DB_MASTER database
1165 * @return DatabaseBlock|null (null if no relevant block could be found). The target and type
1166 * of the returned block will refer to the actual block which was found, which might
1167 * not be the same as the target you gave if you used $vagueTarget!
1168 */
1169 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1170 $blocks = self::newListFromTarget( $specificTarget, $vagueTarget, $fromMaster );
1171 return self::chooseMostSpecificBlock( $blocks );
1172 }
1173
1174 /**
1175 * This is similar to DatabaseBlock::newFromTarget, but it returns all the relevant blocks.
1176 *
1177 * @since 1.34
1178 * @param string|User|int|null $specificTarget
1179 * @param string|User|int|null $vagueTarget
1180 * @param bool $fromMaster
1181 * @return DatabaseBlock[] Any relevant blocks
1182 */
1183 public static function newListFromTarget(
1184 $specificTarget,
1185 $vagueTarget = null,
1186 $fromMaster = false
1187 ) {
1188 list( $target, $type ) = self::parseTarget( $specificTarget );
1189 if ( $type == self::TYPE_ID || $type == self::TYPE_AUTO ) {
1190 $block = self::newFromID( $target );
1191 return $block ? [ $block ] : [];
1192 } elseif ( $target === null && $vagueTarget == '' ) {
1193 # We're not going to find anything useful here
1194 # Be aware that the == '' check is explicit, since empty values will be
1195 # passed by some callers (T31116)
1196 return [];
1197 } elseif ( in_array(
1198 $type,
1199 [ self::TYPE_USER, self::TYPE_IP, self::TYPE_RANGE, null ] )
1200 ) {
1201 return self::newLoad( $target, $type, $fromMaster, $vagueTarget );
1202 }
1203 return [];
1204 }
1205
1206 /**
1207 * Get all blocks that match any IP from an array of IP addresses
1208 *
1209 * @param array $ipChain List of IPs (strings), usually retrieved from the
1210 * X-Forwarded-For header of the request
1211 * @param bool $isAnon Exclude anonymous-only blocks if false
1212 * @param bool $fromMaster Whether to query the master or replica DB
1213 * @return array Array of Blocks
1214 * @since 1.22
1215 */
1216 public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
1217 if ( $ipChain === [] ) {
1218 return [];
1219 }
1220
1221 $conds = [];
1222 $proxyLookup = MediaWikiServices::getInstance()->getProxyLookup();
1223 foreach ( array_unique( $ipChain ) as $ipaddr ) {
1224 # Discard invalid IP addresses. Since XFF can be spoofed and we do not
1225 # necessarily trust the header given to us, make sure that we are only
1226 # checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
1227 # Do not treat private IP spaces as special as it may be desirable for wikis
1228 # to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
1229 if ( !IP::isValid( $ipaddr ) ) {
1230 continue;
1231 }
1232 # Don't check trusted IPs (includes local CDNs which will be in every request)
1233 if ( $proxyLookup->isTrustedProxy( $ipaddr ) ) {
1234 continue;
1235 }
1236 # Check both the original IP (to check against single blocks), as well as build
1237 # the clause to check for rangeblocks for the given IP.
1238 $conds['ipb_address'][] = $ipaddr;
1239 $conds[] = self::getRangeCond( IP::toHex( $ipaddr ) );
1240 }
1241
1242 if ( $conds === [] ) {
1243 return [];
1244 }
1245
1246 if ( $fromMaster ) {
1247 $db = wfGetDB( DB_MASTER );
1248 } else {
1249 $db = wfGetDB( DB_REPLICA );
1250 }
1251 $conds = $db->makeList( $conds, LIST_OR );
1252 if ( !$isAnon ) {
1253 $conds = [ $conds, 'ipb_anon_only' => 0 ];
1254 }
1255 $blockQuery = self::getQueryInfo();
1256 $rows = $db->select(
1257 $blockQuery['tables'],
1258 array_merge( [ 'ipb_range_start', 'ipb_range_end' ], $blockQuery['fields'] ),
1259 $conds,
1260 __METHOD__,
1261 [],
1262 $blockQuery['joins']
1263 );
1264
1265 $blocks = [];
1266 foreach ( $rows as $row ) {
1267 $block = self::newFromRow( $row );
1268 if ( !$block->isExpired() ) {
1269 $blocks[] = $block;
1270 }
1271 }
1272
1273 return $blocks;
1274 }
1275
1276 /**
1277 * From a list of multiple blocks, find the most exact and strongest block.
1278 *
1279 * The logic for finding the "best" block is:
1280 * - Blocks that match the block's target IP are preferred over ones in a range
1281 * - Hardblocks are chosen over softblocks that prevent account creation
1282 * - Softblocks that prevent account creation are chosen over other softblocks
1283 * - Other softblocks are chosen over autoblocks
1284 * - If there are multiple exact or range blocks at the same level, the one chosen
1285 * is random
1286 * This should be used when $blocks were retrieved from the user's IP address
1287 * and $ipChain is populated from the same IP address information.
1288 *
1289 * @param array $blocks Array of DatabaseBlock objects
1290 * @param array $ipChain List of IPs (strings). This is used to determine how "close"
1291 * a block is to the server, and if a block matches exactly, or is in a range.
1292 * The order is furthest from the server to nearest e.g., (Browser, proxy1, proxy2,
1293 * local-cdn, ...)
1294 * @throws MWException
1295 * @return DatabaseBlock|null The "best" block from the list
1296 */
1297 public static function chooseBlock( array $blocks, array $ipChain ) {
1298 if ( $blocks === [] ) {
1299 return null;
1300 } elseif ( count( $blocks ) == 1 ) {
1301 return $blocks[0];
1302 }
1303
1304 // Sort hard blocks before soft ones and secondarily sort blocks
1305 // that disable account creation before those that don't.
1306 usort( $blocks, function ( DatabaseBlock $a, DatabaseBlock $b ) {
1307 $aWeight = (int)$a->isHardblock() . (int)$a->appliesToRight( 'createaccount' );
1308 $bWeight = (int)$b->isHardblock() . (int)$b->appliesToRight( 'createaccount' );
1309 return strcmp( $bWeight, $aWeight ); // highest weight first
1310 } );
1311
1312 $blocksListExact = [
1313 'hard' => false,
1314 'disable_create' => false,
1315 'other' => false,
1316 'auto' => false
1317 ];
1318 $blocksListRange = [
1319 'hard' => false,
1320 'disable_create' => false,
1321 'other' => false,
1322 'auto' => false
1323 ];
1324 $ipChain = array_reverse( $ipChain );
1325
1326 foreach ( $blocks as $block ) {
1327 // Stop searching if we have already have a "better" block. This
1328 // is why the order of the blocks matters
1329 if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
1330 break;
1331 } elseif ( !$block->appliesToRight( 'createaccount' ) && $blocksListExact['disable_create'] ) {
1332 break;
1333 }
1334
1335 foreach ( $ipChain as $checkip ) {
1336 $checkipHex = IP::toHex( $checkip );
1337 if ( (string)$block->getTarget() === $checkip ) {
1338 if ( $block->isHardblock() ) {
1339 $blocksListExact['hard'] = $blocksListExact['hard'] ?: $block;
1340 } elseif ( $block->appliesToRight( 'createaccount' ) ) {
1341 $blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?: $block;
1342 } elseif ( $block->mAuto ) {
1343 $blocksListExact['auto'] = $blocksListExact['auto'] ?: $block;
1344 } else {
1345 $blocksListExact['other'] = $blocksListExact['other'] ?: $block;
1346 }
1347 // We found closest exact match in the ip list, so go to the next block
1348 break;
1349 } elseif ( array_filter( $blocksListExact ) == []
1350 && $block->getRangeStart() <= $checkipHex
1351 && $block->getRangeEnd() >= $checkipHex
1352 ) {
1353 if ( $block->isHardblock() ) {
1354 $blocksListRange['hard'] = $blocksListRange['hard'] ?: $block;
1355 } elseif ( $block->appliesToRight( 'createaccount' ) ) {
1356 $blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?: $block;
1357 } elseif ( $block->mAuto ) {
1358 $blocksListRange['auto'] = $blocksListRange['auto'] ?: $block;
1359 } else {
1360 $blocksListRange['other'] = $blocksListRange['other'] ?: $block;
1361 }
1362 break;
1363 }
1364 }
1365 }
1366
1367 if ( array_filter( $blocksListExact ) == [] ) {
1368 $blocksList = &$blocksListRange;
1369 } else {
1370 $blocksList = &$blocksListExact;
1371 }
1372
1373 $chosenBlock = null;
1374 if ( $blocksList['hard'] ) {
1375 $chosenBlock = $blocksList['hard'];
1376 } elseif ( $blocksList['disable_create'] ) {
1377 $chosenBlock = $blocksList['disable_create'];
1378 } elseif ( $blocksList['other'] ) {
1379 $chosenBlock = $blocksList['other'];
1380 } elseif ( $blocksList['auto'] ) {
1381 $chosenBlock = $blocksList['auto'];
1382 } else {
1383 throw new MWException( "Proxy block found, but couldn't be classified." );
1384 }
1385
1386 return $chosenBlock;
1387 }
1388
1389 /**
1390 * @inheritDoc
1391 *
1392 * Autoblocks have whichever type corresponds to their target, so to detect if a block is an
1393 * autoblock, we have to check the mAuto property instead.
1394 */
1395 public function getType() {
1396 return $this->mAuto
1397 ? self::TYPE_AUTO
1398 : parent::getType();
1399 }
1400
1401 /**
1402 * Set the 'BlockID' cookie to this block's ID and expiry time. The cookie's expiry will be
1403 * the same as the block's, to a maximum of 24 hours.
1404 *
1405 * @since 1.29
1406 * @deprecated since 1.34 Set a cookie via BlockManager::trackBlockWithCookie instead.
1407 * @param WebResponse $response The response on which to set the cookie.
1408 */
1409 public function setCookie( WebResponse $response ) {
1410 MediaWikiServices::getInstance()->getBlockManager()->setBlockCookie( $this, $response );
1411 }
1412
1413 /**
1414 * Unset the 'BlockID' cookie.
1415 *
1416 * @since 1.29
1417 * @deprecated since 1.34 Use BlockManager::clearBlockCookie instead
1418 * @param WebResponse $response The response on which to unset the cookie.
1419 */
1420 public static function clearCookie( WebResponse $response ) {
1421 MediaWikiServices::getInstance()->getBlockManager()->clearBlockCookie( $response );
1422 }
1423
1424 /**
1425 * Get the BlockID cookie's value for this block. This is usually the block ID concatenated
1426 * with an HMAC in order to avoid spoofing (T152951), but if wgSecretKey is not set will just
1427 * be the block ID.
1428 *
1429 * @since 1.29
1430 * @deprecated since 1.34 Use BlockManager::trackBlockWithCookie instead of calling this
1431 * directly
1432 * @return string The block ID, probably concatenated with "!" and the HMAC.
1433 */
1434 public function getCookieValue() {
1435 return MediaWikiServices::getInstance()->getBlockManager()->getCookieValue( $this );
1436 }
1437
1438 /**
1439 * Get the stored ID from the 'BlockID' cookie. The cookie's value is usually a combination of
1440 * the ID and a HMAC (see DatabaseBlock::setCookie), but will sometimes only be the ID.
1441 *
1442 * @since 1.29
1443 * @deprecated since 1.34 Use BlockManager::getUserBlock instead
1444 * @param string $cookieValue The string in which to find the ID.
1445 * @return int|null The block ID, or null if the HMAC is present and invalid.
1446 */
1447 public static function getIdFromCookieValue( $cookieValue ) {
1448 return MediaWikiServices::getInstance()->getBlockManager()->getIdFromCookieValue( $cookieValue );
1449 }
1450
1451 /**
1452 * @inheritDoc
1453 *
1454 * Build different messages for autoblocks and partial blocks.
1455 */
1456 public function getPermissionsError( IContextSource $context ) {
1457 $params = $this->getBlockErrorParams( $context );
1458
1459 $msg = 'blockedtext';
1460 if ( $this->mAuto ) {
1461 $msg = 'autoblockedtext';
1462 } elseif ( !$this->isSitewide() ) {
1463 $msg = 'blockedtext-partial';
1464 }
1465
1466 array_unshift( $params, $msg );
1467
1468 return $params;
1469 }
1470
1471 /**
1472 * Get Restrictions.
1473 *
1474 * Getting the restrictions will perform a database query if the restrictions
1475 * are not already loaded.
1476 *
1477 * @since 1.33
1478 * @return Restriction[]
1479 */
1480 public function getRestrictions() {
1481 if ( $this->restrictions === null ) {
1482 // If the block id has not been set, then do not attempt to load the
1483 // restrictions.
1484 if ( !$this->mId ) {
1485 return [];
1486 }
1487 $this->restrictions = $this->getBlockRestrictionStore()->loadByBlockId( $this->mId );
1488 }
1489
1490 return $this->restrictions;
1491 }
1492
1493 /**
1494 * Set Restrictions.
1495 *
1496 * @since 1.33
1497 * @param Restriction[] $restrictions
1498 * @return self
1499 */
1500 public function setRestrictions( array $restrictions ) {
1501 $this->restrictions = array_filter( $restrictions, function ( $restriction ) {
1502 return $restriction instanceof Restriction;
1503 } );
1504
1505 return $this;
1506 }
1507
1508 /**
1509 * @inheritDoc
1510 */
1511 public function appliesToTitle( Title $title ) {
1512 if ( $this->isSitewide() ) {
1513 return true;
1514 }
1515
1516 $restrictions = $this->getRestrictions();
1517 foreach ( $restrictions as $restriction ) {
1518 if ( $restriction->matches( $title ) ) {
1519 return true;
1520 }
1521 }
1522
1523 return false;
1524 }
1525
1526 /**
1527 * @inheritDoc
1528 */
1529 public function appliesToNamespace( $ns ) {
1530 if ( $this->isSitewide() ) {
1531 return true;
1532 }
1533
1534 // Blocks do not apply to virtual namespaces.
1535 if ( $ns < 0 ) {
1536 return false;
1537 }
1538
1539 $restriction = $this->findRestriction( NamespaceRestriction::TYPE, $ns );
1540
1541 return (bool)$restriction;
1542 }
1543
1544 /**
1545 * @inheritDoc
1546 */
1547 public function appliesToPage( $pageId ) {
1548 if ( $this->isSitewide() ) {
1549 return true;
1550 }
1551
1552 // If the pageId is not over zero, the block cannot apply to it.
1553 if ( $pageId <= 0 ) {
1554 return false;
1555 }
1556
1557 $restriction = $this->findRestriction( PageRestriction::TYPE, $pageId );
1558
1559 return (bool)$restriction;
1560 }
1561
1562 /**
1563 * Find Restriction by type and value.
1564 *
1565 * @param string $type
1566 * @param int $value
1567 * @return Restriction|null
1568 */
1569 private function findRestriction( $type, $value ) {
1570 $restrictions = $this->getRestrictions();
1571 foreach ( $restrictions as $restriction ) {
1572 if ( $restriction->getType() !== $type ) {
1573 continue;
1574 }
1575
1576 if ( $restriction->getValue() === $value ) {
1577 return $restriction;
1578 }
1579 }
1580
1581 return null;
1582 }
1583
1584 /**
1585 * @deprecated since 1.34 Use BlockManager::trackBlockWithCookie instead of calling this
1586 * directly.
1587 * @inheritDoc
1588 */
1589 public function shouldTrackWithCookie( $isAnon ) {
1590 wfDeprecated( __METHOD__, '1.34' );
1591 $config = RequestContext::getMain()->getConfig();
1592 switch ( $this->getType() ) {
1593 case self::TYPE_IP:
1594 case self::TYPE_RANGE:
1595 return $isAnon && $config->get( 'CookieSetOnIpBlock' );
1596 case self::TYPE_USER:
1597 return !$isAnon && $config->get( 'CookieSetOnAutoblock' ) && $this->isAutoblocking();
1598 default:
1599 return false;
1600 }
1601 }
1602
1603 /**
1604 * Get a BlockRestrictionStore instance
1605 *
1606 * @return BlockRestrictionStore
1607 */
1608 private function getBlockRestrictionStore() : BlockRestrictionStore {
1609 return MediaWikiServices::getInstance()->getBlockRestrictionStore();
1610 }
1611 }
1612
1613 /**
1614 * @deprecated since 1.34
1615 */
1616 class_alias( DatabaseBlock::class, 'Block' );