Merge "Revision history: Prefer `outline` over `border` to give text more space"
[lhc/web/wiklou.git] / includes / Block.php
1 <?php
2 /**
3 * Blocks and bans object
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 use Wikimedia\Rdbms\Database;
24 use Wikimedia\Rdbms\IDatabase;
25 use MediaWiki\Block\BlockRestrictionStore;
26 use MediaWiki\Block\Restriction\Restriction;
27 use MediaWiki\Block\Restriction\NamespaceRestriction;
28 use MediaWiki\Block\Restriction\PageRestriction;
29 use MediaWiki\MediaWikiServices;
30
31 class Block {
32 /** @var string */
33 public $mReason;
34
35 /** @var string */
36 public $mTimestamp;
37
38 /** @var bool */
39 public $mAuto;
40
41 /** @var string */
42 public $mExpiry;
43
44 /** @var bool */
45 public $mHideName;
46
47 /** @var int */
48 public $mParentBlockId;
49
50 /** @var int */
51 private $mId;
52
53 /** @var bool */
54 private $mFromMaster;
55
56 /** @var bool */
57 private $mBlockEmail;
58
59 /** @var bool */
60 private $allowUsertalk;
61
62 /** @var bool */
63 private $blockCreateAccount;
64
65 /** @var User|string */
66 private $target;
67
68 /** @var int Hack for foreign blocking (CentralAuth) */
69 private $forcedTargetID;
70
71 /**
72 * @var int Block::TYPE_ constant. After the block has been loaded
73 * from the database, this can only be USER, IP or RANGE.
74 */
75 private $type;
76
77 /** @var User */
78 private $blocker;
79
80 /** @var bool */
81 private $isHardblock;
82
83 /** @var bool */
84 private $isAutoblocking;
85
86 /** @var string|null */
87 private $systemBlockType;
88
89 /** @var bool */
90 private $isSitewide;
91
92 /** @var Restriction[] */
93 private $restrictions;
94
95 # TYPE constants
96 const TYPE_USER = 1;
97 const TYPE_IP = 2;
98 const TYPE_RANGE = 3;
99 const TYPE_AUTO = 4;
100 const TYPE_ID = 5;
101
102 /**
103 * Create a new block with specified option parameters on a user, IP or IP range.
104 *
105 * @param array $options Parameters of the block:
106 * address string|User Target user name, User object, IP address or IP range
107 * user int Override target user ID (for foreign users)
108 * by int User ID of the blocker
109 * reason string Reason of the block
110 * timestamp string The time at which the block comes into effect
111 * auto bool Is this an automatic block?
112 * expiry string Timestamp of expiration of the block or 'infinity'
113 * anonOnly bool Only disallow anonymous actions
114 * createAccount bool Disallow creation of new accounts
115 * enableAutoblock bool Enable automatic blocking
116 * hideName bool Hide the target user name
117 * blockEmail bool Disallow sending emails
118 * allowUsertalk bool Allow the target to edit its own talk page
119 * byText string Username of the blocker (for foreign users)
120 * systemBlock string Indicate that this block is automatically
121 * created by MediaWiki rather than being stored
122 * in the database. Value is a string to return
123 * from self::getSystemBlockType().
124 * sitewide bool Disallow editing all pages and all contribution
125 * actions, except those specifically allowed by
126 * other block flags
127 *
128 * @since 1.26 $options array
129 */
130 public function __construct( array $options = [] ) {
131 $defaults = [
132 'address' => '',
133 'user' => null,
134 'by' => null,
135 'reason' => '',
136 'timestamp' => '',
137 'auto' => false,
138 'expiry' => '',
139 'anonOnly' => false,
140 'createAccount' => false,
141 'enableAutoblock' => false,
142 'hideName' => false,
143 'blockEmail' => false,
144 'allowUsertalk' => false,
145 'byText' => '',
146 'systemBlock' => null,
147 'sitewide' => true,
148 ];
149
150 $options += $defaults;
151
152 $this->setTarget( $options['address'] );
153
154 if ( $this->target instanceof User && $options['user'] ) {
155 # Needed for foreign users
156 $this->forcedTargetID = $options['user'];
157 }
158
159 if ( $options['by'] ) {
160 # Local user
161 $this->setBlocker( User::newFromId( $options['by'] ) );
162 } else {
163 # Foreign user
164 $this->setBlocker( $options['byText'] );
165 }
166
167 $this->setReason( $options['reason'] );
168 $this->setTimestamp( wfTimestamp( TS_MW, $options['timestamp'] ) );
169 $this->setExpiry( wfGetDB( DB_REPLICA )->decodeExpiry( $options['expiry'] ) );
170
171 # Boolean settings
172 $this->mAuto = (bool)$options['auto'];
173 $this->setHideName( (bool)$options['hideName'] );
174 $this->isHardblock( !$options['anonOnly'] );
175 $this->isAutoblocking( (bool)$options['enableAutoblock'] );
176 $this->isSitewide( (bool)$options['sitewide'] );
177 $this->isEmailBlocked( (bool)$options['blockEmail'] );
178 $this->isCreateAccountBlocked( (bool)$options['createAccount'] );
179 $this->isUsertalkEditAllowed( (bool)$options['allowUsertalk'] );
180
181 $this->mFromMaster = false;
182 $this->systemBlockType = $options['systemBlock'];
183 }
184
185 /**
186 * Load a block from the block id.
187 *
188 * @param int $id Block id to search for
189 * @return Block|null
190 */
191 public static function newFromID( $id ) {
192 $dbr = wfGetDB( DB_REPLICA );
193 $blockQuery = self::getQueryInfo();
194 $res = $dbr->selectRow(
195 $blockQuery['tables'],
196 $blockQuery['fields'],
197 [ 'ipb_id' => $id ],
198 __METHOD__,
199 [],
200 $blockQuery['joins']
201 );
202 if ( $res ) {
203 return self::newFromRow( $res );
204 } else {
205 return null;
206 }
207 }
208
209 /**
210 * Return the list of ipblocks fields that should be selected to create
211 * a new block.
212 * @deprecated since 1.31, use self::getQueryInfo() instead.
213 * @return array
214 */
215 public static function selectFields() {
216 global $wgActorTableSchemaMigrationStage;
217
218 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW ) {
219 // If code is using this instead of self::getQueryInfo(), there's a
220 // decent chance it's going to try to directly access
221 // $row->ipb_by or $row->ipb_by_text and we can't give it
222 // useful values here once those aren't being used anymore.
223 throw new BadMethodCallException(
224 'Cannot use ' . __METHOD__
225 . ' when $wgActorTableSchemaMigrationStage has SCHEMA_COMPAT_READ_NEW'
226 );
227 }
228
229 wfDeprecated( __METHOD__, '1.31' );
230 return [
231 'ipb_id',
232 'ipb_address',
233 'ipb_by',
234 'ipb_by_text',
235 'ipb_by_actor' => 'NULL',
236 'ipb_timestamp',
237 'ipb_auto',
238 'ipb_anon_only',
239 'ipb_create_account',
240 'ipb_enable_autoblock',
241 'ipb_expiry',
242 'ipb_deleted',
243 'ipb_block_email',
244 'ipb_allow_usertalk',
245 'ipb_parent_block_id',
246 'ipb_sitewide',
247 ] + CommentStore::getStore()->getFields( 'ipb_reason' );
248 }
249
250 /**
251 * Return the tables, fields, and join conditions to be selected to create
252 * a new block object.
253 * @since 1.31
254 * @return array With three keys:
255 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
256 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
257 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
258 */
259 public static function getQueryInfo() {
260 $commentQuery = CommentStore::getStore()->getJoin( 'ipb_reason' );
261 $actorQuery = ActorMigration::newMigration()->getJoin( 'ipb_by' );
262 return [
263 'tables' => [ 'ipblocks' ] + $commentQuery['tables'] + $actorQuery['tables'],
264 'fields' => [
265 'ipb_id',
266 'ipb_address',
267 'ipb_timestamp',
268 'ipb_auto',
269 'ipb_anon_only',
270 'ipb_create_account',
271 'ipb_enable_autoblock',
272 'ipb_expiry',
273 'ipb_deleted',
274 'ipb_block_email',
275 'ipb_allow_usertalk',
276 'ipb_parent_block_id',
277 'ipb_sitewide',
278 ] + $commentQuery['fields'] + $actorQuery['fields'],
279 'joins' => $commentQuery['joins'] + $actorQuery['joins'],
280 ];
281 }
282
283 /**
284 * Check if two blocks are effectively equal. Doesn't check irrelevant things like
285 * the blocking user or the block timestamp, only things which affect the blocked user
286 *
287 * @param Block $block
288 *
289 * @return bool
290 */
291 public function equals( Block $block ) {
292 return (
293 (string)$this->target == (string)$block->target
294 && $this->type == $block->type
295 && $this->mAuto == $block->mAuto
296 && $this->isHardblock() == $block->isHardblock()
297 && $this->isCreateAccountBlocked() == $block->isCreateAccountBlocked()
298 && $this->getExpiry() == $block->getExpiry()
299 && $this->isAutoblocking() == $block->isAutoblocking()
300 && $this->getHideName() == $block->getHideName()
301 && $this->isEmailBlocked() == $block->isEmailBlocked()
302 && $this->isUsertalkEditAllowed() == $block->isUsertalkEditAllowed()
303 && $this->getReason() == $block->getReason()
304 && $this->isSitewide() == $block->isSitewide()
305 // Block::getRestrictions() may perform a database query, so keep it at
306 // the end.
307 && $this->getBlockRestrictionStore()->equals(
308 $this->getRestrictions(), $block->getRestrictions()
309 )
310 );
311 }
312
313 /**
314 * Load a block from the database which affects the already-set $this->target:
315 * 1) A block directly on the given user or IP
316 * 2) A rangeblock encompassing the given IP (smallest first)
317 * 3) An autoblock on the given IP
318 * @param User|string|null $vagueTarget Also search for blocks affecting this target. Doesn't
319 * make any sense to use TYPE_AUTO / TYPE_ID here. Leave blank to skip IP lookups.
320 * @throws MWException
321 * @return bool Whether a relevant block was found
322 */
323 protected function newLoad( $vagueTarget = null ) {
324 $db = wfGetDB( $this->mFromMaster ? DB_MASTER : DB_REPLICA );
325
326 if ( $this->type !== null ) {
327 $conds = [
328 'ipb_address' => [ (string)$this->target ],
329 ];
330 } else {
331 $conds = [ 'ipb_address' => [] ];
332 }
333
334 # Be aware that the != '' check is explicit, since empty values will be
335 # passed by some callers (T31116)
336 if ( $vagueTarget != '' ) {
337 list( $target, $type ) = self::parseTarget( $vagueTarget );
338 switch ( $type ) {
339 case self::TYPE_USER:
340 # Slightly weird, but who are we to argue?
341 $conds['ipb_address'][] = (string)$target;
342 break;
343
344 case self::TYPE_IP:
345 $conds['ipb_address'][] = (string)$target;
346 $conds[] = self::getRangeCond( IP::toHex( $target ) );
347 $conds = $db->makeList( $conds, LIST_OR );
348 break;
349
350 case self::TYPE_RANGE:
351 list( $start, $end ) = IP::parseRange( $target );
352 $conds['ipb_address'][] = (string)$target;
353 $conds[] = self::getRangeCond( $start, $end );
354 $conds = $db->makeList( $conds, LIST_OR );
355 break;
356
357 default:
358 throw new MWException( "Tried to load block with invalid type" );
359 }
360 }
361
362 $blockQuery = self::getQueryInfo();
363 $res = $db->select(
364 $blockQuery['tables'], $blockQuery['fields'], $conds, __METHOD__, [], $blockQuery['joins']
365 );
366
367 # This result could contain a block on the user, a block on the IP, and a russian-doll
368 # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
369 $bestRow = null;
370
371 # Lower will be better
372 $bestBlockScore = 100;
373
374 foreach ( $res as $row ) {
375 $block = self::newFromRow( $row );
376
377 # Don't use expired blocks
378 if ( $block->isExpired() ) {
379 continue;
380 }
381
382 # Don't use anon only blocks on users
383 if ( $this->type == self::TYPE_USER && !$block->isHardblock() ) {
384 continue;
385 }
386
387 if ( $block->getType() == self::TYPE_RANGE ) {
388 # This is the number of bits that are allowed to vary in the block, give
389 # or take some floating point errors
390 $prefix = 'v6-';
391 $end = Wikimedia\base_convert( ltrim( $block->getRangeEnd(), $prefix ), 16, 10 );
392 $start = Wikimedia\base_convert( ltrim( $block->getRangeStart(), $prefix ), 16, 10 );
393 $size = log( $end - $start + 1, 2 );
394
395 # Rank a range block covering a single IP equally with a single-IP block
396 $score = self::TYPE_RANGE - 1 + ( $size / 128 );
397
398 } else {
399 $score = $block->getType();
400 }
401
402 if ( $score < $bestBlockScore ) {
403 $bestBlockScore = $score;
404 $bestRow = $row;
405 }
406 }
407
408 if ( $bestRow !== null ) {
409 $this->initFromRow( $bestRow );
410 return true;
411 } else {
412 return false;
413 }
414 }
415
416 /**
417 * Get a set of SQL conditions which will select rangeblocks encompassing a given range
418 * @param string $start Hexadecimal IP representation
419 * @param string|null $end Hexadecimal IP representation, or null to use $start = $end
420 * @return string
421 */
422 public static function getRangeCond( $start, $end = null ) {
423 if ( $end === null ) {
424 $end = $start;
425 }
426 # Per T16634, we want to include relevant active rangeblocks; for
427 # rangeblocks, we want to include larger ranges which enclose the given
428 # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
429 # so we can improve performance by filtering on a LIKE clause
430 $chunk = self::getIpFragment( $start );
431 $dbr = wfGetDB( DB_REPLICA );
432 $like = $dbr->buildLike( $chunk, $dbr->anyString() );
433
434 # Fairly hard to make a malicious SQL statement out of hex characters,
435 # but stranger things have happened...
436 $safeStart = $dbr->addQuotes( $start );
437 $safeEnd = $dbr->addQuotes( $end );
438
439 return $dbr->makeList(
440 [
441 "ipb_range_start $like",
442 "ipb_range_start <= $safeStart",
443 "ipb_range_end >= $safeEnd",
444 ],
445 LIST_AND
446 );
447 }
448
449 /**
450 * Get the component of an IP address which is certain to be the same between an IP
451 * address and a rangeblock containing that IP address.
452 * @param string $hex Hexadecimal IP representation
453 * @return string
454 */
455 protected static function getIpFragment( $hex ) {
456 global $wgBlockCIDRLimit;
457 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
458 return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
459 } else {
460 return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
461 }
462 }
463
464 /**
465 * Given a database row from the ipblocks table, initialize
466 * member variables
467 * @param stdClass $row A row from the ipblocks table
468 */
469 protected function initFromRow( $row ) {
470 $this->setTarget( $row->ipb_address );
471 $this->setBlocker( User::newFromAnyId(
472 $row->ipb_by, $row->ipb_by_text, $row->ipb_by_actor ?? null
473 ) );
474
475 $this->setTimestamp( wfTimestamp( TS_MW, $row->ipb_timestamp ) );
476 $this->mAuto = $row->ipb_auto;
477 $this->setHideName( $row->ipb_deleted );
478 $this->mId = (int)$row->ipb_id;
479 $this->mParentBlockId = $row->ipb_parent_block_id;
480
481 // I wish I didn't have to do this
482 $db = wfGetDB( DB_REPLICA );
483 $this->setExpiry( $db->decodeExpiry( $row->ipb_expiry ) );
484 $this->setReason(
485 CommentStore::getStore()
486 // Legacy because $row may have come from self::selectFields()
487 ->getCommentLegacy( $db, 'ipb_reason', $row )->text
488 );
489
490 $this->isHardblock( !$row->ipb_anon_only );
491 $this->isAutoblocking( $row->ipb_enable_autoblock );
492 $this->isSitewide( (bool)$row->ipb_sitewide );
493
494 $this->isCreateAccountBlocked( $row->ipb_create_account );
495 $this->isEmailBlocked( $row->ipb_block_email );
496 $this->isUsertalkEditAllowed( $row->ipb_allow_usertalk );
497 }
498
499 /**
500 * Create a new Block object from a database row
501 * @param stdClass $row Row from the ipblocks table
502 * @return Block
503 */
504 public static function newFromRow( $row ) {
505 $block = new Block;
506 $block->initFromRow( $row );
507 return $block;
508 }
509
510 /**
511 * Delete the row from the IP blocks table.
512 *
513 * @throws MWException
514 * @return bool
515 */
516 public function delete() {
517 if ( wfReadOnly() ) {
518 return false;
519 }
520
521 if ( !$this->getId() ) {
522 throw new MWException( "Block::delete() requires that the mId member be filled\n" );
523 }
524
525 $dbw = wfGetDB( DB_MASTER );
526
527 $this->getBlockRestrictionStore()->deleteByParentBlockId( $this->getId() );
528 $dbw->delete( 'ipblocks', [ 'ipb_parent_block_id' => $this->getId() ], __METHOD__ );
529
530 $this->getBlockRestrictionStore()->deleteByBlockId( $this->getId() );
531 $dbw->delete( 'ipblocks', [ 'ipb_id' => $this->getId() ], __METHOD__ );
532
533 return $dbw->affectedRows() > 0;
534 }
535
536 /**
537 * Insert a block into the block table. Will fail if there is a conflicting
538 * block (same name and options) already in the database.
539 *
540 * @param IDatabase|null $dbw If you have one available
541 * @return bool|array False on failure, assoc array on success:
542 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
543 */
544 public function insert( $dbw = null ) {
545 global $wgBlockDisablesLogin;
546
547 if ( $this->getSystemBlockType() !== null ) {
548 throw new MWException( 'Cannot insert a system block into the database' );
549 }
550 if ( !$this->getBlocker() || $this->getBlocker()->getName() === '' ) {
551 throw new MWException( 'Cannot insert a block without a blocker set' );
552 }
553
554 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
555
556 if ( $dbw === null ) {
557 $dbw = wfGetDB( DB_MASTER );
558 }
559
560 self::purgeExpired();
561
562 $row = $this->getDatabaseArray( $dbw );
563
564 $dbw->insert( 'ipblocks', $row, __METHOD__, [ 'IGNORE' ] );
565 $affected = $dbw->affectedRows();
566 if ( $affected ) {
567 $this->setId( $dbw->insertId() );
568 if ( $this->restrictions ) {
569 $this->getBlockRestrictionStore()->insert( $this->restrictions );
570 }
571 }
572
573 # Don't collide with expired blocks.
574 # Do this after trying to insert to avoid locking.
575 if ( !$affected ) {
576 # T96428: The ipb_address index uses a prefix on a field, so
577 # use a standard SELECT + DELETE to avoid annoying gap locks.
578 $ids = $dbw->selectFieldValues( 'ipblocks',
579 'ipb_id',
580 [
581 'ipb_address' => $row['ipb_address'],
582 'ipb_user' => $row['ipb_user'],
583 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() )
584 ],
585 __METHOD__
586 );
587 if ( $ids ) {
588 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], __METHOD__ );
589 $this->getBlockRestrictionStore()->deleteByBlockId( $ids );
590 $dbw->insert( 'ipblocks', $row, __METHOD__, [ 'IGNORE' ] );
591 $affected = $dbw->affectedRows();
592 $this->setId( $dbw->insertId() );
593 if ( $this->restrictions ) {
594 $this->getBlockRestrictionStore()->insert( $this->restrictions );
595 }
596 }
597 }
598
599 if ( $affected ) {
600 $auto_ipd_ids = $this->doRetroactiveAutoblock();
601
602 if ( $wgBlockDisablesLogin && $this->target instanceof User ) {
603 // Change user login token to force them to be logged out.
604 $this->target->setToken();
605 $this->target->saveSettings();
606 }
607
608 return [ 'id' => $this->mId, 'autoIds' => $auto_ipd_ids ];
609 }
610
611 return false;
612 }
613
614 /**
615 * Update a block in the DB with new parameters.
616 * The ID field needs to be loaded first.
617 *
618 * @return bool|array False on failure, array on success:
619 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
620 */
621 public function update() {
622 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
623 $dbw = wfGetDB( DB_MASTER );
624
625 $dbw->startAtomic( __METHOD__ );
626
627 $result = $dbw->update(
628 'ipblocks',
629 $this->getDatabaseArray( $dbw ),
630 [ 'ipb_id' => $this->getId() ],
631 __METHOD__
632 );
633
634 // Only update the restrictions if they have been modified.
635 if ( $this->restrictions !== null ) {
636 // An empty array should remove all of the restrictions.
637 if ( empty( $this->restrictions ) ) {
638 $success = $this->getBlockRestrictionStore()->deleteByBlockId( $this->getId() );
639 } else {
640 $success = $this->getBlockRestrictionStore()->update( $this->restrictions );
641 }
642 // Update the result. The first false is the result, otherwise, true.
643 $result = $result && $success;
644 }
645
646 if ( $this->isAutoblocking() ) {
647 // update corresponding autoblock(s) (T50813)
648 $dbw->update(
649 'ipblocks',
650 $this->getAutoblockUpdateArray( $dbw ),
651 [ 'ipb_parent_block_id' => $this->getId() ],
652 __METHOD__
653 );
654
655 // Only update the restrictions if they have been modified.
656 if ( $this->restrictions !== null ) {
657 $this->getBlockRestrictionStore()->updateByParentBlockId( $this->getId(), $this->restrictions );
658 }
659 } else {
660 // autoblock no longer required, delete corresponding autoblock(s)
661 $this->getBlockRestrictionStore()->deleteByParentBlockId( $this->getId() );
662 $dbw->delete(
663 'ipblocks',
664 [ 'ipb_parent_block_id' => $this->getId() ],
665 __METHOD__
666 );
667 }
668
669 $dbw->endAtomic( __METHOD__ );
670
671 if ( $result ) {
672 $auto_ipd_ids = $this->doRetroactiveAutoblock();
673 return [ 'id' => $this->mId, 'autoIds' => $auto_ipd_ids ];
674 }
675
676 return $result;
677 }
678
679 /**
680 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
681 * @param IDatabase $dbw
682 * @return array
683 */
684 protected function getDatabaseArray( IDatabase $dbw ) {
685 $expiry = $dbw->encodeExpiry( $this->getExpiry() );
686
687 if ( $this->forcedTargetID ) {
688 $uid = $this->forcedTargetID;
689 } else {
690 $uid = $this->target instanceof User ? $this->target->getId() : 0;
691 }
692
693 $a = [
694 'ipb_address' => (string)$this->target,
695 'ipb_user' => $uid,
696 'ipb_timestamp' => $dbw->timestamp( $this->getTimestamp() ),
697 'ipb_auto' => $this->mAuto,
698 'ipb_anon_only' => !$this->isHardblock(),
699 'ipb_create_account' => $this->isCreateAccountBlocked(),
700 'ipb_enable_autoblock' => $this->isAutoblocking(),
701 'ipb_expiry' => $expiry,
702 'ipb_range_start' => $this->getRangeStart(),
703 'ipb_range_end' => $this->getRangeEnd(),
704 'ipb_deleted' => intval( $this->getHideName() ), // typecast required for SQLite
705 'ipb_block_email' => $this->isEmailBlocked(),
706 'ipb_allow_usertalk' => $this->isUsertalkEditAllowed(),
707 'ipb_parent_block_id' => $this->mParentBlockId,
708 'ipb_sitewide' => $this->isSitewide(),
709 ] + CommentStore::getStore()->insert( $dbw, 'ipb_reason', $this->getReason() )
710 + ActorMigration::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
711
712 return $a;
713 }
714
715 /**
716 * @param IDatabase $dbw
717 * @return array
718 */
719 protected function getAutoblockUpdateArray( IDatabase $dbw ) {
720 return [
721 'ipb_create_account' => $this->isCreateAccountBlocked(),
722 'ipb_deleted' => (int)$this->getHideName(), // typecast required for SQLite
723 'ipb_allow_usertalk' => $this->isUsertalkEditAllowed(),
724 'ipb_sitewide' => $this->isSitewide(),
725 ] + CommentStore::getStore()->insert( $dbw, 'ipb_reason', $this->getReason() )
726 + ActorMigration::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
727 }
728
729 /**
730 * Retroactively autoblocks the last IP used by the user (if it is a user)
731 * blocked by this Block.
732 *
733 * @return array Block IDs of retroactive autoblocks made
734 */
735 protected function doRetroactiveAutoblock() {
736 $blockIds = [];
737 # If autoblock is enabled, autoblock the LAST IP(s) used
738 if ( $this->isAutoblocking() && $this->getType() == self::TYPE_USER ) {
739 wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
740
741 $continue = Hooks::run(
742 'PerformRetroactiveAutoblock', [ $this, &$blockIds ] );
743
744 if ( $continue ) {
745 self::defaultRetroactiveAutoblock( $this, $blockIds );
746 }
747 }
748 return $blockIds;
749 }
750
751 /**
752 * Retroactively autoblocks the last IP used by the user (if it is a user)
753 * blocked by this Block. This will use the recentchanges table.
754 *
755 * @param Block $block
756 * @param array &$blockIds
757 */
758 protected static function defaultRetroactiveAutoblock( Block $block, array &$blockIds ) {
759 global $wgPutIPinRC;
760
761 // No IPs are in recentchanges table, so nothing to select
762 if ( !$wgPutIPinRC ) {
763 return;
764 }
765
766 // Autoblocks only apply to TYPE_USER
767 if ( $block->getType() !== self::TYPE_USER ) {
768 return;
769 }
770 $target = $block->getTarget(); // TYPE_USER => always a User object
771
772 $dbr = wfGetDB( DB_REPLICA );
773 $rcQuery = ActorMigration::newMigration()->getWhere( $dbr, 'rc_user', $target, false );
774
775 $options = [ 'ORDER BY' => 'rc_timestamp DESC' ];
776
777 // Just the last IP used.
778 $options['LIMIT'] = 1;
779
780 $res = $dbr->select(
781 [ 'recentchanges' ] + $rcQuery['tables'],
782 [ 'rc_ip' ],
783 $rcQuery['conds'],
784 __METHOD__,
785 $options,
786 $rcQuery['joins']
787 );
788
789 if ( !$res->numRows() ) {
790 # No results, don't autoblock anything
791 wfDebug( "No IP found to retroactively autoblock\n" );
792 } else {
793 foreach ( $res as $row ) {
794 if ( $row->rc_ip ) {
795 $id = $block->doAutoblock( $row->rc_ip );
796 if ( $id ) {
797 $blockIds[] = $id;
798 }
799 }
800 }
801 }
802 }
803
804 /**
805 * Checks whether a given IP is on the autoblock whitelist.
806 * TODO: this probably belongs somewhere else, but not sure where...
807 *
808 * @param string $ip The IP to check
809 * @return bool
810 */
811 public static function isWhitelistedFromAutoblocks( $ip ) {
812 // Try to get the autoblock_whitelist from the cache, as it's faster
813 // than getting the msg raw and explode()'ing it.
814 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
815 $lines = $cache->getWithSetCallback(
816 $cache->makeKey( 'ip-autoblock', 'whitelist' ),
817 $cache::TTL_DAY,
818 function ( $curValue, &$ttl, array &$setOpts ) {
819 $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
820
821 return explode( "\n",
822 wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
823 }
824 );
825
826 wfDebug( "Checking the autoblock whitelist..\n" );
827
828 foreach ( $lines as $line ) {
829 # List items only
830 if ( substr( $line, 0, 1 ) !== '*' ) {
831 continue;
832 }
833
834 $wlEntry = substr( $line, 1 );
835 $wlEntry = trim( $wlEntry );
836
837 wfDebug( "Checking $ip against $wlEntry..." );
838
839 # Is the IP in this range?
840 if ( IP::isInRange( $ip, $wlEntry ) ) {
841 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
842 return true;
843 } else {
844 wfDebug( " No match\n" );
845 }
846 }
847
848 return false;
849 }
850
851 /**
852 * Autoblocks the given IP, referring to this Block.
853 *
854 * @param string $autoblockIP The IP to autoblock.
855 * @return int|bool Block ID if an autoblock was inserted, false if not.
856 */
857 public function doAutoblock( $autoblockIP ) {
858 # If autoblocks are disabled, go away.
859 if ( !$this->isAutoblocking() ) {
860 return false;
861 }
862
863 # Don't autoblock for system blocks
864 if ( $this->getSystemBlockType() !== null ) {
865 throw new MWException( 'Cannot autoblock from a system block' );
866 }
867
868 # Check for presence on the autoblock whitelist.
869 if ( self::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
870 return false;
871 }
872
873 // Avoid PHP 7.1 warning of passing $this by reference
874 $block = $this;
875 # Allow hooks to cancel the autoblock.
876 if ( !Hooks::run( 'AbortAutoblock', [ $autoblockIP, &$block ] ) ) {
877 wfDebug( "Autoblock aborted by hook.\n" );
878 return false;
879 }
880
881 # It's okay to autoblock. Go ahead and insert/update the block...
882
883 # Do not add a *new* block if the IP is already blocked.
884 $ipblock = self::newFromTarget( $autoblockIP );
885 if ( $ipblock ) {
886 # Check if the block is an autoblock and would exceed the user block
887 # if renewed. If so, do nothing, otherwise prolong the block time...
888 if ( $ipblock->mAuto && // @todo Why not compare $ipblock->mExpiry?
889 $this->getExpiry() > self::getAutoblockExpiry( $ipblock->getTimestamp() )
890 ) {
891 # Reset block timestamp to now and its expiry to
892 # $wgAutoblockExpiry in the future
893 $ipblock->updateTimestamp();
894 }
895 return false;
896 }
897
898 # Make a new block object with the desired properties.
899 $autoblock = new Block;
900 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
901 $autoblock->setTarget( $autoblockIP );
902 $autoblock->setBlocker( $this->getBlocker() );
903 $autoblock->setReason(
904 wfMessage( 'autoblocker', $this->getTarget(), $this->getReason() )
905 ->inContentLanguage()->plain()
906 );
907 $timestamp = wfTimestampNow();
908 $autoblock->setTimestamp( $timestamp );
909 $autoblock->mAuto = 1;
910 $autoblock->isCreateAccountBlocked( $this->isCreateAccountBlocked() );
911 # Continue suppressing the name if needed
912 $autoblock->setHideName( $this->getHideName() );
913 $autoblock->isUsertalkEditAllowed( $this->isUsertalkEditAllowed() );
914 $autoblock->mParentBlockId = $this->mId;
915 $autoblock->isSitewide( $this->isSitewide() );
916 $autoblock->setRestrictions( $this->getRestrictions() );
917
918 if ( $this->getExpiry() == 'infinity' ) {
919 # Original block was indefinite, start an autoblock now
920 $autoblock->setExpiry( self::getAutoblockExpiry( $timestamp ) );
921 } else {
922 # If the user is already blocked with an expiry date, we don't
923 # want to pile on top of that.
924 $autoblock->setExpiry( min( $this->getExpiry(), self::getAutoblockExpiry( $timestamp ) ) );
925 }
926
927 # Insert the block...
928 $status = $autoblock->insert();
929 return $status
930 ? $status['id']
931 : false;
932 }
933
934 /**
935 * Check if a block has expired. Delete it if it is.
936 * @return bool
937 */
938 public function deleteIfExpired() {
939 if ( $this->isExpired() ) {
940 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
941 $this->delete();
942 $retVal = true;
943 } else {
944 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
945 $retVal = false;
946 }
947
948 return $retVal;
949 }
950
951 /**
952 * Has the block expired?
953 * @return bool
954 */
955 public function isExpired() {
956 $timestamp = wfTimestampNow();
957 wfDebug( "Block::isExpired() checking current " . $timestamp . " vs $this->mExpiry\n" );
958
959 if ( !$this->getExpiry() ) {
960 return false;
961 } else {
962 return $timestamp > $this->getExpiry();
963 }
964 }
965
966 /**
967 * Is the block address valid (i.e. not a null string?)
968 *
969 * @deprecated since 1.33 No longer needed in core.
970 * @return bool
971 */
972 public function isValid() {
973 wfDeprecated( __METHOD__, '1.33' );
974 return $this->getTarget() != null;
975 }
976
977 /**
978 * Update the timestamp on autoblocks.
979 */
980 public function updateTimestamp() {
981 if ( $this->mAuto ) {
982 $this->setTimestamp( wfTimestamp() );
983 $this->setExpiry( self::getAutoblockExpiry( $this->getTimestamp() ) );
984
985 $dbw = wfGetDB( DB_MASTER );
986 $dbw->update( 'ipblocks',
987 [ /* SET */
988 'ipb_timestamp' => $dbw->timestamp( $this->getTimestamp() ),
989 'ipb_expiry' => $dbw->timestamp( $this->getExpiry() ),
990 ],
991 [ /* WHERE */
992 'ipb_id' => $this->getId(),
993 ],
994 __METHOD__
995 );
996 }
997 }
998
999 /**
1000 * Get the IP address at the start of the range in Hex form
1001 * @throws MWException
1002 * @return string IP in Hex form
1003 */
1004 public function getRangeStart() {
1005 switch ( $this->type ) {
1006 case self::TYPE_USER:
1007 return '';
1008 case self::TYPE_IP:
1009 return IP::toHex( $this->target );
1010 case self::TYPE_RANGE:
1011 list( $start, /*...*/ ) = IP::parseRange( $this->target );
1012 return $start;
1013 default:
1014 throw new MWException( "Block with invalid type" );
1015 }
1016 }
1017
1018 /**
1019 * Get the IP address at the end of the range in Hex form
1020 * @throws MWException
1021 * @return string IP in Hex form
1022 */
1023 public function getRangeEnd() {
1024 switch ( $this->type ) {
1025 case self::TYPE_USER:
1026 return '';
1027 case self::TYPE_IP:
1028 return IP::toHex( $this->target );
1029 case self::TYPE_RANGE:
1030 list( /*...*/, $end ) = IP::parseRange( $this->target );
1031 return $end;
1032 default:
1033 throw new MWException( "Block with invalid type" );
1034 }
1035 }
1036
1037 /**
1038 * Get the user id of the blocking sysop
1039 *
1040 * @return int (0 for foreign users)
1041 */
1042 public function getBy() {
1043 return $this->getBlocker()->getId();
1044 }
1045
1046 /**
1047 * Get the username of the blocking sysop
1048 *
1049 * @return string
1050 */
1051 public function getByName() {
1052 return $this->getBlocker()->getName();
1053 }
1054
1055 /**
1056 * Get the block ID
1057 * @return int
1058 */
1059 public function getId() {
1060 return $this->mId;
1061 }
1062
1063 /**
1064 * Set the block ID
1065 *
1066 * @param int $blockId
1067 * @return int
1068 */
1069 private function setId( $blockId ) {
1070 $this->mId = (int)$blockId;
1071
1072 if ( is_array( $this->restrictions ) ) {
1073 $this->restrictions = $this->getBlockRestrictionStore()->setBlockId(
1074 $blockId, $this->restrictions
1075 );
1076 }
1077
1078 return $this;
1079 }
1080
1081 /**
1082 * Get the reason given for creating the block
1083 *
1084 * @since 1.33
1085 * @return string
1086 */
1087 public function getReason() {
1088 return $this->mReason;
1089 }
1090
1091 /**
1092 * Set the reason for creating the block
1093 *
1094 * @since 1.33
1095 * @param string $reason
1096 */
1097 public function setReason( $reason ) {
1098 $this->mReason = $reason;
1099 }
1100
1101 /**
1102 * Get whether the block hides the target's username
1103 *
1104 * @since 1.33
1105 * @return bool The block hides the username
1106 */
1107 public function getHideName() {
1108 return $this->mHideName;
1109 }
1110
1111 /**
1112 * Set whether ths block hides the target's username
1113 *
1114 * @since 1.33
1115 * @param bool $hideName The block hides the username
1116 */
1117 public function setHideName( $hideName ) {
1118 $this->mHideName = $hideName;
1119 }
1120
1121 /**
1122 * Get the system block type, if any
1123 * @since 1.29
1124 * @return string|null
1125 */
1126 public function getSystemBlockType() {
1127 return $this->systemBlockType;
1128 }
1129
1130 /**
1131 * Get/set a flag determining whether the master is used for reads
1132 *
1133 * @param bool|null $x
1134 * @return bool
1135 */
1136 public function fromMaster( $x = null ) {
1137 return wfSetVar( $this->mFromMaster, $x );
1138 }
1139
1140 /**
1141 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range)
1142 * @param bool|null $x
1143 * @return bool
1144 */
1145 public function isHardblock( $x = null ) {
1146 wfSetVar( $this->isHardblock, $x );
1147
1148 # You can't *not* hardblock a user
1149 return $this->getType() == self::TYPE_USER
1150 ? true
1151 : $this->isHardblock;
1152 }
1153
1154 /**
1155 * @param null|bool $x
1156 * @return bool
1157 */
1158 public function isAutoblocking( $x = null ) {
1159 wfSetVar( $this->isAutoblocking, $x );
1160
1161 # You can't put an autoblock on an IP or range as we don't have any history to
1162 # look over to get more IPs from
1163 return $this->getType() == self::TYPE_USER
1164 ? $this->isAutoblocking
1165 : false;
1166 }
1167
1168 /**
1169 * Indicates that the block is a sitewide block. This means the user is
1170 * prohibited from editing any page on the site (other than their own talk
1171 * page).
1172 *
1173 * @since 1.33
1174 * @param null|bool $x
1175 * @return bool
1176 */
1177 public function isSitewide( $x = null ) {
1178 return wfSetVar( $this->isSitewide, $x );
1179 }
1180
1181 /**
1182 * Get or set the flag indicating whether this block blocks the target from
1183 * creating an account. (Note that the flag may be overridden depending on
1184 * global configs.)
1185 *
1186 * @since 1.33
1187 * @param null|bool $x Value to set (if null, just get the property value)
1188 * @return bool Value of the property
1189 */
1190 public function isCreateAccountBlocked( $x = null ) {
1191 return wfSetVar( $this->blockCreateAccount, $x );
1192 }
1193
1194 /**
1195 * Get or set the flag indicating whether this block blocks the target from
1196 * sending emails. (Note that the flag may be overridden depending on
1197 * global configs.)
1198 *
1199 * @since 1.33
1200 * @param null|bool $x Value to set (if null, just get the property value)
1201 * @return bool Value of the property
1202 */
1203 public function isEmailBlocked( $x = null ) {
1204 return wfSetVar( $this->mBlockEmail, $x );
1205 }
1206
1207 /**
1208 * Get or set the flag indicating whether this block blocks the target from
1209 * editing their own user talk page. (Note that the flag may be overridden
1210 * depending on global configs.)
1211 *
1212 * @since 1.33
1213 * @param null|bool $x Value to set (if null, just get the property value)
1214 * @return bool Value of the property
1215 */
1216 public function isUsertalkEditAllowed( $x = null ) {
1217 return wfSetVar( $this->allowUsertalk, $x );
1218 }
1219
1220 /**
1221 * Determine whether the Block prevents a given right. A right
1222 * may be blacklisted or whitelisted, or determined from a
1223 * property on the Block object. For certain rights, the property
1224 * may be overridden according to global configs.
1225 *
1226 * @since 1.33
1227 * @param string $right Right to check
1228 * @return bool|null null if unrecognized right or unset property
1229 */
1230 public function appliesToRight( $right ) {
1231 $config = RequestContext::getMain()->getConfig();
1232 $blockDisablesLogin = $config->get( 'BlockDisablesLogin' );
1233
1234 $res = null;
1235 switch ( $right ) {
1236 case 'edit':
1237 // TODO: fix this case to return proper value
1238 $res = true;
1239 break;
1240 case 'createaccount':
1241 $res = $this->isCreateAccountBlocked();
1242 break;
1243 case 'sendemail':
1244 $res = $this->isEmailBlocked();
1245 break;
1246 case 'upload':
1247 // Until T6995 is completed
1248 $res = $this->isSitewide();
1249 break;
1250 case 'read':
1251 $res = false;
1252 break;
1253 case 'purge':
1254 $res = false;
1255 break;
1256 }
1257 if ( !$res && $blockDisablesLogin ) {
1258 // If a block would disable login, then it should
1259 // prevent any right that all users cannot do
1260 $anon = new User;
1261 $res = $anon->isAllowed( $right ) ? $res : true;
1262 }
1263
1264 return $res;
1265 }
1266
1267 /**
1268 * Get/set whether the Block prevents a given action
1269 *
1270 * @deprecated since 1.33, use appliesToRight to determine block
1271 * behaviour, and specific methods to get/set properties
1272 * @param string $action Action to check
1273 * @param bool|null $x Value for set, or null to just get value
1274 * @return bool|null Null for unrecognized rights.
1275 */
1276 public function prevents( $action, $x = null ) {
1277 $config = RequestContext::getMain()->getConfig();
1278 $blockDisablesLogin = $config->get( 'BlockDisablesLogin' );
1279 $blockAllowsUTEdit = $config->get( 'BlockAllowsUTEdit' );
1280
1281 $res = null;
1282 switch ( $action ) {
1283 case 'edit':
1284 # For now... <evil laugh>
1285 $res = true;
1286 break;
1287 case 'createaccount':
1288 $res = wfSetVar( $this->blockCreateAccount, $x );
1289 break;
1290 case 'sendemail':
1291 $res = wfSetVar( $this->mBlockEmail, $x );
1292 break;
1293 case 'upload':
1294 // Until T6995 is completed
1295 $res = $this->isSitewide();
1296 break;
1297 case 'editownusertalk':
1298 // NOTE: this check is not reliable on partial blocks
1299 // since partially blocked users are always allowed to edit
1300 // their own talk page unless a restriction exists on the
1301 // page or User_talk: namespace
1302 wfSetVar( $this->allowUsertalk, $x === null ? null : !$x );
1303 $res = !$this->isUsertalkEditAllowed();
1304
1305 // edit own user talk can be disabled by config
1306 if ( !$blockAllowsUTEdit ) {
1307 $res = true;
1308 }
1309 break;
1310 case 'read':
1311 $res = false;
1312 break;
1313 case 'purge':
1314 $res = false;
1315 break;
1316 }
1317 if ( !$res && $blockDisablesLogin ) {
1318 // If a block would disable login, then it should
1319 // prevent any action that all users cannot do
1320 $anon = new User;
1321 $res = $anon->isAllowed( $action ) ? $res : true;
1322 }
1323
1324 return $res;
1325 }
1326
1327 /**
1328 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
1329 * @return string Text is escaped
1330 */
1331 public function getRedactedName() {
1332 if ( $this->mAuto ) {
1333 return Html::element(
1334 'span',
1335 [ 'class' => 'mw-autoblockid' ],
1336 wfMessage( 'autoblockid', $this->mId )->text()
1337 );
1338 } else {
1339 return htmlspecialchars( $this->getTarget() );
1340 }
1341 }
1342
1343 /**
1344 * Get a timestamp of the expiry for autoblocks
1345 *
1346 * @param string|int $timestamp
1347 * @return string
1348 */
1349 public static function getAutoblockExpiry( $timestamp ) {
1350 global $wgAutoblockExpiry;
1351
1352 return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry );
1353 }
1354
1355 /**
1356 * Purge expired blocks from the ipblocks table
1357 */
1358 public static function purgeExpired() {
1359 if ( wfReadOnly() ) {
1360 return;
1361 }
1362
1363 DeferredUpdates::addUpdate( new AutoCommitUpdate(
1364 wfGetDB( DB_MASTER ),
1365 __METHOD__,
1366 function ( IDatabase $dbw, $fname ) {
1367 $ids = $dbw->selectFieldValues( 'ipblocks',
1368 'ipb_id',
1369 [ 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
1370 $fname
1371 );
1372 if ( $ids ) {
1373 $blockRestrictionStore = MediaWikiServices::getInstance()->getBlockRestrictionStore();
1374 $blockRestrictionStore->deleteByBlockId( $ids );
1375
1376 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], $fname );
1377 }
1378 }
1379 ) );
1380 }
1381
1382 /**
1383 * Given a target and the target's type, get an existing Block object if possible.
1384 * @param string|User|int $specificTarget A block target, which may be one of several types:
1385 * * A user to block, in which case $target will be a User
1386 * * An IP to block, in which case $target will be a User generated by using
1387 * User::newFromName( $ip, false ) to turn off name validation
1388 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
1389 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
1390 * usernames
1391 * Calling this with a user, IP address or range will not select autoblocks, and will
1392 * only select a block where the targets match exactly (so looking for blocks on
1393 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
1394 * @param string|User|int|null $vagueTarget As above, but we will search for *any* block which
1395 * affects that target (so for an IP address, get ranges containing that IP; and also
1396 * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
1397 * @param bool $fromMaster Whether to use the DB_MASTER database
1398 * @return Block|null (null if no relevant block could be found). The target and type
1399 * of the returned Block will refer to the actual block which was found, which might
1400 * not be the same as the target you gave if you used $vagueTarget!
1401 */
1402 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1403 list( $target, $type ) = self::parseTarget( $specificTarget );
1404 if ( $type == self::TYPE_ID || $type == self::TYPE_AUTO ) {
1405 return self::newFromID( $target );
1406
1407 } elseif ( $target === null && $vagueTarget == '' ) {
1408 # We're not going to find anything useful here
1409 # Be aware that the == '' check is explicit, since empty values will be
1410 # passed by some callers (T31116)
1411 return null;
1412
1413 } elseif ( in_array(
1414 $type,
1415 [ self::TYPE_USER, self::TYPE_IP, self::TYPE_RANGE, null ] )
1416 ) {
1417 $block = new Block();
1418 $block->fromMaster( $fromMaster );
1419
1420 if ( $type !== null ) {
1421 $block->setTarget( $target );
1422 }
1423
1424 if ( $block->newLoad( $vagueTarget ) ) {
1425 return $block;
1426 }
1427 }
1428 return null;
1429 }
1430
1431 /**
1432 * Get all blocks that match any IP from an array of IP addresses
1433 *
1434 * @param array $ipChain List of IPs (strings), usually retrieved from the
1435 * X-Forwarded-For header of the request
1436 * @param bool $isAnon Exclude anonymous-only blocks if false
1437 * @param bool $fromMaster Whether to query the master or replica DB
1438 * @return array Array of Blocks
1439 * @since 1.22
1440 */
1441 public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
1442 if ( $ipChain === [] ) {
1443 return [];
1444 }
1445
1446 $conds = [];
1447 $proxyLookup = MediaWikiServices::getInstance()->getProxyLookup();
1448 foreach ( array_unique( $ipChain ) as $ipaddr ) {
1449 # Discard invalid IP addresses. Since XFF can be spoofed and we do not
1450 # necessarily trust the header given to us, make sure that we are only
1451 # checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
1452 # Do not treat private IP spaces as special as it may be desirable for wikis
1453 # to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
1454 if ( !IP::isValid( $ipaddr ) ) {
1455 continue;
1456 }
1457 # Don't check trusted IPs (includes local squids which will be in every request)
1458 if ( $proxyLookup->isTrustedProxy( $ipaddr ) ) {
1459 continue;
1460 }
1461 # Check both the original IP (to check against single blocks), as well as build
1462 # the clause to check for rangeblocks for the given IP.
1463 $conds['ipb_address'][] = $ipaddr;
1464 $conds[] = self::getRangeCond( IP::toHex( $ipaddr ) );
1465 }
1466
1467 if ( $conds === [] ) {
1468 return [];
1469 }
1470
1471 if ( $fromMaster ) {
1472 $db = wfGetDB( DB_MASTER );
1473 } else {
1474 $db = wfGetDB( DB_REPLICA );
1475 }
1476 $conds = $db->makeList( $conds, LIST_OR );
1477 if ( !$isAnon ) {
1478 $conds = [ $conds, 'ipb_anon_only' => 0 ];
1479 }
1480 $blockQuery = self::getQueryInfo();
1481 $rows = $db->select(
1482 $blockQuery['tables'],
1483 array_merge( [ 'ipb_range_start', 'ipb_range_end' ], $blockQuery['fields'] ),
1484 $conds,
1485 __METHOD__,
1486 [],
1487 $blockQuery['joins']
1488 );
1489
1490 $blocks = [];
1491 foreach ( $rows as $row ) {
1492 $block = self::newFromRow( $row );
1493 if ( !$block->isExpired() ) {
1494 $blocks[] = $block;
1495 }
1496 }
1497
1498 return $blocks;
1499 }
1500
1501 /**
1502 * From a list of multiple blocks, find the most exact and strongest Block.
1503 *
1504 * The logic for finding the "best" block is:
1505 * - Blocks that match the block's target IP are preferred over ones in a range
1506 * - Hardblocks are chosen over softblocks that prevent account creation
1507 * - Softblocks that prevent account creation are chosen over other softblocks
1508 * - Other softblocks are chosen over autoblocks
1509 * - If there are multiple exact or range blocks at the same level, the one chosen
1510 * is random
1511 * This should be used when $blocks where retrieved from the user's IP address
1512 * and $ipChain is populated from the same IP address information.
1513 *
1514 * @param array $blocks Array of Block objects
1515 * @param array $ipChain List of IPs (strings). This is used to determine how "close"
1516 * a block is to the server, and if a block matches exactly, or is in a range.
1517 * The order is furthest from the server to nearest e.g., (Browser, proxy1, proxy2,
1518 * local-squid, ...)
1519 * @throws MWException
1520 * @return Block|null The "best" block from the list
1521 */
1522 public static function chooseBlock( array $blocks, array $ipChain ) {
1523 if ( $blocks === [] ) {
1524 return null;
1525 } elseif ( count( $blocks ) == 1 ) {
1526 return $blocks[0];
1527 }
1528
1529 // Sort hard blocks before soft ones and secondarily sort blocks
1530 // that disable account creation before those that don't.
1531 usort( $blocks, function ( Block $a, Block $b ) {
1532 $aWeight = (int)$a->isHardblock() . (int)$a->appliesToRight( 'createaccount' );
1533 $bWeight = (int)$b->isHardblock() . (int)$b->appliesToRight( 'createaccount' );
1534 return strcmp( $bWeight, $aWeight ); // highest weight first
1535 } );
1536
1537 $blocksListExact = [
1538 'hard' => false,
1539 'disable_create' => false,
1540 'other' => false,
1541 'auto' => false
1542 ];
1543 $blocksListRange = [
1544 'hard' => false,
1545 'disable_create' => false,
1546 'other' => false,
1547 'auto' => false
1548 ];
1549 $ipChain = array_reverse( $ipChain );
1550
1551 /** @var Block $block */
1552 foreach ( $blocks as $block ) {
1553 // Stop searching if we have already have a "better" block. This
1554 // is why the order of the blocks matters
1555 if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
1556 break;
1557 } elseif ( !$block->appliesToRight( 'createaccount' ) && $blocksListExact['disable_create'] ) {
1558 break;
1559 }
1560
1561 foreach ( $ipChain as $checkip ) {
1562 $checkipHex = IP::toHex( $checkip );
1563 if ( (string)$block->getTarget() === $checkip ) {
1564 if ( $block->isHardblock() ) {
1565 $blocksListExact['hard'] = $blocksListExact['hard'] ?: $block;
1566 } elseif ( $block->appliesToRight( 'createaccount' ) ) {
1567 $blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?: $block;
1568 } elseif ( $block->mAuto ) {
1569 $blocksListExact['auto'] = $blocksListExact['auto'] ?: $block;
1570 } else {
1571 $blocksListExact['other'] = $blocksListExact['other'] ?: $block;
1572 }
1573 // We found closest exact match in the ip list, so go to the next Block
1574 break;
1575 } elseif ( array_filter( $blocksListExact ) == []
1576 && $block->getRangeStart() <= $checkipHex
1577 && $block->getRangeEnd() >= $checkipHex
1578 ) {
1579 if ( $block->isHardblock() ) {
1580 $blocksListRange['hard'] = $blocksListRange['hard'] ?: $block;
1581 } elseif ( $block->appliesToRight( 'createaccount' ) ) {
1582 $blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?: $block;
1583 } elseif ( $block->mAuto ) {
1584 $blocksListRange['auto'] = $blocksListRange['auto'] ?: $block;
1585 } else {
1586 $blocksListRange['other'] = $blocksListRange['other'] ?: $block;
1587 }
1588 break;
1589 }
1590 }
1591 }
1592
1593 if ( array_filter( $blocksListExact ) == [] ) {
1594 $blocksList = &$blocksListRange;
1595 } else {
1596 $blocksList = &$blocksListExact;
1597 }
1598
1599 $chosenBlock = null;
1600 if ( $blocksList['hard'] ) {
1601 $chosenBlock = $blocksList['hard'];
1602 } elseif ( $blocksList['disable_create'] ) {
1603 $chosenBlock = $blocksList['disable_create'];
1604 } elseif ( $blocksList['other'] ) {
1605 $chosenBlock = $blocksList['other'];
1606 } elseif ( $blocksList['auto'] ) {
1607 $chosenBlock = $blocksList['auto'];
1608 } else {
1609 throw new MWException( "Proxy block found, but couldn't be classified." );
1610 }
1611
1612 return $chosenBlock;
1613 }
1614
1615 /**
1616 * From an existing Block, get the target and the type of target.
1617 * Note that, except for null, it is always safe to treat the target
1618 * as a string; for User objects this will return User::__toString()
1619 * which in turn gives User::getName().
1620 *
1621 * @param string|int|User|null $target
1622 * @return array [ User|String|null, Block::TYPE_ constant|null ]
1623 */
1624 public static function parseTarget( $target ) {
1625 # We may have been through this before
1626 if ( $target instanceof User ) {
1627 if ( IP::isValid( $target->getName() ) ) {
1628 return [ $target, self::TYPE_IP ];
1629 } else {
1630 return [ $target, self::TYPE_USER ];
1631 }
1632 } elseif ( $target === null ) {
1633 return [ null, null ];
1634 }
1635
1636 $target = trim( $target );
1637
1638 if ( IP::isValid( $target ) ) {
1639 # We can still create a User if it's an IP address, but we need to turn
1640 # off validation checking (which would exclude IP addresses)
1641 return [
1642 User::newFromName( IP::sanitizeIP( $target ), false ),
1643 self::TYPE_IP
1644 ];
1645
1646 } elseif ( IP::isValidRange( $target ) ) {
1647 # Can't create a User from an IP range
1648 return [ IP::sanitizeRange( $target ), self::TYPE_RANGE ];
1649 }
1650
1651 # Consider the possibility that this is not a username at all
1652 # but actually an old subpage (T31797)
1653 if ( strpos( $target, '/' ) !== false ) {
1654 # An old subpage, drill down to the user behind it
1655 $target = explode( '/', $target )[0];
1656 }
1657
1658 $userObj = User::newFromName( $target );
1659 if ( $userObj instanceof User ) {
1660 # Note that since numbers are valid usernames, a $target of "12345" will be
1661 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1662 # since hash characters are not valid in usernames or titles generally.
1663 return [ $userObj, self::TYPE_USER ];
1664
1665 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1666 # Autoblock reference in the form "#12345"
1667 return [ substr( $target, 1 ), self::TYPE_AUTO ];
1668
1669 } else {
1670 # WTF?
1671 return [ null, null ];
1672 }
1673 }
1674
1675 /**
1676 * Get the type of target for this particular block. Autoblocks have whichever type
1677 * corresponds to their target, so to detect if a block is an autoblock, we have to
1678 * check the mAuto property instead.
1679 * @return int Block::TYPE_ constant, will never be TYPE_ID
1680 */
1681 public function getType() {
1682 return $this->mAuto
1683 ? self::TYPE_AUTO
1684 : $this->type;
1685 }
1686
1687 /**
1688 * Get the target and target type for this particular Block. Note that for autoblocks,
1689 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1690 * in this situation.
1691 * @return array [ User|String, Block::TYPE_ constant ]
1692 * @todo FIXME: This should be an integral part of the Block member variables
1693 */
1694 public function getTargetAndType() {
1695 return [ $this->getTarget(), $this->getType() ];
1696 }
1697
1698 /**
1699 * Get the target for this particular Block. Note that for autoblocks,
1700 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1701 * in this situation.
1702 * @return User|string
1703 */
1704 public function getTarget() {
1705 return $this->target;
1706 }
1707
1708 /**
1709 * Get the block expiry time
1710 *
1711 * @since 1.19
1712 * @return string
1713 */
1714 public function getExpiry() {
1715 return $this->mExpiry;
1716 }
1717
1718 /**
1719 * Set the block expiry time
1720 *
1721 * @since 1.33
1722 * @param string $expiry
1723 */
1724 public function setExpiry( $expiry ) {
1725 $this->mExpiry = $expiry;
1726 }
1727
1728 /**
1729 * Get the timestamp indicating when the block was created
1730 *
1731 * @since 1.33
1732 * @return string
1733 */
1734 public function getTimestamp() {
1735 return $this->mTimestamp;
1736 }
1737
1738 /**
1739 * Set the timestamp indicating when the block was created
1740 *
1741 * @since 1.33
1742 * @param string $timestamp
1743 */
1744 public function setTimestamp( $timestamp ) {
1745 $this->mTimestamp = $timestamp;
1746 }
1747
1748 /**
1749 * Set the target for this block, and update $this->type accordingly
1750 * @param mixed $target
1751 */
1752 public function setTarget( $target ) {
1753 list( $this->target, $this->type ) = self::parseTarget( $target );
1754 }
1755
1756 /**
1757 * Get the user who implemented this block
1758 * @return User User object. May name a foreign user.
1759 */
1760 public function getBlocker() {
1761 return $this->blocker;
1762 }
1763
1764 /**
1765 * Set the user who implemented (or will implement) this block
1766 * @param User|string $user Local User object or username string
1767 */
1768 public function setBlocker( $user ) {
1769 if ( is_string( $user ) ) {
1770 $user = User::newFromName( $user, false );
1771 }
1772
1773 if ( $user->isAnon() && User::isUsableName( $user->getName() ) ) {
1774 throw new InvalidArgumentException(
1775 'Blocker must be a local user or a name that cannot be a local user'
1776 );
1777 }
1778
1779 $this->blocker = $user;
1780 }
1781
1782 /**
1783 * Set the 'BlockID' cookie to this block's ID and expiry time. The cookie's expiry will be
1784 * the same as the block's, to a maximum of 24 hours.
1785 *
1786 * @since 1.29
1787 *
1788 * @param WebResponse $response The response on which to set the cookie.
1789 */
1790 public function setCookie( WebResponse $response ) {
1791 // Calculate the default expiry time.
1792 $maxExpiryTime = wfTimestamp( TS_MW, wfTimestamp() + ( 24 * 60 * 60 ) );
1793
1794 // Use the Block's expiry time only if it's less than the default.
1795 $expiryTime = $this->getExpiry();
1796 if ( $expiryTime === 'infinity' || $expiryTime > $maxExpiryTime ) {
1797 $expiryTime = $maxExpiryTime;
1798 }
1799
1800 // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
1801 $expiryValue = DateTime::createFromFormat( 'YmdHis', $expiryTime )->format( 'U' );
1802 $cookieOptions = [ 'httpOnly' => false ];
1803 $cookieValue = $this->getCookieValue();
1804 $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
1805 }
1806
1807 /**
1808 * Unset the 'BlockID' cookie.
1809 *
1810 * @since 1.29
1811 *
1812 * @param WebResponse $response The response on which to unset the cookie.
1813 */
1814 public static function clearCookie( WebResponse $response ) {
1815 $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
1816 }
1817
1818 /**
1819 * Get the BlockID cookie's value for this block. This is usually the block ID concatenated
1820 * with an HMAC in order to avoid spoofing (T152951), but if wgSecretKey is not set will just
1821 * be the block ID.
1822 *
1823 * @since 1.29
1824 *
1825 * @return string The block ID, probably concatenated with "!" and the HMAC.
1826 */
1827 public function getCookieValue() {
1828 $config = RequestContext::getMain()->getConfig();
1829 $id = $this->getId();
1830 $secretKey = $config->get( 'SecretKey' );
1831 if ( !$secretKey ) {
1832 // If there's no secret key, don't append a HMAC.
1833 return $id;
1834 }
1835 $hmac = MWCryptHash::hmac( $id, $secretKey, false );
1836 $cookieValue = $id . '!' . $hmac;
1837 return $cookieValue;
1838 }
1839
1840 /**
1841 * Get the stored ID from the 'BlockID' cookie. The cookie's value is usually a combination of
1842 * the ID and a HMAC (see Block::setCookie), but will sometimes only be the ID.
1843 *
1844 * @since 1.29
1845 *
1846 * @param string $cookieValue The string in which to find the ID.
1847 *
1848 * @return int|null The block ID, or null if the HMAC is present and invalid.
1849 */
1850 public static function getIdFromCookieValue( $cookieValue ) {
1851 // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
1852 $bangPos = strpos( $cookieValue, '!' );
1853 $id = ( $bangPos === false ) ? $cookieValue : substr( $cookieValue, 0, $bangPos );
1854 // Get the site-wide secret key.
1855 $config = RequestContext::getMain()->getConfig();
1856 $secretKey = $config->get( 'SecretKey' );
1857 if ( !$secretKey ) {
1858 // If there's no secret key, just use the ID as given.
1859 return $id;
1860 }
1861 $storedHmac = substr( $cookieValue, $bangPos + 1 );
1862 $calculatedHmac = MWCryptHash::hmac( $id, $secretKey, false );
1863 if ( $calculatedHmac === $storedHmac ) {
1864 return $id;
1865 } else {
1866 return null;
1867 }
1868 }
1869
1870 /**
1871 * Get the key and parameters for the corresponding error message.
1872 *
1873 * @since 1.22
1874 * @param IContextSource $context
1875 * @return array
1876 */
1877 public function getPermissionsError( IContextSource $context ) {
1878 $params = $this->getBlockErrorParams( $context );
1879
1880 $msg = 'blockedtext';
1881 if ( $this->getSystemBlockType() !== null ) {
1882 $msg = 'systemblockedtext';
1883 } elseif ( $this->mAuto ) {
1884 $msg = 'autoblockedtext';
1885 } elseif ( !$this->isSitewide() ) {
1886 $msg = 'blockedtext-partial';
1887 }
1888
1889 array_unshift( $params, $msg );
1890
1891 return $params;
1892 }
1893
1894 /**
1895 * Get block information used in different block error messages
1896 *
1897 * @since 1.33
1898 * @param IContextSource $context
1899 * @return array
1900 */
1901 public function getBlockErrorParams( IContextSource $context ) {
1902 $blocker = $this->getBlocker();
1903 if ( $blocker instanceof User ) { // local user
1904 $blockerUserpage = $blocker->getUserPage();
1905 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
1906 } else { // foreign user
1907 $link = $blocker;
1908 }
1909
1910 $reason = $this->getReason();
1911 if ( $reason == '' ) {
1912 $reason = $context->msg( 'blockednoreason' )->text();
1913 }
1914
1915 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1916 * This could be a username, an IP range, or a single IP. */
1917 $intended = $this->getTarget();
1918 $systemBlockType = $this->getSystemBlockType();
1919 $lang = $context->getLanguage();
1920
1921 return [
1922 $link,
1923 $reason,
1924 $context->getRequest()->getIP(),
1925 $this->getByName(),
1926 $systemBlockType ?? $this->getId(),
1927 $lang->formatExpiry( $this->getExpiry() ),
1928 (string)$intended,
1929 $lang->userTimeAndDate( $this->getTimestamp(), $context->getUser() ),
1930 ];
1931 }
1932
1933 /**
1934 * Get Restrictions.
1935 *
1936 * Getting the restrictions will perform a database query if the restrictions
1937 * are not already loaded.
1938 *
1939 * @since 1.33
1940 * @return Restriction[]
1941 */
1942 public function getRestrictions() {
1943 if ( $this->restrictions === null ) {
1944 // If the block id has not been set, then do not attempt to load the
1945 // restrictions.
1946 if ( !$this->mId ) {
1947 return [];
1948 }
1949 $this->restrictions = $this->getBlockRestrictionStore()->loadByBlockId( $this->mId );
1950 }
1951
1952 return $this->restrictions;
1953 }
1954
1955 /**
1956 * Set Restrictions.
1957 *
1958 * @since 1.33
1959 * @param Restriction[] $restrictions
1960 * @return self
1961 */
1962 public function setRestrictions( array $restrictions ) {
1963 $this->restrictions = array_filter( $restrictions, function ( $restriction ) {
1964 return $restriction instanceof Restriction;
1965 } );
1966
1967 return $this;
1968 }
1969
1970 /**
1971 * Determine whether the block allows the user to edit their own
1972 * user talk page. This is done separately from Block::appliesToRight
1973 * because there is no right for editing one's own user talk page
1974 * and because the user's talk page needs to be passed into the
1975 * Block object, which is unaware of the user.
1976 *
1977 * The ipb_allow_usertalk flag (which corresponds to the property
1978 * allowUsertalk) is used on sitewide blocks and partial blocks
1979 * that contain a namespace restriction on the user talk namespace,
1980 * but do not contain a page restriction on the user's talk page.
1981 * For all other (i.e. most) partial blocks, the flag is ignored,
1982 * and the user can always edit their user talk page unless there
1983 * is a page restriction on their user talk page, in which case
1984 * they can never edit it. (Ideally the flag would be stored as
1985 * null in these cases, but the database field isn't nullable.)
1986 *
1987 * This method does not validate that the passed in talk page belongs to the
1988 * block target since the target (an IP) might not be the same as the user's
1989 * talk page (if they are logged in).
1990 *
1991 * @since 1.33
1992 * @param Title|null $usertalk The user's user talk page. If null,
1993 * and if the target is a User, the target's userpage is used
1994 * @return bool The user can edit their talk page
1995 */
1996 public function appliesToUsertalk( Title $usertalk = null ) {
1997 if ( !$usertalk ) {
1998 if ( $this->target instanceof User ) {
1999 $usertalk = $this->target->getTalkPage();
2000 } else {
2001 throw new InvalidArgumentException(
2002 '$usertalk must be provided if block target is not a user/IP'
2003 );
2004 }
2005 }
2006
2007 if ( $usertalk->getNamespace() !== NS_USER_TALK ) {
2008 throw new InvalidArgumentException(
2009 '$usertalk must be a user talk page'
2010 );
2011 }
2012
2013 if ( !$this->isSitewide() ) {
2014 if ( $this->appliesToPage( $usertalk->getArticleID() ) ) {
2015 return true;
2016 }
2017 if ( !$this->appliesToNamespace( NS_USER_TALK ) ) {
2018 return false;
2019 }
2020 }
2021
2022 // This is a type of block which uses the ipb_allow_usertalk
2023 // flag. The flag can still be overridden by global configs.
2024 $config = RequestContext::getMain()->getConfig();
2025 if ( !$config->get( 'BlockAllowsUTEdit' ) ) {
2026 return true;
2027 }
2028 return !$this->isUsertalkEditAllowed();
2029 }
2030
2031 /**
2032 * Checks if a block applies to a particular title
2033 *
2034 * This check does not consider whether `$this->isUsertalkEditAllowed`
2035 * returns false, as the identity of the user making the hypothetical edit
2036 * isn't known here (particularly in the case of IP hardblocks, range
2037 * blocks, and auto-blocks).
2038 *
2039 * @param Title $title
2040 * @return bool
2041 */
2042 public function appliesToTitle( Title $title ) {
2043 if ( $this->isSitewide() ) {
2044 return true;
2045 }
2046
2047 $restrictions = $this->getRestrictions();
2048 foreach ( $restrictions as $restriction ) {
2049 if ( $restriction->matches( $title ) ) {
2050 return true;
2051 }
2052 }
2053
2054 return false;
2055 }
2056
2057 /**
2058 * Checks if a block applies to a particular namespace
2059 *
2060 * @since 1.33
2061 *
2062 * @param int $ns
2063 * @return bool
2064 */
2065 public function appliesToNamespace( $ns ) {
2066 if ( $this->isSitewide() ) {
2067 return true;
2068 }
2069
2070 // Blocks do not apply to virtual namespaces.
2071 if ( $ns < 0 ) {
2072 return false;
2073 }
2074
2075 $restriction = $this->findRestriction( NamespaceRestriction::TYPE, $ns );
2076
2077 return (bool)$restriction;
2078 }
2079
2080 /**
2081 * Checks if a block applies to a particular page
2082 *
2083 * This check does not consider whether `$this->isUsertalkEditAllowed`
2084 * returns false, as the identity of the user making the hypothetical edit
2085 * isn't known here (particularly in the case of IP hardblocks, range
2086 * blocks, and auto-blocks).
2087 *
2088 * @since 1.33
2089 *
2090 * @param int $pageId
2091 * @return bool
2092 */
2093 public function appliesToPage( $pageId ) {
2094 if ( $this->isSitewide() ) {
2095 return true;
2096 }
2097
2098 // If the pageId is not over zero, the block cannot apply to it.
2099 if ( $pageId <= 0 ) {
2100 return false;
2101 }
2102
2103 $restriction = $this->findRestriction( PageRestriction::TYPE, $pageId );
2104
2105 return (bool)$restriction;
2106 }
2107
2108 /**
2109 * Find Restriction by type and value.
2110 *
2111 * @param string $type
2112 * @param int $value
2113 * @return Restriction|null
2114 */
2115 private function findRestriction( $type, $value ) {
2116 $restrictions = $this->getRestrictions();
2117 foreach ( $restrictions as $restriction ) {
2118 if ( $restriction->getType() !== $type ) {
2119 continue;
2120 }
2121
2122 if ( $restriction->getValue() === $value ) {
2123 return $restriction;
2124 }
2125 }
2126
2127 return null;
2128 }
2129
2130 /**
2131 * Check if the block should be tracked with a cookie.
2132 *
2133 * @since 1.33
2134 * @param bool $isAnon The user is logged out
2135 * @return bool The block should be tracked with a cookie
2136 */
2137 public function shouldTrackWithCookie( $isAnon ) {
2138 $config = RequestContext::getMain()->getConfig();
2139 switch ( $this->getType() ) {
2140 case self::TYPE_IP:
2141 case self::TYPE_RANGE:
2142 return $isAnon && $config->get( 'CookieSetOnIpBlock' );
2143 case self::TYPE_USER:
2144 return !$isAnon && $config->get( 'CookieSetOnAutoblock' ) && $this->isAutoblocking();
2145 default:
2146 return false;
2147 }
2148 }
2149
2150 /**
2151 * Check if the block prevents a user from resetting their password
2152 *
2153 * @since 1.33
2154 * @return bool The block blocks password reset
2155 */
2156 public function appliesToPasswordReset() {
2157 switch ( $this->getSystemBlockType() ) {
2158 case null:
2159 case 'global-block':
2160 return $this->isCreateAccountBlocked();
2161 case 'proxy':
2162 return true;
2163 case 'dnsbl':
2164 case 'wgSoftBlockRanges':
2165 return false;
2166 default:
2167 return true;
2168 }
2169 }
2170
2171 /**
2172 * Get a BlockRestrictionStore instance
2173 *
2174 * @return BlockRestrictionStore
2175 */
2176 private function getBlockRestrictionStore() : BlockRestrictionStore {
2177 return MediaWikiServices::getInstance()->getBlockRestrictionStore();
2178 }
2179 }