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