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